当前位置: 代码迷 >> 综合 >> SpringMVC(Spring4)——JSON和拦截器
  详细解决方案

SpringMVC(Spring4)——JSON和拦截器

热度:63   发布时间:2023-12-17 12:29:48.0

1.处理JSON:

步骤:

加入jar包:

编写目标方法,在方法上添加@ResponseBody注解:

@ResponseBody@RequestMapping("/testJson")public Collection<Employee> testJson(){return employeeDao.getAll();}

2.HttpMessageConverter<T>:

HttpMessageConverter<T>是Spring3.0新添加的一个接口,负责将请求信息转换为一个对象,将对象输出为响应信息。

有如下几个方法:

Boolean canRead(Class<?> clazz,MediaType mediaType):指定转换器可以读取的对象类型,同时指定支持的MIME类型(text/html,applaiction/json?)。

Boolean canWrite(Class<?> clazz,MediaType mediaType):同上相反。

LIst<MediaType> getSupportMediaTypes()?:该转换器支持的媒体类型。

T read(Class<? extends T> clazz,HttpInputMessage inputMessage):将请求信息流转换为T类型的对象。

void write(T t,MediaType contnetType,HttpOutputMessgaeoutputMessage):同上相反。

实现类:

DispatcherServlet默认装配RequestMappingHandlerAdapter,而RequestMappingHandlerAdapter默认装配如下HttpMessageConverter:

加入jackson jar包之后:

2.1 使用HttpMessageConverter<T>:

之前使用了@RequestBody / @ResponseBody对消息进行了处理,同样的HttpEntity<T> / ResponseEntity<T>与之前的注解功能类似。

Spring首先根据请求头或响应头的Accept属性选择匹配的HttpMessageConverter,进而根据参数类型或泛型类型的过滤得到匹配的HttpMessageConverter。

@RequestMapping("/testResponseEntity")public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException{byte [] body = null;ServletContext servletContext = session.getServletContext();InputStream in = servletContext.getResourceAsStream("/files/abc.txt");body = new byte[in.available()];in.read(body);HttpHeaders headers = new HttpHeaders();headers.add("Content-Disposition", "attachment;filename=abc.txt");HttpStatus statusCode = HttpStatus.OK;ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode);return response;}@ResponseBody@RequestMapping("/testHttpMessageConverter")public String testHttpMessageConverter(@RequestBody String body){System.out.println(body);return "helloworld! " + new Date();}

3.文件上传:

Spring用Jakarta Commons FileUpload技术实现了一个MultipartResolver实现类CommonsMultipartResovler。

加入Jar包:

配置:

<!-- 配置 MultipartResolver --><bean id="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><property name="defaultEncoding" value="UTF-8"></property><property name="maxUploadSize" value="1024000"></property>	</bean>	

目标方法:

@RequestMapping("/testFileUpload")public String testFileUpload(@RequestParam("desc") String desc, @RequestParam("file") MultipartFile file) throws IOException{System.out.println("desc: " + desc);System.out.println("OriginalFilename: " + file.getOriginalFilename());System.out.println("InputStream: " + file.getInputStream());return "success";}

4.拦截器:

package com.atguigu.springmvc.interceptors;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;public class FirstInterceptor implements HandlerInterceptor{@Overridepublic boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {System.out.println("[FirstInterceptor] preHandle");return true;}@Overridepublic void postHandle(HttpServletRequest request,HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {System.out.println("[FirstInterceptor] postHandle");}@Overridepublic void afterCompletion(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex)throws Exception {System.out.println("[FirstInterceptor] afterCompletion");}}
<mvc:interceptors><!-- 配置自定义的拦截器 --><bean class="com.atguigu.springmvc.interceptors.FirstInterceptor"></bean>
</mvc:interceptors>

当拦截器对应一个特定的处理方法时:

<mvc:interceptor><mvc:mapping path="/emps"/><bean class="com.atguigu.springmvc.interceptors.SecondInterceptor">    </bean>
</mvc:interceptor>

执行顺序:

return false时:

  相关解决方案