questMapping("/login")
public ModelAndView login(User user){
ModelAndView mv = new ModelAndView();
User u = userService.selectUserByUsernameAndPassword(user);
//根据用户名和密码查询user,如果存在,则跳转到 success.jsp 页面
if(u != null){
mv.addObject("username", u.getUsername());
mv.addObject("user", u);
mv.setViewName("view/success.jsp");
}else{
//如果不存在,则跳转到 login.jsp页面重新登录
return new ModelAndView("redirect:/login.jsp");
}
return mv;
}
}
④、加载 Spring 容器
我们在 classpath/spring 目录下新建了 spring-dao.xml,spring-service.xml,spring-transaction.xml 这些文件,里面有我们配置的 mapper,controller,service,那么如何将这些加载到 spring 容器中呢?
在 web.xml 文件中添加如下代码:
<!-- 加载spring容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
由于配置文件比较多,我们使用通配符加载的方式。注意:这段代码最好要加在前端控制器的前面。
至此 SSM 三大框架整合就完成了,接下来我们进行测试。
5、测试
在 WebContent 目录下创建 login.jsp 页面,以及 success.jsp页面,如下图:
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="login" method="post">
<label>账号:</label>
<input type="text" id="txtUsername" name="username" placeholder="请输入账号" /><br/>
<label>密码:</label>
<input type="password" id="txtPassword" name="password" placeholder="请输入密码" /><br/>
<input type="submit" value="提交" />
<input type="reset" value="重置" />
</form>
</body>
</html>
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
Hello ${user.username}
</body>
</html>
1、将项目发布到 tomcat,如何发布可以参考这篇博客:http://www.cnblogs.com/ysocean/p/6893446.html
2、在浏览器输入:http://localhost:8080/SSMDemo/login.jsp
点击提交: