关于session

关于session,网上给出的定义为:

Session:在计算机中,尤其是在网络应用中,称为“会话控制”。Session对象存储特定用户会话所需的属性及配置信息。这样,当用户在应用程序的Web页之间跳转时,存储在Session对象中的变量将不会丢失,而是在整个用户会话中一直存在下去。当用户请求来自应用程序的 Web页时,如果该用户还没有会话,则Web服务器将自动创建一个 Session对象。当会话过期或被放弃后,服务器将终止该会话。Session 对象最常见的一个用法就是存储用户的首选项。例如,如果用户指明不喜欢查看图形,就可以将该信息存储在Session对象中。有关使用Session 对象的详细信息,请参阅“ASP应用程序”部分的“管理会话”。注意会话状态仅在支持cookie的浏览器中保留

1.设置session

java里面,可以给session添加自定义key,value(HttpServletRequest request 作为方法的输入参数)

HttpSession session = request.getSession();
session.setAttribute("usrid", userid);

2.取得session

session.getAttribute("username");
HttpSession session = request.getSession(); 
session.getAttribute("usrname");
复制代码
 public void doPost(HttpServletRequest request, HttpServletResponse response)  
            throws IOException, ServletException {  
         
        String userid = request.getParameter("username");
        String pwd = request.getParameter("password");
        
        JSONObject json = new JSONObject();  
        
        AdminDAO adminDAO = new AdminDAO();
        List<Admin> userList = adminDAO.findByProperty("usrid", userid);

        if(userList.get(0).getPassword().equals(pwd)){
             json.put("success", true);
             HttpSession session = request.getSession();
             session.setAttribute("usrid", userid);
        } else {
             json.put("success", false);
             json.put("meg", "sorry");
        }          
                 
        PrintWriter pw = response.getWriter();   
        pw.print(json.toString());  
        pw.close();  
    }  
复制代码
复制代码
public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        JSONObject json = new JSONObject();  
       
        HttpSession session = request.getSession(); 
        if(session==null||session.getAttribute("usrid")==null)
        {
             json.put("success", false);
             json.put("meg", "Time out,please login again!");
        }
        else
        {
           ...
            json.put("jsonArray", array);     
        }    
        
           
        PrintWriter pw = response.getWriter();   
        pw.print(json.toString());  
        pw.close();
    }
复制代码
复制代码
$(document).ready(function(){
            $.ajax({
                url: "HomePageServlet",
                type: "post",
                dataType: "json",
                success: function(data) {        
                if (data["success"]) {
                      ...
                } 
                else
                {
                    alert(data["meg"]);
                    window.location.href="login.html";
                }                            
            }
                
        });
    });
原文地址:https://www.cnblogs.com/9635741zly/p/14916710.html