本文主要是介绍使用Filter AND Interceptor校验等录(全网独一份,机不可失),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
说明:基于spring boot进行的校验
1.熟悉如何使用jwt令牌。(不会的看这里:带你领略JWTl令牌的魅力!!!-CSDN博客)
Filter和Interceptor共用文件:(可以仿照,根据你的实际情况)
controller层代码:
/** Copyright (c) 2020, 2023, All rights reserved.**/
package com.itheima.controller;import com.itheima.pojo.Emp;
import com.itheima.pojo.Result;
import com.itheima.service.EmpService;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;import java.util.HashMap;
import java.util.Map;/*** <p>Project: tlias-web-management - LoginController</p>* <p>Powered by scl On 2023-10-16 14:16:46</p>* <p>描述:<p>** @author 孙臣龙 [1846080280@qq.com]* @version 1.0* @since 17*/
@Slf4j
@RestController
public class LoginController {@Autowiredprivate EmpService empService;@PostMapping("/login")public Result login(@RequestBody Emp emp) {log.info("员工登录:{}", emp);Emp e = empService.login(emp);//登录成功生成令牌,下发令牌if (e != null) {Map<String, Object> climas = new HashMap<>();climas.put("id", e.getId());climas.put("name", e.getName());climas.put("username", e.getUsername());String s = JwtUtils.generateJwt(climas);return Result.success(s);}return Result.error("用户名或密码错误");}
}
service层代码:
package com.itheima.service;import com.itheima.pojo.Emp;
import com.itheima.pojo.PageBean;
import org.springframework.format.annotation.DateTimeFormat;import java.time.LocalDate;
import java.util.List;/*** <p>Project: tlias-web-management - EmpService</p>* <p>Powered by scl On 2023-10-12 15:31:01</p>* <p>描述:<p>** @author 孙臣龙 [1846080280@qq.com]* @version 1.0* @since 17*/
public interface EmpService {/*** 用户登录* @param emp* @return*/Emp login(Emp emp);
}
mapper层代码:
package com.itheima.mapper;import com.itheima.pojo.Emp;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;import java.time.LocalDate;
import java.util.List;/*** <p>Project: tlias-web-management - EmpMapper</p>* <p>Powered by scl On 2023-10-12 15:29:01</p>* <p>描述:<p>** @author 孙臣龙 [1846080280@qq.com]* @version 1.0* @since 17*/
@Mapper
public interface EmpMapper {/*** 用户登录* @param emp* @return*/@Select("select * from emp where username=#{username} and password=#{password}")Emp getByUserNameAndPwd(Emp emp);
}
Result(响应代码):
package com.itheima.pojo;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result {private Integer code;//响应码,1 代表成功; 0 代表失败private String msg; //响应信息 描述字符串private Object data; //返回的数据//增删改 成功响应public static Result success(){return new Result(1,"success",null);}//查询 成功响应public static Result success(Object data){return new Result(1,"success",data);}//失败响应public static Result error(String msg){return new Result(0,msg,null);}
}
2.Filter校验器:
①:首先需要在pom文件中添加依赖:
<!--jwt令牌--><!-- jjwt-api --><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.62</version></dependency>
②:创建Filter过滤器:
/** Copyright (c) 2020, 2023, All rights reserved.**/
package com.itheima.filter;import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.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;
import java.util.Locale;/*** <p>Project: tlias-web-management - LoginCheckFilter</p>* <p>Powered by scl On 2023-10-17 16:30:20</p>* <p>描述:<p>** @author 孙臣龙 [1846080280@qq.com]* @version 1.0* @since 17*/
@Slf4j
@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {HttpServletResponse resp= (HttpServletResponse) servletResponse;HttpServletRequest req= (HttpServletRequest) servletRequest;//获取urlString url = req.getRequestURI().toString();log.info("获取的url:{}",url);//判断url中是否包含loginif (url.contains("login")){filterChain.doFilter(servletRequest,servletResponse);return;}//获取请求头的内容String jwt = req.getHeader("token");//判断jwt令牌是否存在if (!StringUtils.hasLength(jwt)){log.info("请求头token不存在");Result error = Result.error("NOT_LOGIN");String nologin = JSONObject.toJSONString(error);resp.getWriter().write(nologin);return;}//解析jtw令牌try {JwtUtils.parseJWT(jwt);} catch (Exception e) {e.printStackTrace();log.info("jwt令牌解析错误,");Result error = Result.error("NOT_LOGIN");String nologin = JSONObject.toJSONString(error);resp.getWriter().write(nologin);return;}//jwt令牌解析成功,放行log.info("放行");filterChain.doFilter(servletRequest,servletResponse);}
}
3.Interceptor拦截器:
①:创建拦截器:
/** Copyright (c) 2020, 2023, All rights reserved.**/
package com.itheima.interceptor;import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.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;/*** <p>Project: tlias-web-management - LoginCheckInterceptor</p>* <p>Powered by scl On 2023-10-17 17:18:06</p>* <p>描述:<p>** @author 孙臣龙 [1846080280@qq.com]* @version 1.0* @since 17*/
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {@Override //目标资源方法运行前运行,返回true:放行,返回false:不放行public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {//获取urlString url = req.getRequestURI().toString();log.info("获取的url:{}",url);//判断url中是否包含loginif (url.contains("login")){return true;}//获取请求头的内容String jwt = req.getHeader("token");//判断jwt令牌是否存在if (!StringUtils.hasLength(jwt)){log.info("请求头token不存在");Result error = Result.error("NOT_LOGIN");String nologin = JSONObject.toJSONString(error);resp.getWriter().write(nologin);return false;}//解析jtw令牌try {JwtUtils.parseJWT(jwt);} catch (Exception e) {e.printStackTrace();log.info("jwt令牌解析错误,");Result error = Result.error("NOT_LOGIN");String nologin = JSONObject.toJSONString(error);resp.getWriter().write(nologin);return false;}//jwt令牌解析成功,放行log.info("放行");return true;}@Override //目标资源方法后运行public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System.out.println("postHandle...");}@Override //最后运行public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {System.out.println("afterCompletion...");}
}
说明一下:有实体类代码我没有上传(需要根据你自己的数据库决定),Filter和Interceptor使用一个就可以了。
这篇关于使用Filter AND Interceptor校验等录(全网独一份,机不可失)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!