文章目录
- 1.需求分析
- 2.目录
- 3.自定义ResponseBody注解
- 4.MonsterController.java
- 5.Monster.java 实现序列化接口
- 6.引入jackson
- 7.Adapter.java 如果有@ResponseBody注解就返回json
- 8.测试
- 9.SpringMVC执行流程
1.需求分析
2.目录
3.自定义ResponseBody注解
package com.sunxiansheng.springmvc.annotation;import java.lang.annotation.*;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = ElementType.METHOD)
@Documented
public @interface ResponseBody {}
4.MonsterController.java
@ResponseBody @RequestMapping(url = "/json/monster")public List<Monster> jsonMonster(HttpServletResponse response) {List<Monster> monsters = monsterService.listMonster();log.info("monsters: {}", monsters);return monsters;}
5.Monster.java 实现序列化接口
6.引入jackson
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.13.4</version> </dependency>
7.Adapter.java 如果有@ResponseBody注解就返回json
package com.sunxiansheng.springmvc.adaptor;import com.fasterxml.jackson.databind.ObjectMapper;
import com.sunxiansheng.springmvc.annotation.ResponseBody;
import com.sunxiansheng.springmvc.handler.HandlerMapping;
import com.sunxiansheng.springmvc.handler.SunHandler;
import com.sunxiansheng.springmvc.viewparser.ViewParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public class Adapter {private static final Logger log = LoggerFactory.getLogger(Adapter.class);public static void executeDispatch(HttpServletRequest request, HttpServletResponse response) {HandlerMapping handlerMapping = SunHandler.getHandlerMapping(request);if (handlerMapping == null) {try {response.getWriter().write("404 NOT FOUND");} catch (Exception e) {throw new RuntimeException(e);}return;}Object controller = handlerMapping.getController();Method method = handlerMapping.getMethod();Object[] args = ResolveArguments.resolveMethodArguments(request, response, method);List<Class<?>> argsList = new ArrayList<>();for (Object arg : args) {argsList.add(arg.getClass());}log.info("实参列表:{}", argsList);try {Object invoke = method.invoke(controller, args);if (method.isAnnotationPresent(ResponseBody.class)) {ObjectMapper objectMapper = new ObjectMapper();String jsonResponse = objectMapper.writeValueAsString(invoke);response.setContentType("application/json;charset=utf-8");response.setCharacterEncoding("UTF-8");response.getOutputStream().write(jsonResponse.getBytes());} else {if (invoke instanceof String) {ViewParser.parse(invoke.toString(), request, response);}}} catch (Exception e) {throw new RuntimeException(e);}}}
8.测试
9.SpringMVC执行流程
- 中央控制器是一个Servlet,配置了,在Tomcat启动时调用init方法
- init方法完成初始化Spring容器,初始化映射器的操作
- 浏览器发送请求,交给适配器完成请求分发
- 适配器首先从映射器中获取映射关系,其中映射关系包括url、目标对象、Method对象
- 适配器调用参数解析器根据形参列表的类型来填充实参列表,然后反射调用方法
- 适配器检测方法是否有**@ResponseBody注解,如果有则返回Json数据,如果没有则将结果交给视图解析器**处理
- 视图解析器根据冒号进行分割,请求转发或者重定向到指定的视图