八、在web容器中实例化spring容器、登录验证

  1. 在web容器中实例化spring容器,即在web.xml中配置spring容器的相关信息,tomcat读取web.xml的时候实例化spring容器,我们就不用去ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml")来获取spring容器,可以WebApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(this.getServlet().getServletContext())来加载spring容器,方便接下来的web层与spring的整合
<!-- 指定spring的配置文件,默认从web根目录寻找配置文件,我们可以通过spring提供的classpath:前缀指定从类路径下寻找 -->
      <context-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:applicationContext.xml</param-value>
      </context-param>
      
      <!-- 对spring容器进行实例化 -->
      <listener>
          <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>

  2.EmployeeServiceInterface中增加loginCheck函数,在

//登录验证,如果验证成功则返回该employee对象,否则返回空
    public Employee loginCheck(Employee e) {
        // TODO Auto-generated method stub
        String hql="from Employee where id=? and password=?";
        List<Employee> list = sessionFactory.getCurrentSession().createQuery(hql).setInteger(0, e.getId()).setString(1, e.getPassword()).list();
        if(list.size()>0) return list.get(0);
        else return null;
    }

  3.LoginAction中,修改login函数进行登录验证

public class LoginAction extends DispatchAction {
    
    public ActionForward login(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        // TODO Auto-generated method stub
        
        //web容器中加载spring容器,通过web路径获取spring容器实例
        WebApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(this.getServlet().getServletContext());
        //从spring容器中获取bean
        EmployeeServiceInterface esi=(EmployeeServiceInterface) ctx.getBean("employeeService");
        
        //使用类路径获取spring容器实例
//        ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
//        EmployeeServiceInterface esi=(EmployeeServiceInterface) ac.getBean("employeeService");
        EmployeeForm employeeForm=(EmployeeForm) form;
        
        
        Employee e=new Employee();
        e.setId(employeeForm.getId());
        e.setPassword(employeeForm.getPassword());

        Employee loginUser=esi.loginCheck(e);
        if(loginUser!=null){
            //登录成功则保存用户信息到session中
            request.getSession().setAttribute("loginUser", loginUser);
            return mapping.findForward("ok");
        }else{
            return mapping.findForward("err");
        }
    }
}

  

4.测试,发布运行后,输入正确的id和密码能够登录成功,否则登录失败

原文地址:https://www.cnblogs.com/myz666/p/8435794.html