package com.ckm.controller;
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;
@Controller
public class LoginController {
@RequestMapping("/user/login")
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
Model model,
HttpSession session)
{
System.out.println(username+" -->"+password);
if (!StringUtils.isEmpty(username) && "123456".equals(password)){
session.setAttribute("loginUser",username);
return "redirect:/main.html";
}else {
model.addAttribute("msg","用户名或者密码错误!");
return "index";
}
}
}
package com.ckm.config;
import org.jetbrains.annotations.NotNull;
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(@NotNull HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//获取登陆成功后的Session
Object user = request.getSession().getAttribute("loginUser");
if (user == null){
//如果null则没有登陆,返回msg信息
request.setAttribute("msg","没有权限,请先登陆!");
//重定向到/index.html登陆页面
request.getRequestDispatcher("/index.html").forward(request,response);
//return false不放行
return false;
}else {
//return true放行
return true;
}
}
}
//重写WebMvcConfigurer接口中addInterceptors方法
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor())
//拦截所有请求
.addPathPatterns("/**")
//哪些请求不会被拦截 登陆页 -- 静态资源文件 static下的所有文件
.excludePathPatterns("/index.html","/","/user/login","/css/*","/js/**","/img/**");
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/weixin_44912902/article/details/123456655
内容来源于网络,如有侵权,请联系作者删除!