Springboot从入门到放弃之完整登录流程(含拦截器)

  1. 首先将登录界面 Login.html 放在resources下的templates下:

     <!DOCTYPE html>
     <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
     <head>
     <meta charset="UTF-8">
     <title>登录</title>
     <link rel="stylesheet"  type="text/css"  href="/static/css/loginstyle.css"/>
    
     </head>
     <body>
    
     <div id="particles-js">
     	 <form  class="login" action="home.html"th:action="@{/user}" method="post">   //注意这里,请求路径为/user, 方式为post
     		<div class="login">
                 <div class="login-top">
            			 <h1 th:text="#{login.tip}"></h1>
        		 	</div>
    
        	 		<div class="login-center clearfix">
             			<div class="login-center-img"><img src="/static/images/name.png"/></div>
             			<div class="login-center-input">
                				 <input type="text"  name="username" value="" placeholder="请输入您的用户名" onfocus="this.placeholder=''" onblur="this.placeholder='请输入您的用户名'"/>
                				 <div class="login-center-input-text">用户名</div>
            			 </div>
         		</div>
         		<div class="login-center clearfix">
             		<div class="login-center-img"><img src="/static/images/password.png"/></div>
             		<div class="login-center-input">
                  		<input type="password" name="password" value="" placeholder="请输入您的密码" onfocus="this.placeholder=''" onblur="this.placeholder='请输入您的密码'"/>
                 		<div class="login-center-input-text">密码</div>
             		</div>
         	 	</div>
    
         		<div style="text-align: center; margin-left: 5px; margin-top: 20px">
         		//判断msg里面有没有值
             		<p style="color: #009688; text-align: center;" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
             		
             		<button type="submit" class="login-button"> 登录 </button>   //表单submit
         		</div>
    
         		<div style="text-align: center; margin-left: 5px; margin-top: 20px">
         			//手动切换中文
             		<a   th:href="@{/login.html(l='ch_CN')}">中文</a>
        		 </div>
         		<div style="text-align: center; margin-left: 5px; margin-top: 20px">
         		     //手动切换英文
            			 <a  th:href="@{/login.html(l='en_US')}">English</a>
         		</div>
     		</div>
     	</form>
       </div>
      </body>
     </html>
    
  2. 配置controller

     @Controller
     public class LoginController {
     	//映射到处理方法
     	@PostMapping("/user")
     	public String login(@RequestParam("username")String username,
                    @RequestParam("password")String password,
                    Map<String,Object> map,
                    HttpSession session)
     {
    			if(!StringUtils.isEmpty(username)&&"123456".equals(password))
    			{
    				//在session里将用户名保存
        			session.setAttribute("loginUser",username);
        			session.setAttribute("age",20);
        			//防止表单重复提交
        			//main.html 相当于一个中间变量,配置映射实际返回到home.html:
        			// registry.addViewController("/main.html").setViewName("home"); 
       			 return "redirect:/main.html";     
    
    			}
     		   else
    			{
       			 map.put("msg","用户名密码错误");
        			 return "login";
    			}
    	 }
     }
    
  3. 写拦截器:

     /**
     	*登录拦截
      */
     @Component
     public class LoginInterception implements HandlerInterceptor {
    
      @Override
      public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
     		HttpSession session = request.getSession();
    			String uri = request.getRequestURI();
     		System.out.println("filter url:"+uri);
     		System.out.println("----------开始进行拦截-----------");
     		if (session.getAttribute("loginUser") != null) {
         			System.out.println("-----------拦截通过----------");
         			return true;
     		}else {
         		System.out.println("-----------拦截不通过----------");
         		// 跳转到登录界面login.html
         		String url = request.getContextPath() + "/login.html";
         		response.sendRedirect(url);
         		return false;
    		 }
    
     	}
    
  4. 配置拦截器

     @Configuration
     public class MyConfig implements WebMvcConfigurer  {
    
     @Bean
     public WebMvcConfigurer webMvcConfigurer() {
    
     //该方法为配置映射
     WebMvcConfigurer webMvcConfigurer = new WebMvcConfigurer() {
         @Override
         public void addViewControllers(ViewControllerRegistry registry) {
             registry.addViewController("/login").setViewName("Login");
             registry.addViewController("/login.html").setViewName("Login");
             registry.addViewController("/main.html").setViewName("home"); 
    
         	}
     	};
     	return webMvcConfigurer;
      }
    
     //该方法为配置静态文件
     @Override
     public void addResourceHandlers(ResourceHandlerRegistry registry)
     {
     	registry.addResourceHandler("/static/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX+"/static/");
      }
    
     @Override
     public void addInterceptors(InterceptorRegistry registry){
     		registry.addInterceptor(new LoginInterception()).addPathPatterns("/**")
          			.excludePathPatterns("/login.html","/login","/user","/static/css/loginstyle.css");
          			//静态文件也需要被排除
          		    //路径不能写大写
     }
    
     //该方法为配置国际化
     @Bean
     public LocaleResolver myLocaleResolver(){
    	return new MyLocaleResolver();
     	}
     }
    
  5. 效果就是: 未登录就访问main.html 是不行的,会直接回到login.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值