Spring Boot 登录拦截
重写拦截器方法,进行登录拦截!代码如下:
第一步:自定义拦截器 实现 HandlerInterceptor
package com.controller; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 自定义拦截器 * */ public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // HttpSession session = request.getSession(true); JSONObject jsonObject = JSON.parseObject(request.getParameter("params")); // String queryString = request.getQueryString(); // System.out.println(request.getParameterMap().get("params")); if(jsonObject.get("userName") == null){ response.sendRedirect(request.getContextPath() + "/index.xml"); 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 { } }
第二步:配置, 添加拦截到指定的URL
package com.Config; import com.controller.MyInterceptor; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class AddInterceptor extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry interceptorRegistry){ interceptorRegistry.addInterceptor(new MyInterceptor()).addPathPatterns("/login"); } }
第三步:controller
package com.controller; import com.VO.User; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController public class LoginController { @ApiOperation(value="登陆", notes="") @RequestMapping(value={"/login"}, method= RequestMethod.GET) public String login(@RequestParam(value = "params")String params) { return null; } @RequestMapping(value={"/getList"}, method= RequestMethod.POST) public List<User> getUserList() { return null; } }
最后: 前台调用即可!
走着 走着 就近了,所以不要停止前行!