Add interceptor a login (login test)

On login.html page, we form the post form by our request to the control layer;

<section class="loginCont">
        <!--在这个form表单之上我们添加一个if表达式,当其登录失误的时候对其进行处理-->
        <div th:if="${not #strings.isEmpty(msg)}"
        th:text="${msg}"
        style="color:red; margin-left: 130px"> <!--这里的话对控制层打印出的错误信息进行显示-->
        </div>
        <!--我们这里的话对login表单进行处理,提交一个login请求,把控制权交给控制器进行处理-->
        <form class="loginForm" th:action="@{/login}" th:method="post">

So we are here to write a login control layer of the page;

@Controller
public class LoginController {
    //这里以post方式提交,我们在html上的请求就会被提交到这里进行处理
    @PostMapping("/login")
    public String login(HttpSession session,
                        @RequestParam("username") String username,
                        @RequestParam("password") String password,
                        Map<String, Object> map) {
        if (!StringUtils.isEmpty(username) && "123".equals(password)) {
            //如果登录成功的话就进入到该if中,然后我们把该用户名保存到session中,
            // 然后我们到拦截器中对其进行获取
            session.setAttribute("username",username);
            //登录成功,防止表单重复提交,通过重定向到主页,需要添加一个视图
            return "redirect:/main.html";//这里相当于接收一个请求路径:到main路径下找html
        }
        //登录失败:我们把该字段写入到msg这个map中
        map.put("msg", "用户名或者是密码错误");
        return "/main/login";
    }
}

And a register to their interceptor: a write allowed to achieve HandlerInterceptor LoginHandlerInterceptor class interface and implementation inside The preHandle ;

  package com.siter.springboot01bill.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 这里写一个登录拦截器:然后实现一个拦截器接口,实现一下里面的方法
 * 这里只是注册一个拦截器,并没有对其进行添加到容器中
 */
public class LoginHandlerInterceptor implements HandlerInterceptor {

    /**
     * 调用目标方法之前被拦截:
     * 就是通过session中有没有用户名来判断是否有登录过,
     * 未登录过就进行拦截,
     * 故我们在登录的控制层对其进行一个登录名的获取
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //这里我们先用request对象获取到session,然后再获取到session中(getAttribute)保存好的值
        Object loginUser = request.getSession().getAttribute("username");
        if (loginUser!=null){
            //如果获取到的loginUser对象不为空,故已经进行了登录,故放行
            return true;
        }
        /**没有进行登录的话我们需要对其进行提示,
        并为其转发到登录页面(之所以选择转发的话,是因为转发可以带信息,重定向的话是直接修改了url地址)
         */
        //这里选择把信息也绑定到msg,到时候统一进行提示;
        request.setAttribute("msg","未登录,请先进行登录~");
        request.getRequestDispatcher("/index.html").forward(request,response);
        return false;
    }
}

Then we need to continue to be injected into the vessel at the interceptor springMVCconfig; and specify the intercepted request and we should not intercepted request: In this class we WebMvcConfigurer ctrl + o, choose to override the addInterceptors method; as follows:

package com.siter.springboot01bill.config;

import com.siter.springboot01bill.component.MyLocalResolver;
import com.siter.springboot01bill.interceptor.LoginHandlerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 我们使用该类来进行跳转到首页:让其访问localhost:8080就能进入首页
 */
@Configuration
public class MySpringMvcConfig {
    @Bean  //这里得注意加bean注入到容器中
    public WebMvcConfigurer webMvcConfigurer() {
        return new WebMvcConfigurer() {
            @Override //这里添加一个视图控制器,用来跳转到我们定制的首页
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("main/login");
                registry.addViewController("/index.html").setViewName("main/login");
                //通过执行的url跳转到指定的页面
                registry.addViewController("/main.html").setViewName("main/index");


            }
            //刚才只是定义了一个拦截器,然后我们这里把其装入到容器中
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(new LoginHandlerInterceptor())
                        //指定要拦截的请求:/**表示拦截所有请求
                        .addPathPatterns("/**")
                        //排除不需要拦截的请求
                        .excludePathPatterns("/index.html","/login","/")
                        //springboot2.0之后我们需要对静态文件路径手动进行排除~
                        .excludePathPatterns("/css/*","/img/*","/js/*");

            }
        };
    }

    //需要替换MVC自动配置类中区域解析器
    @Bean
    public LocaleResolver localeResolver() {
        return new MyLocalResolver();
    }
}
Published 37 original articles · won praise 12 · views 3975

Guess you like

Origin blog.csdn.net/z19950712/article/details/104412524