SpringMVC之HandlerMethodReturnValueHandler接口实现自定义注解

1.接口介绍

HandlerMethodReturnValueHandler是RequestMappingHandlerAdapter处理完映射控制后对方法返回值的进一步进行处理。我们将实现HandlerMethodReturnValueHandler接口重写handleReturnValue方法将返回值格式化为我们需要的json格式。

2.接口定义

/**
 * 策略模式接口:处理 Controller 方法返回值
 */
public interface HandlerMethodReturnValueHandler {

    /**
     * 该处理程序是否支持给定的方法返回类型(只有返回true才回去调用handleReturnValue)
     */
    boolean supportsReturnType(MethodParameter returnType);

    /**
     * 处理给定的返回值
     * 通过向 ModelAndViewContainer 添加属性和设置视图或者
     * 通过调用 ModelAndViewContainer.setRequestHandled(true) 来标识响应已经被直接处理(不再调用视图解析器)
     */
    void handleReturnValue(Object returnValue, MethodParameter returnType,
            ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception;

}

3.实现

接口返回格式ResultInfo.java

   /**
     * @Auther: hougq
     * @Date: 2019/4/3 15:34
     * @Description:app接口返回格式
     */
    public class ResultInfo {
    
        public long code;
        public Object result;
    
        public long getCode() {
            if(code==0l){
                code=200l;
            }
            return code;
        }
    
        public Object getResult() {
            return result;
        }
    
        public void setResult(Object result) {
            this.result = result;
        }
    }

实现HandlerMethodReturnValueHandler接口重写handleReturnValue方法FormatJsonReturnValueHandler.java

import com.google.gson.Gson;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class FormatJsonReturnValueHandler implements HandlerMethodReturnValueHandler {
    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        boolean hasJSONAnno = returnType.getMethodAnnotation(AppResponsBody.class) != null || returnType.getMethodAnnotation(AppResponsBody.class) != null;
        return hasJSONAnno;
    }


    @Override
    public void handleReturnValue(Object obj, MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest) throws Exception {
        modelAnd

ViewContainer.setRequestHandled(true);
        AppResponsBody res=methodParameter.getMethodAnnotation(AppResponsBody.class);
        String type = res.type();
        HttpServletResponse response=nativeWebRequest.getNativeResponse(HttpServletResponse.class);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        PrintWriter writer = null;
        Gson gson=new Gson();
        ResultInfo info=new ResultInfo();
        info.setResult(obj);
        try {
            writer = response.getWriter();
            writer.write(gson.toJson(info));
            writer.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (writer != null)
                writer.close();
        }
    }

    }

接口注解类AppResponsBody.java

import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.annotation.*;

@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AppResponsBody {
    String type() default "json";
}

测试controller类TestController .java

@Controller
@RequestMapping(value = "/app")
public class TestController {
    @Autowired
    private DeptDutycheckstandService deptDutycheckstandService;
    @RequestMapping("/kbm/list")
    @AppResponsBody
    public Page list(DeptDutycheckstand deptDutycheckstand, HttpServletRequest request) {
    	//此处查询数据库返回page对象
        Page page = deptDutycheckstandService.findPage(new Page(request), deptDutycheckstand);
        return page;
    }
}

4.结果

使用postman 访问接口,返回数据如下:
SpringMVC之HandlerMethodReturnValueHandler接口实现自定义注解_第1张图片
寄语:每天进步一点点,成功就会在眼前。

你可能感兴趣的:(spring)