不关闭客户端,关闭服务器端后再启动服务器端,两次获取的session是同一个吗?
程序员文章站
2022-07-15 14:04:07
...
情景描述:情况大概是这样的,在一个JSP页面中,通过表单提交数据给AServlet处理,该Servlet需要从表单中获取数据,并存入session中,如果在此时,把服务器端正常关闭,然后重新启动服务器端,那么这一次获得session和上一次是同一个session吗,第一次表单中获取到的数据还会保存吗?
需要写一个简单JSP页面【以A.jsp为例】和一个简单的Servlet【SomeServlet.java为例】。代码如下:
A.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="SomeServlet" method="post">
姓名:<input type="text" value="" name="name">
<input type="submit" value="提交">
</form>
</body>
</html>
SomeServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class SomeServlet
*/
@WebServlet("/SomeServlet")
public class SomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public SomeServlet() {
super();
// TODO Auto-generated constructor stub
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(req,resp);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
String username=request.getParameter("name");
//String username="hello test!";
HttpSession session=request.getSession();
session.setAttribute("username", username);
PrintWriter out=response.getWriter();
out.println("SomeServlet Session: "+ session);
out.println("SomeServelt username: "+ username);
}
}
结果:
1.输入->提交
2.跳转到SomeServlet
3.关闭服务器
4.重启服务器
5.刷新客户端的页面
6.可以非常明显的看到两次的session不是同一个,但是获取到的表单值是一样的。