cookie:将数据储存在客户端。 session:将数据储存在服务端,较安全
携带sevlet a 的数据,来访问sevlet b。
@WebServlet("/a")
public class se extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, ServletException {
//super.doGet(req, resp);
// List<brands> brand=new ArrayList<>();
// brand.add(new brands(1,"三只松鼠","三只松鼠"));
// brand.add(new brands(2,"优衣库","优衣库"));
//
// req.setAttribute("brands",brand);
//
// req.getRequestDispatcher("src/main/webapp/index.jsp").forward(req,resp);
Cookie cookies=new Cookie("us","dd");
resp.addCookie(cookies);
}
@WebServlet("/b")
public class s extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//super.doGet(req, resp);
Cookie[] cookies=req.getCookies();
for(Cookie cookie:cookies){
String name=cookie.getName();
if("us".equals(name)){
String value=cookie.getValue();
System.out.println(name+value);
break;
}
}
}
细节:储存中文即cookie的存活时间
@WebServlet("/a")
public class se extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, ServletException {
Cookie cookies=new Cookie("us","dd");
cookies.setMaxAge(60*60*24*7);//设置cookie的存活时间,即记住数据多久
String value="张三";
value= URLEncoder.encode(value,"UTF-8");//储存中文
System.out.println(value);
resp.addCookie(cookies);
}
session
@WebServlet("/session1")
public class session1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//super.doGet(req, resp);
HttpSession session=req.getSession();
session.setAttribute("username","doudou");
}
@WebServlet("/session2")标签:cookies,ServletException,resp,req,cookie,doGet From: https://www.cnblogs.com/doudou666/p/16620713.html
public class session2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doGet(req, resp);
HttpSession session=req.getSession();
Object username=session.getAttribute("username");
System.out.println(username);
}