zeromemos
最好的学习方法就是输出所学的知识

SpringBoot拦截器里直接返回JSON

http://www.zeromemos.com/index/article/read.html?id=349

接着这篇

pom文件里加入一个JSON工具依赖

        <!-- 阿里JSON解析和打包工具 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.51</version>
        </dependency>

修改拦截器方法,测试直接在拦截器里拦截并返回JSON

package com.zeromemos.Interceptor;

import com.alibaba.fastjson.JSONObject;
import com.zeromemos.utils.R;
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;

public class MyInterceptor implements HandlerInterceptor {

//给前端输出json的方法 private void returnJson(HttpServletResponse response, String json) { PrintWriter writer = null; response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); try { writer = response.getWriter(); writer.print(json); } catch (IOException e) { System.out.println(e.getMessage()); } finally { if (writer != null) writer.close(); } } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("这里执行控制器方法前的拦截方法"); String jsonObjectStr = JSONObject.toJSONString(R.error()); returnJson(response, jsonObjectStr); return false;//true放行,false拦截 } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("这里执行控制器方法后的方法"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("这里执行最后的结束方法,一般用于释放资源"); } }


配置类不变

package com.zeromemos.config;

import com.zeromemos.Interceptor.MyInterceptor;
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 {
    /**
     * 添加拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 对所有访问路径,都通过MyInterceptor类型的拦截器进行拦截
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**")
                .excludePathPatterns("/index");//放行/index路径
    }
}

访问被拦截的地址测试

评论区

关于我们

本站主要用于记录个人学习笔记,网站开发中,如需以前站内资料请加QQ群272473835索取。注册账号仅提供回帖功能,可不注册!

微信公众号