📅  最后修改于: 2021-01-09 12:44:58             🧑  作者: Mango
在这种情况下,容器为每个用户创建一个会话ID,容器使用该ID来标识特定用户.HttpSession对象可以用于执行两项任务:
HttpServletRequest接口提供了两种获取HttpSession对象的方法:
在此示例中,我们在一个servlet的会话范围内设置属性,并从另一个servlet的会话范围获取该值。为了在会话范围内设置属性,我们使用了HttpSession接口的setAttribute()方法,并且为了获取属性,我们使用了getAttribute方法。
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
HttpSession session=request.getSession();
session.setAttribute("uname",n);
out.print("visit");
out.close();
}catch(Exception e){System.out.println(e);}
}
}
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
}
s1
FirstServlet
s1
/servlet1
s2
SecondServlet
s2
/servlet2