仅供参考
设置session值,根据自己的需求设置值
/** * 登入验证 * * @return */ @RequestMapping(value = "/loginCheck.htm", method = RequestMethod.POST) @ResponseBody public Response loginCheck(User user) { responseUtil = new Response(); List<User> list = userService.getUser(user); if (list != null && list.size() > 0) { this.getSession().setAttribute("user", list.get(0));//向session中填入登入信息 responseUtil.setStatusAndMessage(HttpStatus.HTTP_SUCCESS, "验证成功"); } return responseUtil; }
web.xml设置session时间
<!-- session60分钟时间 --> <session-config> <session-timeout>60</session-timeout> </session-config>
设置拦截器,可以在这里设置日志、权限、是否登入。下面是判断是否登入,如果没有登入就跳转登入页面
package com.springmvc.util.action; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Repository; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import com.springmvc.model.User; @Repository public class SystemInterceptor extends HandlerInterceptorAdapter{ /** * 访问前判断session是否有值,是否登入 */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); User user = (User)request.getSession().getAttribute("user"); if (user == null) { // 未登录 PrintWriter out = response.getWriter(); StringBuilder builder = new StringBuilder(); builder.append("<script type=\"text/javascript\" charset=\"UTF-8\">"); builder.append("alert(\"页面过期,请重新登录\");"); builder.append("window.top.location.href=\""); String basePath = String.valueOf(request.getAttribute("basePath")); builder.append(basePath+"101/login.htm\";</script>"); out.print(builder.toString()); out.close(); return false; } else { return true; } } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
在对应dispatcher-servlet.xml,也就是servlet中设置需要拦截的路径、不需要拦截的、拦截之后需要在哪个类中处理
<mvc:interceptors> <mvc:interceptor> <!-- 需拦截的地址 --> <!-- 一级目录 --> <mvc:mapping path="/*.do" /> <mvc:mapping path="/*.ajax" /> <mvc:mapping path="/*.htm" /> <!-- 二级目录 --> <mvc:mapping path="/*/*.do" /> <mvc:mapping path="/*/*.ajax" /> <mvc:mapping path="/*/*.htm" /> <!-- 需排除拦截的地址 --> <mvc:exclude-mapping path="/*/login.htm"/> <mvc:exclude-mapping path="/*/loginCheck.htm"/> <!-- 拦截之后处理类 --> <bean class="com.springmvc.util.action.SystemInterceptor" /> </mvc:interceptor> </mvc:interceptors>
可以在baseAction中添加session获取方法
public User getSessionObject(){ User user = (User)getRequest().getSession().getAttribute("user"); return user; }
时间: 2024-11-14 11:51:26