标签:exception desc view contex 一个 ping des mod col
实现登陆页面拦截功能
首页,登陆页面允许随意进入,首页需要输入登陆信息之后再进入
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <a href="${pageContext.request.contextPath}/gologin">登陆页面</a> <a href="${pageContext.request.contextPath}/main">首页</a> </body> </html>
登陆页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>登陆页面</title> </head> <body> <form action="${pageContext.request.contextPath}/login" method="post"> 用户名:<input type="text" name="username"> 密码:<input type="text" name="password"> <input type="submit" value="提交"> </form> </body> </html>
首页
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>首页</h1> <span>${username} </span> <a href="${pageContext.request.contextPath}/goOut"> 注销</a> </body> </html>
controller
package com.wu.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpSession; /** * @author wuyimin * @create 2021-06-14-20:16 * @description */ @Controller public class LoginController { //登陆页面 @RequestMapping("/login") public String login(HttpSession session, String username, String password, Model model){ //把用户的信息存在session中 session.setAttribute("LoginInfo",username); //通过model传递数据给前端 model.addAttribute("username",username); return "main"; } //首页 @RequestMapping("/main") public String main(){ return "main"; } //转到login页面 @RequestMapping("/gologin") public String login(){ return "login"; } //注销 @RequestMapping("/goOut") public String goOut(HttpSession session){ session.removeAttribute("LoginInfo"); return "main"; } }
拦截器
public class MyInterceptor implements HandlerInterceptor { //返回true就执行下一个拦截器 ,放行 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session=request.getSession(); //登陆页面准许进入 if(request.getRequestURI().contains("login")){ return true; } //没有登陆信息的情况不给进首页 if(session.getAttribute("LoginInfo")!=null){ return true; } //发到登陆页面 request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response); return false; } //拦截日志 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
配置
<mvc:interceptors> <mvc:interceptor> <!--拦截所有请求--> <mvc:mapping path="/**"/> <bean class="com.wu.config.MyInterceptor"/> </mvc:interceptor> </mvc:interceptors>
标签:exception desc view contex 一个 ping des mod col
原文地址:https://www.cnblogs.com/wuyimin/p/14883199.html