第一部分:程序结构
第二部分:页面的创建
1、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>主页</title> </head> <body> <form action="/mvc1/user/chklogin" method="post"> <table> <tr> <td>账号:</td> <td><input name="username" type="text"></td> </tr> <tr> <td>密码:</td> <td><input name="password" type="password"></td> </tr> <tr> <td></td> <td><input type="submit" value="登录"></td> </tr> </table> </form> ${error } </body> </html>
2、index.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>主页</title> </head> <body> ${username }: 欢迎登陆 </body> </html>
第三部分:编写controller
package cn.shxy.web.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/user") public class UserController { @RequestMapping("/login_show") public String login_show() { return "/login"; } @RequestMapping("/login") public String login(String username, String password, HttpServletRequest request) { if (username.equalsIgnoreCase("aaa") && password.equals("bbb")) { request.setAttribute("username", username); return "/index"; } request.setAttribute("error", "账号或密码有误!"); return "/login"; } @RequestMapping("/chklogin") public String chkLogin(User user,HttpServletRequest request){ if(user.getUsername().equals("aaa") && user.getPassword().equals("bbb")){ request.setAttribute("username", user.getUsername()); return "/index"; } request.setAttribute("error", "账号或密码有误!"); return "/login"; } }
第四部分:测试
地址栏输入路径:http://localhost:8080/mvc1/user/chklogin
时间: 2024-10-10 14:04:28