package com.gxzy.servlet; 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 java.io.IOException; import java.io.PrintWriter; @WebServlet("/servlet1") public class servlet1 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //这个是第一次访问服务端,要和第二次产生访问的sessionID进行比较 //设置响应返回的数据格式和编码格式 resp.setContentType("text/html;charset=utf-8"); PrintWriter out = resp.getWriter(); //这里的sessionId不是服务端产生的,是第一次服务端产生之后,客户端就是 String sessionID = req.getSession().getId(); //在页面上输出 out.println("日俊访问服务端,服务端产生一个sessionID:"+sessionID+"<br>"); //servlet2 要和@web里面的一致 out.println("<a href='servlet2'>servlet2</a>"); } }
第二部分
package com.gxzy.servlet; 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 java.io.IOException; import java.io.PrintWriter; @WebServlet("/servlet2") public class servlet2 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=utf-8"); PrintWriter out = resp.getWriter(); String sessionID = req.getSession().getId(); out.println("第二访问服务端,服务端产生一个sessionID:"+sessionID+"<br>"); out.println("<a href='servlet1'>servlet1</a>"); } }