案例需求:编写一个servlet,可以向session中存放一个消息,再编写一个servlet可以从session取得session中存放的这个消息。
案例实现:
package com.xdl.servlet;
import java.io.IOException;
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;
@WebServlet("/addSessionData.do")
public class XdlCreateSession extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//如何获取session 对象
HttpSession session = request.getSession();
session.setAttribute("msg", "java是目前应用最广泛的语言");
}
}
package com.xdl.servlet;
import java.io.IOException;
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;
@WebServlet("/getSessionData.do")
public class GetSessionDataServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
//从session 对象中获取数据
String msg = (String)session.getAttribute("msg");
System.out.println("msg=" + msg);
}
}