JAVA中JSP的会话跟踪(一)
程序员文章站
2022-03-14 23:49:32
...
会话跟踪技术是一种在客户端与服务器间保持HTTP状态的解决方案。从开发角度考虑,是使上一次请求所传递的数据能够维持状态到下一次请求,并且辨认出是否相同的客户端所发送出来的 。今天和大家讲的是会话跟踪技术中的Cookie和Session技术。
先建一个login的HTML页面
<%@ 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>Insert title here</title>
</head>
<body>
<%-- <%
String error=(String)request.getAttribute("error");
if(error != null){
out.print(error);
}
%> --%>
<%
Cookie[] cooks = request.getCookies();
String name="";
String pass="";
if(cooks != null){
for(Cookie c:cooks){
if("username".equals(c.getName())){
name=c.getValue();
}
if("password".equals(c.getName())){
pass=c.getValue();
}
}
}
%>
<%
String url = response.encodeURL("logServlet");
%>
<form action="<%=url %>" method="post">
<p>用户名:<input name="username" type="text" value="<%=name%>"/></p>
<!-- <p>用户名:<input name="username" type="text"/></p> -->
<p>密 码:<input name="password" type="password" value="<%=pass%>"/></p>
<p><input name="button" type="submit" value="登录"/></p>
</form>
</body>
</html>
再建一个loginServlet
package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/logServlet")
public class LogServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name= request.getParameter("username");
String pass= request.getParameter("password");
if(name !=null&& pass!=null){
Cookie unameCookie = new Cookie("username", name);//创建对象
unameCookie.setMaxAge(60);//设置Cookie生命周期
Cookie upassCookie = new Cookie("password", pass);
upassCookie.setMaxAge(60*60);
response.addCookie(unameCookie);
response.addCookie(upassCookie);
HttpSession session=request.getSession();
session.setAttribute("name", name);
String url=response.encodeRedirectUrl("main.jsp");
response.sendRedirect(url);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
结果如下:
登录时:
登录后:
再回到login页面不断刷新,用户名和密码被保存在Cookie中,此技术用于实现登录时类似记住密码的功能。