JSP&Servlet学习笔记----第4章

时间:2021-12-01 16:01:44

HTTP是基于请求/响应的无状态的通信协议。

使服务器记得此次请求与之后请求关系的方式,叫做会话管理。


隐藏域:由浏览器在每次请求时主动告知服务器多次请求间必要的信息。仅适用于一些简单的状态 管理,如在线问卷。

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;

/**
* Created by N3verL4nd on 2017/2/21.
*/
@WebServlet("/questionnaire")
public class HiddenFieldServlet extends HttpServlet {
private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
//response.setHeader("Content-Type", "text/html; charset=UTF-8");
//response.addHeader("Content-Type", "text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
out.println(
"<!DOCTYPE html>"
+ "<html>"
+"<head>"
+"<title>问卷调查</title>"
+"</head>"
+"<body>"
);
String page = request.getParameter("page");
out.println("<form action='questionnaire' method='post'>");
if (page == null){
out.println("问题一:<input type='text' name='p1q1' /><br />");
out.println("问题二:<input type='text' name='p1q2' /><br />");
out.println("<input type='submit' name='page' value='下一页' />");
}else if ("下一页".equals(page)){
String p1q1 = request.getParameter("p1q1");
String p1q2 = request.getParameter("p1q2");
out.println("问题三:<input type='text' name='p2q1' />");
out.println("<input type='hidden' name='p1q1' value='" + p1q1 + "' />");
out.println("<input type='hidden' name='p1q2' value='" + p1q2 + "' />");
out.println("<input type='submit' name='page' value='完成' />");
}else if ("完成".equals(page)){
out.println(request.getParameter("p1q1") + "<br />");
out.println(request.getParameter("p1q2") + "<br />");
out.println(request.getParameter("p2q1") + "<br />");
}
out.println("</form>");
out.println("</body>");
out.println("</html>");
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
}

cookie:

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 java.io.IOException;
import java.io.PrintWriter;

/**
* Created by N3verL4nd on 2017/2/23.
*/
@WebServlet(name = "SetServlet", urlPatterns = {"/setcookies.do"})
public class SetServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
for (int i = 0; i < 5; i++){
Cookie cookie = new Cookie(String.valueOf(i), "xiya");
response.addCookie(cookie);
}

response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("设置cookies" + "<br />");
out.println("<a href='showcookies.do'>showcookies</a>");
out.close();
}
}
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 java.io.IOException;import java.io.PrintWriter;/** * Created by N3verL4nd on 2017/2/23. */@WebServlet(name = "ShowServlet", urlPatterns = {"/showcookies.do"})public class ShowServlet extends HttpServlet {    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {    }    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        response.setContentType("text/html; charset=UTF-8");        PrintWriter out = response.getWriter();        out.println("<!DOCTYPE html>");        out.println("<html>");        out.println("<head>");        out.println("<title>显示Cookies</title>");        out.println("</head>");        out.println("<body>");        out.println("<body>");        out.println("<table>");        out.println("<tr>");        out.println("<th>Cookie Name</th>");        out.println("<th>Cookie Value</th>");        out.println("</tr>");        Cookie[] cookies = request.getCookies();        if(cookies != null){            for (Cookie cookie : cookies){                String key = cookie.getName();                String value = cookie.getValue();                out.println("<tr>");                out.println("<td>" + key + "</td>");                out.println("<td>" + value + "</td>");                out.println("</tr>");            }        }        out.println("</table>");        out.println("</body>");        out.println("</html>");    }}

url重写:其实就是GET请求参数的应用,当服务器响应浏览器上一次请求时,将某些相关信息以超链接方式响应给浏览器,超链接中包含参数信息。
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;

/**
* Created by N3verL4nd on 2017/2/22.
*/
@WebServlet(name = "SearchServlet", urlPatterns = {"/search.do"})
public class SearchServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>调查</title>");
out.println("</head>");
out.println("<body>");
String start = request.getParameter("start");
if (start == null){
start = "1";
}
int count = Integer.parseInt(start);
int begin = 10 * count - 9;
int end = 10 * count;

