基础版
controller
package com.web.management.controller;
import com.web.management.pojo.Emp;
import com.web.management.pojo.Result;
import com.web.management.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@Slf4j
@RestController
public class LoginController {
@Autowired
private EmpService empService;
@PostMapping("/login")
public Result login(@RequestBody Emp emp) {
log.info("登录账号和密码:{}", emp);
Emp e = empService.login(emp);
// if(emp != null) {
// return Result.success(emp);
// }else {
// return Result.error("账号或密码错误");
// }
return e != null?Result.success(e):Result.error("账号或密码错误");
}
}
service
Emp login(Emp em);
serviceimpl
@Override
public Emp login(Emp emp) {
return empMapper.getByUsernameAndPassword(emp);
}
mapper
@Select("SELECT * from emp where username = #{username} and password = #{password}")
Emp getByUsernameAndPassword(Emp emp);
添加依赖
在pom.xml中,记得刷新
<!--阿里云OSS-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.15.1</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<!-- no more than 2.3.3-->
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
<!--JWT令牌-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<!--fastJSON-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
登录校验
cookie
package com.web.management.controller;
import com.web.management.pojo.Result;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController
public class CookieOrSessionController {
// 设置cookie
@GetMapping("/c1")
public Result cookie1(HttpServletResponse response) {
response.addCookie(new Cookie("login_username","www123")); //设置Cookie/响应Cookie
return Result.success();
}
//获取Cookie
@GetMapping("/c2")
public Result cookie2(HttpServletRequest request){
Cookie[] cookies = request.getCookies();
for (Cookie cookie : cookies) {
if(cookie.getName().equals("login_username")){
System.out.println("login_username: "+cookie.getValue()); //输出name为login_username的cookie
}
}
return Result.success();
}
}
session
package com.web.management.controller;
import com.web.management.pojo.Result;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController
public class CookieOrSessionController {
@GetMapping("/s1")
public Result session1(HttpSession session){
log.info("HttpSession-s1: {}", session.hashCode());
session.setAttribute("loginUser", "tom"); //往session中存储数据
return Result.success();
}
@GetMapping("/s2")
public Result session2(HttpServletRequest request){
HttpSession session = request.getSession();
log.info("HttpSession-s2: {}", session.hashCode());
Object loginUser = session.getAttribute("loginUser"); //从session中获取数据
log.info("loginUser: {}", loginUser);
return Result.success(loginUser);
}
}
JWT令牌
package com.web.management.util;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
import java.util.Map;
public class JwtUtils {
private static String signKey = "www123";
private static Long expire = 43200000L;
/**
* 生成JWT令牌
* @param claims JWT第二部分负载 payload 中存储的内容
* @return
*/
public static String generateJwt(Map<String, Object> claims){
String jwt = Jwts.builder()
.addClaims(claims)
.signWith(SignatureAlgorithm.HS256, signKey)
.setExpiration(new Date(System.currentTimeMillis() + expire))
.compact();
return jwt;
}
/**
* 解析JWT令牌
* @param jwt JWT令牌
* @return JWT第二部分负载 payload 中存储的内容
*/
public static Claims parseJWT(String jwt){
Claims claims = Jwts.parser()
.setSigningKey(signKey)
.parseClaimsJws(jwt)
.getBody();
return claims;
}
}
实现
package com.web.management.controller;
import com.web.management.pojo.Emp;
import com.web.management.pojo.Result;
import com.web.management.service.EmpService;
import com.web.management.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@RestController
public class LoginController {
@Autowired
private EmpService empService;
@PostMapping("/login2")
public Result login2(@RequestBody Emp emp) {
log.info("登录账号和密码:{}", emp);
Emp e = empService.login(emp);
if(emp != null) {
Map<String , Object> claims = new HashMap<>();
claims.put("id",e.getId());
claims.put("name",e.getName());
claims.put("username",e.getUsername());
String jwt = JwtUtils.generateJwt(claims);
return Result.success(jwt);
}else {
return Result.error("账号或密码错误");
}
}
}
其他层与基础版登录一致
过滤器Filter
package com.web.management.filter;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter(urlPatterns = "/*")
public class DemoFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("拦截方法执行,拦截到了请求...");
filterChain.doFilter(servletRequest, servletResponse);//放行
}
}
知识点
实现
package com.web.management.filter;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.web.management.pojo.Result;
import com.web.management.util.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import java.io.IOException;
@Slf4j
@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest req= (HttpServletRequest) servletRequest;
HttpServletResponse resp= (HttpServletResponse) servletResponse;
// 1、获取请求url
String url = req.getRequestURI().toString();
log.info("请求的url是:{}",url);
// 2、判断url是否为login,如果是登录操作,放行。
if (url.contains("login")) {
log.info("正在进行登录操作...");
filterChain.doFilter(servletRequest, servletResponse);
return;
}
// 3、获取请求头中的令牌(token)
String jwt = req.getHeader("token");
// 4、判断令牌是否存在,如果不存在,返回错误结果(未登录)
// 导入import org.springframework.util.StringUtils;
if(!StringUtils.hasLength(jwt)){
log.info("请求头token为空,未登录");
Result error = Result.error("NOT_LOGIN");
// 手动转换为json格式,利用阿里巴巴fastjson,导入依赖
String notLogin = JSONObject.toJSONString(error);
resp.getWriter().write(notLogin);
return;
}
// 解析token,如果解析失败,返回错误结果,未登录
try {
JwtUtils.parseJWT(jwt);
} catch (Exception e) {
e.printStackTrace();
log.info("解析失败,未登录");
Result error = Result.error("NOT_LOGIN");
// 手动转换为json格式,利用阿里巴巴fastjson,导入依赖
String notLogin = JSONObject.toJSONString(error);
resp.getWriter().write(notLogin);
return;
}
// 放行
log.info("令牌合法,放行");
filterChain.doFilter(servletRequest, servletResponse);
}
}
拦截器interceptor
要使用拦截器,记得把过滤器的注解注释了
入门
package com.web.management.interceptor;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
//目标资源方法执行前执行,返回true,放行,放回flase,不放行
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle....");
return true;
}
//目标资源方法执行后执行
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
//视图渲染完毕后执行,最后执行
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
package com.web.management.config;
import com.web.management.interceptor.LoginCheckInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private LoginCheckInterceptor loginCheckInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 设置拦截什么
registry.addInterceptor(loginCheckInterceptor).addPathPatterns("/**").excludePathPatterns("/login");
}
}
知识点
实现
package com.web.management.interceptor;
import com.alibaba.fastjson.JSONObject;
import com.web.management.pojo.Result;
import com.web.management.util.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
//目标资源方法执行前执行,返回true,放行,放回flase,不放行
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle....");
// 1、获取请求url
String url = request.getRequestURI().toString();
log.info("请求的url是:{}",url);
// 2、判断url是否为login,如果是登录操作,放行。
if (url.contains("login")) {
log.info("正在进行登录操作...");
return true;
}
// 3、获取请求头中的令牌(token)
String jwt = request.getHeader("token");
// 4、判断令牌是否存在,如果不存在,返回错误结果(未登录)
// 导入import org.springframework.util.StringUtils;
if(!StringUtils.hasLength(jwt)){
log.info("请求头token为空,未登录");
Result error = Result.error("NOT_LOGIN");
// 手动转换为json格式,利用阿里巴巴fastjson,导入依赖
String notLogin = JSONObject.toJSONString(error);
response.getWriter().write(notLogin);
return true;
}
// 解析token,如果解析失败,返回错误结果,未登录
try {
JwtUtils.parseJWT(jwt);
} catch (Exception e) {
e.printStackTrace();
log.info("解析失败,未登录");
Result error = Result.error("NOT_LOGIN");
// 手动转换为json格式,利用阿里巴巴fastjson,导入依赖
String notLogin = JSONObject.toJSONString(error);
response.getWriter().write(notLogin);
return true;
}
// 放行
log.info("令牌合法,放行");
return true;
}
//目标资源方法执行后执行
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
//视图渲染完毕后执行,最后执行
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
关于过滤器和拦截器放行
过滤器:
filterChain.doFilter(servletRequest, servletResponse);
拦截器:
return true;
如果你觉得本文对你有用的话,请随意打赏~