SpringBootWeb开发-登录和拦截器实现
引言:实现拦截器功能,这里是通过session的方式,在登录请求发起的时候,通过往请求里添加session,request.getSession().setAttribute("loginUser","登录成功");然后再获取session的方式实现拦截器,登录成功,那么session就会放进去,然后获取session,看session是否存在,如果存在就登录成功,否则就登录失败,跳转到登录页。session的详解可以参考前面的博客Java中session的详解。
步骤:
1.首先要在前端html页面的form表单中指定提交的地址和请求类型,也就是表单中的th:action和method
1 <body class="text-center"> 2 <form class="form-signin" action="dashboard.html" th:action="@{/user/login}" method="post"> 3 <img class="mb-4" th:src="@{/asserts/img/bootstrap-solid.svg}" src="asserts/img/bootstrap-solid.svg" alt="" width="72" height="72"> 4 <h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign inh1> 5 6 <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}">p> 7 <label class="sr-only" th:text="#{login.username}">Usernamelabel> 8 <input type="text" name="username" class="form-control" placeholder="Username" th:placeholder="#{login.username}" required="" autofocus=""> 9 <label class="sr-only" th:text="#{login.password}">Passwordlabel> 10 <input type="password" name="password" class="form-control" placeholder="Password" th:placeholder="#{login.password}" required="" autofocus=""> 11 <div class="checkbox mb-3"> 12 <label> 13 <input type="checkbox" value="remember-me"> [[#{login.remember}]] 14 label> 15 div> 16 <button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">Sign inbutton> 17 <p class="mt-5 mb-3 text-muted">? 2017-2018p> 18 <a class="btn btn-sm" th:href="@{/login.html(l='zh_CN')}">中文a> 19 <a class="btn btn-sm" th:href="@{/login.html(l='en_US')}">Englisha> 20 form> 21 body>
2.编写Controller层,代码解析看注释。这里所有的html页面都是通过thymeleaf模板引擎解析的
1 package com.xiaoma.springbootweb.controller; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.util.StringUtils; 5 import org.springframework.web.bind.annotation.PostMapping; 6 import org.springframework.web.bind.annotation.RequestParam; 7 8 import javax.servlet.http.HttpServletRequest; 9 import java.util.Map; 10 11 @Controller 12 public class LoginController { 13 //PostMapping可以直接发post请求 14 @PostMapping(value = "/user/login") 15 //通过RequestParam获取用户名和密码,map里用来存放错误信息 16 public String login(@RequestParam("username") String username, 17 @RequestParam("password") String password, 18 Mapmap, HttpServletRequest request){ 19 //如果用户名不为空并且密码为123456则登录成功,否则登录失败并给出错误提示 20 if(!StringUtils.isEmpty(username)&&"123456".equals(password)){ 21 request.getSession().setAttribute("loginUser","登录成功"); 22 //为了防止表单重复提交,这里用重定向,这里的main.html通过MyMvcConfig中的视图映射,会将页面跳转到templates下的dashboard.html页面 23 return "redirect:/main.html"; 24 } 25 else{ 26 map.put("msg","用户名或者密码错误"); 27 return "login"; 28 } 29 } 30 }
3.编写拦截器
1 package com.xiaoma.springbootweb.component; 2 3 import org.springframework.web.servlet.HandlerInterceptor; 4 import org.springframework.web.servlet.ModelAndView; 5 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 9 public class LoginHandlerInterceptor implements HandlerInterceptor { 10 @Override 11 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 12 Object user=request.getSession().getAttribute("loginUser"); 13 System.out.println("获取的session为"+user); 14 if(user==null){ 15 //设置登录失败的提示信息 16 request.setAttribute("msg","没有权限,请先登录"); 17 //登录失败,返回登陆页面 18 request.getRequestDispatcher("/index.html").forward(request,response); 19 return false; 20 } 21 else{ 22 //登录成功,进入后台 23 return true; 24 } 25 } 26 27 @Override 28 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { 29 HandlerInterceptor.super.postHandle(request, response, handler, modelAndView); 30 } 31 32 @Override 33 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { 34 HandlerInterceptor.super.afterCompletion(request, response, handler, ex); 35 } 36 }
4.在我们的MyMvcConfig.java页面注册拦截器
1 package com.xiaoma.springbootweb.config; 2 3 import com.xiaoma.springbootweb.component.LoginHandlerInterceptor; 4 import com.xiaoma.springbootweb.component.MyLocaleResolver; 5 import org.springframework.context.annotation.Bean; 6 import org.springframework.context.annotation.Configuration; 7 import org.springframework.web.servlet.LocaleResolver; 8 import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 9 import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; 10 import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 11 12 @Configuration 13 public class MyMvcConfig extends WebMvcConfigurerAdapter { 14 @Override 15 public void addViewControllers(ViewControllerRegistry registry) { 16 registry.addViewController("atguigu").setViewName("success"); 17 } 18 19 //通过bean注解将组件注册到loc容器中,让springmvc知道这个组件的存在 20 @Bean 21 //通过mvc视图解析器实现controller层的mapping映射功能 22 public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){ 23 WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() { 24 @Override 25 public void addViewControllers(ViewControllerRegistry registry) { 26 registry.addViewController("/").setViewName("login"); 27 registry.addViewController("/index.html").setViewName("login"); 28 registry.addViewController("/main.html").setViewName("dashboard"); 29 } 30 31 //注册登录拦截器 32 @Override 33 public void addInterceptors(InterceptorRegistry registry) { 34 registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**"). 35 excludePathPatterns("/","/index.html","/user/login"); 36 } 37 }; 38 return adapter; 39 } 40 41 @Bean 42 public LocaleResolver localeResolver(){ 43 return new MyLocaleResolver(); 44 } 45 }