我周围很多同事是这样写的; view plaincopy to clipboardprint? HttpSession session = request.getSession(); // a new session created if no session exists,如果session不存在的话你又创建了一个! String user_name = session.getAttribute("user_name"); HttpSession session = request.getSession(); // a new session created if no session exists, 如果session不存在的话你又创建了一个! String user_name = session.getAttribute("user_name2");
view plaincopy to clipboardprint? /** * Check the given request for a session attribute of the given name. * Returns null if there is no session or if the session has no such attribute. * Does not create a new session if none has existed before! * @param request current HTTP request * @param name the name of the session attribute * @return the value of the session attribute, or <code>null</code> if not found */ public static Object getSessionAttribute(HttpServletRequest request, String name) { Assert.notNull(request, "Request must not be null"); HttpSession session = request.getSession(false); return (session != null ? session.getAttribute(name) : null); } /** * Check the given request for a session attribute of the given name. * Returns null if there is no session or if the session has no such attribute. * Does not create a new session if none has existed before! * @param request current HTTP request * @param name the name of the session attribute * @return the value of the session attribute, or <code>null</code> if not found */ public static void setSessionAttribute(HttpServletRequest request, String name, Object value) { Assert.notNull(request, "Request must not be null"); if(value != null) { request.getSession().setAttribute(name, value); } else { HttpSession session = request.getSession(false); if(session != null) session.removeAttribute(name); } } 注:Assert是Spring工具包中的一个工具,用来判断一些验证操作,本例中用来判断reqeust是否为空,若为空就抛异常。
上面的代码又可以简洁一下啦,看吧:
view plaincopy to clipboardprint? String user_name = WebUtils.getSessionAttribute(reqeust, "user_name");