<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title></title> <meta http-equiv=" pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> </head> <body> <form action="${pageContext.request.contextPath }/servlet/LoginServlet" method="post"> 登陆名:<input type="text" name="username"/><br/> 密码: <input type="password" name="password"/><br/> <input type="submit" value="提交"/><br/> </form> </body> </html>
package cn.itheima.loginout; import java.util.HashMap; import java.util.Map; public class UserDao { private static Map<String, String> map=new HashMap<String, String>(); static{ map.put("李卫康", "123"); } //提供验证用户名和密码的方法 public static boolean validateUsernamePassword(String username,String password){ return map.containsKey(username)&&map.get(username).equals(password); } }
package cn.itheima.loginout; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); //1.得到参数 String username = request.getParameter("username"); String password = request.getParameter("password"); //2.从数据库中查询并判断 if(UserDao.validateUsernamePassword(username, password)){ request.getSession().setAttribute("user", username); //重定向到主页、 response.sendRedirect(request.getContextPath()+"/loginout/index.jsp"); }else{ response.getWriter().write("对不起您没有登陆!三秒后跳转到登陆页面"); response.setHeader("Refresh", "3;url=/day05/loginout/login.jsp"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title></title> <meta http-equiv=" pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> </head> <body> <% String user=(String)session.getAttribute("user"); %> <% if(user==null||"".equals(user)){ %> 欢迎观临!游客! <a href="${pageContext.request.contextPath }/loginout/login.jsp">登录</a> <% }else{ %> 欢迎回来!<%=user %> <a href="${pageContext.request.contextPath }/servlet/LogoutServlet">注销</a> <% } %> </body> </html>运行界面:
未登录:
登陆:
原文:http://blog.csdn.net/u014010769/article/details/46565647