0

我的控制器类在 com.tps.sphbIntegration.controllers包中

我的 applicationContext.xml 文件在WEB-INF/spring/applicationContext.xml

在控制器类中:

@Controller
@RequestMapping("jsp")
public class SpringController {

@RequestMapping(value="register.html" , method = RequestMethod.POST)
public String enterSucess(@Valid Login login , BindingResult result , Map model,HttpSession session){

    if(result.hasErrors()){
        System.out.println("Error happened...");
        return "register";
    }else{

    System.out.println("I am an controller for get method of jsp/success.html ");
    login = (Login) model.get("login");
    session.setAttribute("empId", login.getEmpId()) ;
    session.setAttribute("empName", login.getEmpName()) ;
    session.setAttribute("empPassword", login.getEmpPassword()) ;
    //session.setAttribute("empGender", login.getGender()) ;
    //session.setAttribute("empType", login.getEmpType()) ;

    ApplicationContext factory = new ClassPathXmlApplicationContext("spring/applicationContext.xml");
    EmployeeDao dao=(EmployeeDao)factory.getBean("d");
    dao.saveEmployee(login);

    return "registerCheck";
    }

  }
}

执行时我得到了异常

java.io.FileNotFoundException: class path resource [spring/applicationContext.xml] cannot be opened because it does not exist

请帮我设置applicationContext.xml控制器中的路径或举例说明如何访问applicationContext.xml控制器。

4

4 回答 4

3

您必须告诉 servlet 上下文加载器侦听器在 web.xml 中哪里可以找到 Spring 应用程序上下文 XML 文件。您的错误向我表明您没有这样做。

如果您的 web.xml 中确实有它,请检查路径以查看它们是否正确。

如果路径正确,请打开 WAR 文件并查看 XML 是否丢失。也许您有部署和打包问题。

网络应用程序不应该这样调用:

ApplicationContext factory = new ClassPathXmlApplicationContext("spring/applicationContext.xml");

如果您的目录中有一个,这将起作用,但首选的习惯用法是使用:spring/applicationContext.xmlWEB-INF/classesContextLoaderListener

按照 DispatchServlet 使用 ContextLoaderListener

您应该在启动时为整个应用程序加载应用程序上下文,而不是为一个控制器加载,当然也不是每次客户端调用此 URL 时。启动时加载一次。

于 2013-01-18T11:03:39.713 回答
3
  1. 您的控制器可以实现BeanFactoryAware一个接口,通过该接口它可以访问应用程序上下文的现有实例。您不得自己创建应用程序上下文。

  2. 从您的代码中不太清楚您是否真的需要访问上下文:看起来您需要通过 Spring 的标准依赖注入机制将 DAO注入到您的控制器中。

于 2013-01-18T11:05:17.493 回答
2

我认为这是获得应用程序上下文访问权限的推荐方法:

@Autowired
private ApplicationContext applicationContext;

不需要以这种方式使用“* Aware”类。

于 2013-01-18T18:32:08.143 回答
-1

不不不,你可以这样做!同样,我看到您的类中有一个 ANNOTATION(@Controller),这意味着您的类已由 spring 管理,如果您在方法中创建另一个应用程序,则内存中有两个 ApplicationContext 实例。让你的类实现ApplicationContextAware的接口并重写setApplication方法,并添加一个私有成员ApplicationContext,然后在该方法中赋值

于 2013-01-18T12:21:29.690 回答