在servlet中创建和应用session

时间:2021-03-02 17:09:47

在servlet中创建和应用session

创建设置session

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;

public class setSession extends HttpServlet{

public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,
IOException{
HttpSession session=request.getSession();
//返回与当前request相关联的session,如果没有则在服务器端创建一个;
session.setAttribute("username","zhangjie");

response.getWriter().println("------setSession() is ok--------");
}
}

获取servlet

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;

public class getSession extends HttpServlet{

public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,
IOException{
HttpSession session=request.getSession();
//返回与当前request相关联的session,如果没有则在服务器端创建一个;
response.getWriter().println(session.getAttribute("username"));

resp.getWriter().println("------getSession() is ok--------");
}
}

session

jstl 获取session:${sessionScope.key}

jsp后台获取session:
String username = (String)request.getSession().getAttribute(“username”);