Signin Template for Bootstrap
注意请求路径使用的thymeleaf标签th:action=“@{/user/login}”
还有消息返回提示是判断msg是否存在的strings工具类的使用及逻辑运算符not的使用${not #strings }
package com.zk.controller;
import com.zk.constant.Constant;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpSession;
/**
* @author CNCLUKZK
* @create 2022/7/31-23:44
*/
@Controller
@RequestMapping("/user")
public class LoginController {
@RequestMapping("/login")
public String toLogin(@RequestParam("username") String username, @RequestParam("password") String password, Model model
, HttpSession session){
if (StringUtils.hasText(username)&&password.contains("123")){
// 登录成功,将用户信息保存到session对象中
session.setAttribute(Constant.Session_user,username);
return "redirect:/main";
}else {
model.addAttribute("msg","登陆信息有误!");
return "index";
}
}
@RequestMapping("/loginOut")
public String loginOut(HttpSession session){
// 清除 session
session.removeAttribute(Constant.Session_user);
//退出操作,重定向到登陆页面
return "redirect:/index";
}
}
@Configuration
public class MyMvcConfiguration implements WebMvcConfigurer {
//视图跳转
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//浏览器发送特殊请求,就会跳转到特定页面
registry.addViewController("/").setViewName("index");
registry.addViewController("/index").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
registry.addViewController("/main").setViewName("dashboard");
}
}
package com.zk.config;
import com.zk.constant.Constant;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author CNCLUKZK
* @create 2022/8/2-12:54
*/
public class MyHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String username = (String)request.getSession().getAttribute(Constant.Session_user);
if (StringUtils.hasText(username)) {
return true;
}
request.setAttribute("msg","没有登陆权限!");
request.getRequestDispatcher("/index").forward(request,response);
return false;
}
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/user/login"
,"/","/asserts/**","/index");
}