续 页面国际化
创建一个拦截器实现HandlerInterceptor接口
package com.xiaoyequ.config;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//登录成功,应该有用户的session
Object loginUser = request.getSession().getAttribute("loginUser");
if (loginUser == null) {
request.setAttribute("msg", "没有权限,清先登录");
request.getRequestDispatcher("/index.html").forward(request,response);
return false;
}else {
return true;
}
}
}
新建配置类来管理拦截器,并将之前的拦截器注入其中
package com.xiaoyequ.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
//扩展springmvc
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
// 拦截器配置
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor())
.addPathPatterns("/**") // 可以拦截所有请求
.excludePathPatterns("/index.html","/","/user/login","/css/**","/js/**","/img/**"); // 排除访问路径
}
}
同时控制类里:添加 HttpSession 对象
package com.xiaoyequ.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.util.StringUtils;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("user")
public class LoginController {
@RequestMapping("login")
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
Model model,
HttpSession session) {
if (!StringUtils.isEmpty(username) && "123123".equals(password)) {
session.setAttribute("loginUser", username);
return "redirect:/main.html";
} else {
model.addAttribute("msg", "用户名或密码错误");
return "index";
}
}
}
thymeleaf 中用
[[${session.loginUser}]]
接收