本案例主要使用session实现登录与注销的功能。
1.登录页面
<%@ 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>
运行界面:
2.使用UserDao模拟数据库提供对外验证密码和密码是否正确的函数
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);
}
}
3.实现LoginServlet的代码,因为login.jsp是post的提交方式,这里为了方便我使用rrequest.setCharacterEncoding("utf-8");告诉服务器使用utf-8编码,这里向服务器输出了汉字,因此采用response.setContentType("text/html;charset=utf-8");来解决乱码问题....这句话两个作用...这里我就不介绍了、
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);
}
}
4.index.jsp如果没有登陆就欢迎光临游客!如果从session中查出用户就欢迎指定的用户
<%@ 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>
运行界面:
未登录:
登陆: