目的:
1.login.jsp登录界面
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <html> <head> <!-- Page title --> <title>imooc - Login</title> <!-- End of Page title --> </head> <body> <form action="dologin.jsp" method="post"> <label>用户名: </label> <input name="username" value="" /> <label>密码: </label> <input type="password" name="password" value=""> <input type="submit" value="登录" /> </form> </body> </html>
2.登录处理页面dologin.jsp
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; String username =""; String password =""; request.setCharacterEncoding("utf-8");//防止中文乱码 username = request.getParameter("username"); password = request.getParameter("password"); //如果用户和密码都等于admin,则登录成功 if("admin".equals(username)&&"admin".equals(password)) { session.setAttribute("loginUser", username); request.getRequestDispatcher("login_success.jsp").forward(request, response); } else { response.sendRedirect("login_failure.jsp"); } %>
3.登录成功跳转到login_success.jsp
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <html> <head> <!-- Page title --> <title>imooc - Login</title> <!-- End of Page title --> </head> <body> <% String loginUser = ""; if(session.getAttribute("loginUser")!=null) { loginUser = session.getAttribute("loginUser").toString(); } %> 欢迎您<font color="red"><%=loginUser%></font>,登录成功! </body> </html>
4.登录失败跳转到login_failure.jsp
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <html> <head> <!-- Page title --> <title>imooc - Login</title> <!-- End of Page title --> </head> <body> 登录失败!请检查用户或者密码!<br> <a href="login.jsp">返回登录</a> </body> </html>
5.效果