MVC框架实现登陆功能
1、jsp页面:index.jsp
1)、引入 JSTL core标签:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <c:set var="path" value="${pageContext.request.contextPath}"/>
2)、body主体:
<body> <center><h1>登陆页面</h1><hr> <form action="${path}/action/user/login" method="post"> <table> <tr><td>账号:</td><td><input type="text" name="uname"></td></tr> <tr><td>密码:</td><td><input type="password" name="passwd"></td></tr> <tr><td><input type="submit" value="登陆"></td><td><a href="${path}/register.jsp">还没注册</a></td></tr> </table> </form> </center> </body>
2、在web.xml页面设置
<!-- 框架只有一个Servlet来处理所有的请求,设置load-on-startup --> <servlet> <servlet-name>MVC</servlet-name> <servlet-class>my.mvc.ActionServlet</servlet-class> <!-- 多个包请用逗号隔开 --> <init-param> <param-name>packages</param-name> <param-value>com.ph.web</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>MVC</servlet-name> <url-pattern>/action/*</url-pattern> </servlet-mapping>
my.mvc.ActionServlet:是对action的url字符串做处理的
/**
* 核心控制器,定义了映射规则
* 业务处理方法入口,URI的映射逻辑:
* /action/XXX/xxxx -> [com.ph.web].XXXAction.xxxx(RequestContext rc)
*/
所以${path}/action/user/login:被解析为:[com.ph.web].UserAction.login(RequestContext rc)
3、实现 UserAction类的login方法:
/** * 登陆 * */ public void login(RequestContext rc) throws ServletException, IOException { String uname = rc.param("uname"); String passwd = rc.param("passwd"); User user = userService.validate(uname, passwd); if(user == null) { rc.reqAttr("msg", "账号或密码错误"); rc.forward("/index.jsp"); } else { rc.session().setAttribute("USER", user); rc.redirect(rc.contextPath() + "/action/user/listUser"); } }