out.println("第 " + begin + " 到 " + end + " 搜索结果<br />");
out.println("<ul>");
for (int i = begin; i <= end; i++){
out.println("<li>搜索结果" + i + "</li>");
}
out.println("</ul>");
for (int i = 1; i < 10; i++){
if (i == count){
out.println(i);
continue;
}
out.println("<a href='search.do?start=" + i + "'>" + i + "</a>");
}
out.println("</body>");
out.println("</html>");
}
}

JSP&Servlet学习笔记----第4章

在Servlet/JSP中可以使用HttpSession来进行会话管理。

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;
import java.io.IOException;
import java.io.PrintWriter;

/**
* Created by N3verL4nd on 2017/2/22.
*/
@WebServlet(name = "SessionServlet", urlPatterns = {"/session.do"})
public class SessionServlet extends HttpServlet {

private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
out.println(
"<!DOCTYPE html>"
+ "<html>"
+"<head>"
+"<title>问卷调查</title>"
+"</head>"
+"<body>"
);
String page = request.getParameter("page");
out.println("<form action='session.do' method='post'>");
if (page == null){
out.println("问题一:<input type='text' name='p1q1' /><br />");
out.println("问题二:<input type='text' name='p1q2' /><br />");
out.println("<input type='submit' name='page' value='下一页' />");
}else if ("下一页".equals(page)){
String p1q1 = request.getParameter("p1q1");
String p1q2 = request.getParameter("p1q2");
HttpSession session = request.getSession();
System.out.println(session.getId());
session.setAttribute("p1q1", p1q1);
session.setAttribute("p1q2", p1q2);
out.println("问题三:<input type='text' name='p2q1' /><br />");
out.println("<input type='submit' name='page' value='完成' />");
}else if ("完成".equals(page)){
String p2q1 = request.getParameter("p2q1");
HttpSession session = request.getSession();
System.out.println(session.getId());
session.setAttribute("p2q1", p2q1);

out.println(session.getAttribute("p1q1") + "<br />");
out.println(session.getAttribute("p1q2") + "<br />");
out.println(session.getAttribute("p2q1") + "<br />");
}
out.println("</form>");
out.println("</body>");
out.println("</html>");
out.close();
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
}

如上所示,HttpSession是通过HttpServletRequest获得的,但是该实例存在于Web容器内。

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;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
* Created by N3verL4nd on 2017/2/23.
*/
@WebServlet(name = "SessionInfoServlet", urlPatterns = {"/SessionInfoServlet"})
public class SessionInfoServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html; charset=UTF-8");
HttpSession session = request.getSession();
//session.setMaxInactiveInterval(10);//多少秒失效
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>SessionInfoServlet</title>");
out.println("</head>");
out.println("<body>");

out.println("New Session:" + session.isNew() + "<br />");
out.println("Session ID:" + session.getId() + "<br />");
out.println("getCreationTime:" + new Date(session.getCreationTime()) + "<br />");
out.println("getLastAccessedTime:" + new Date(session.getLastAccessedTime()) + "<br />");
out.println("getRequestedSessionId:" + request.getRequestedSessionId() + "<br />");
out.println("isRequestedSessionIdFromURL:" + request.isRequestedSessionIdFromURL() + "<br />");
out.println("isRequestedSessionIdFromCookie:" + request.isRequestedSessionIdFromCookie() + "<br />");
out.println("isRequestedSessionIdValid:" + request.isRequestedSessionIdValid() + "<br />");
out.println("<br /><a href='" + response.encodeURL("SessionInfoServlet") + "'>刷新</a><br />");
}
}

对于以上程序,我们使用Fiddler抓包观察下:

JSP&Servlet学习笔记----第4章JSP&Servlet学习笔记----第4章JSP&Servlet学习笔记----第4章

JSP&Servlet学习笔记----第4章


第一次调用该Servlet会返回Set-Cookie,第二次调用我们会向HTTP服务器发送该cookie来获取Web容器内对应的HttpSession。