SpringBoot 拦截器 && 拦截之后返回前台自定义格式
1、加入 阿里的 json jar包
<!--json jar相关jar包-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.7</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.23</version>
</dependency>
本文需要jar依赖 如图 - >
拦截之后返回的效果->
新建 config 包 并新建 InterceptorConfig 配置类 类上面添加 @Configuration 注解 表示是一个配置类
package com.pigs.springbootpigsinterceptor.config;
import com.pigs.springbootpigsinterceptor.interceptor.HomeInterceptor;
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;
/**
* @author PIGS
*
* 拦截 路径
*/
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
/**
* 拦截 类
*/
@Autowired
private HomeInterceptor homeInterceptor;
/**
* 这个方法用来注册拦截器,写好的拦截器需要通过这里添加注册才能生效
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
/**
* 表示拦截所有的请求,
* addPathPatterns("/**");
* excludePathPatterns("/login", "/register")
* 表示除了登陆与注册之外,因为登陆注册不需要登陆也可以访问excludePathPatterns("/login", "/register")
*
*
*/
registry.addInterceptor(homeInterceptor).addPathPatterns("/home");
}
}
新建 一个拦截类
HomeInterceptor 在类上面添加 @Component 注解 交给spring 容器管理 并实现 HandlerInterceptor 类
代码 ->
package com.pigs.springbootpigsinterceptor.interceptor;
import com.alibaba.fastjson.JSON;
import com.pigs.springbootpigsinterceptor.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
*
* 拦截器
*
* @author PIGS
*/
@Component
public class HomeInterceptor implements HandlerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(HomeInterceptor.class);
/**
* 判断session 是否有值
*
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String userName = (String) request.getSession().getAttribute("userName");
logger.info("userName={}",userName);
if (userName==null){
String result = JSON.toJSONString(ResultUtil.error(101, "你还没有登录哦!"));
returnJson(response, result);
return false;
}
return true;
}
/**
* 返回客户端数据
*/
private void returnJson(HttpServletResponse response, String result) throws Exception {
PrintWriter writer = null;
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=utf-8");
try {
writer = response.getWriter();
writer.print(result);
} catch (IOException e) {
} finally {
if (writer != null) {
writer.close();
}
}
}
/**
* 处理请求完成后视图渲染之前的处理操作
*
* @param httpServletRequest
* @param httpServletResponse
* @param o
* @param modelAndView
* @throws Exception
*/
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object
o, ModelAndView modelAndView) throws Exception {
}
/**
* 视图渲染之后的操作
*
* @param httpServletRequest
* @param httpServletResponse
* @param o
* @param e
* @throws Exception
*/
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse
httpServletResponse, Object o, Exception e) throws Exception {
}
}
自定义返回格式 ResultFormat 类 ->
代码->
package com.pigs.springbootpigsinterceptor.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;
/**
* @author PIGS-猪农·杨
* @version 1.0
* @date 2020/2/17 14:41
* 统一返回格式
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
public class ResultFormat<T> {
/**
* 错误码
*/
private Integer code;
/**
* 提示信息
*/
private String msg;
/**
* 内容
*/
private T data;
}
ResultUtil返回工具类 ->
代码->
package com.pigs.springbootpigsinterceptor.util;
import com.pigs.springbootpigsinterceptor.entity.ResultFormat;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @author PIGS-猪农·杨
* @version 1.0
* @date 2020/2/17 14:53
* 统一返回工具类
*/
public class ResultUtil {
public static ResultFormat success(Object object) {
ResultFormat result =new ResultFormat();
result.setCode(200);
result.setMsg("成功");
result.setData(object);
return result;
}
public static ResultFormat success() {
return success(null);
}
public static ResultFormat error(Integer code, String msg) {
ResultFormat result =new ResultFormat();
result.setCode(code);
result.setMsg(msg);
return result;
}
}
已经托管 码云
https://gitee.com/pig_farmer_x/springboot/blob/master/springboot-pigs-interceptor.zip