[学习笔记]springboot-国际化和拦截器

国际化:

1,自定义config类,实现接口 LocaleResolver

public class MylocaleResolver implements LocaleResolver {
    @Override

    //设置国际化
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        String param = httpServletRequest.getParameter("l");  //从浏览起端读取返回的参数
        Locale locale = Locale.getDefault();  //设置默认的地区
        if(!StringUtils.isEmpty(param)){
            String[] split = param.split("_");
            locale = new Locale(split[0],split[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, @Nullable HttpServletResponse httpServletResponse, @Nullable Locale locale) {
    }
}

2 在config类中返回该类对象,并注入容器@Bean

@Configuration
public class MyMvcConfig implements WebMvcConfigurer{

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {

        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
        registry.addViewController("/main.html").setViewName("dashboard");
    }

    @Bean    //自定义国际化配置,然后@bean放到容器中
    public LocaleResolver localeResolver(){
        return new MylocaleResolver();
    }
}

拦截器:

1 创建config类,实现HandlerInterceptor接口(其中loginUser是对应登录的controller,放到Model中的参数)

public class LoginHandlerInterceptor  implements HandlerInterceptor{
    //拦截器
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String user = (String) request.getSession().getAttribute("loginUser");
        if(user==null){
           request.setAttribute("msg","尚未登录,请先登录~");
           request.getRequestDispatcher("/index.html").forward(request,response);
           return false;
        }else{
            return true;
        }
    }

}

2 在config类中配置拦截器

@Configuration
public class MyMvcConfig implements WebMvcConfigurer{

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {

        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
        registry.addViewController("/main.html").setViewName("dashboard");
    }
    
   @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginHandlerInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/","/index.html","/user/login","/asserts/**");
    }
}

你可能感兴趣的:(springboot,java)