controller方法返回json或html

mac2024-12-29  19

一、情景描述

一个普通的Controller方法:

@Controller public class ExampleController { @RequestMapping("/test") public ModelAndView test() { Map<String, String> map = new HashMap(); map.put("哈哈", "哈哈哈哈"); map.put("呵呵", "呵呵呵呵"); return new ModelAndView("test", map); } }

通过 http://localhost:8080/novel/test.json 访问:

{"哈哈": "哈哈哈哈", "呵呵", "呵呵呵呵"}

在 test.jsp中随便添加一点内容:

This is a test jsp.

通过 http://localhost:8080/novel/test   或 http://localhost:8080/novel/test.html 访问:

This is a test jsp.

二、具体实现

很明显,这是通过url后缀确定返回不同的媒体类型。

关键代码:

public void configureViewResolvers(ViewResolverRegistry registry) {     registry.jsp("/WEB-INF/pages/", ".jsp");     registry.enableContentNegotiation(new FastJsonJsonView()); } public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {     configurer.favorPathExtension(true)             .ignoreAcceptHeader(true)             .parameterName("mediaType")             .defaultContentType(MediaType.TEXT_HTML)             .mediaType("html", MediaType.TEXT_HTML)             .mediaType("json", MediaType.APPLICATION_JSON); }

重点是ContentNegotiationConfigurer配置:    .defaultContentType(MediaType.TEXT_HTML) 默认返回html    .mediaType(“html”, MediaType.TEXT_HTML) 返回html   .mediaType(“json”, MediaType.APPLICATION_JSON) 返回json

json处理的话,在这里使用的阿里的FastJson   registry.enableContentNegotiation(new FastJsonJsonView())

三、附完整配置

pom.xml

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <packaging>war</packaging> <name>novel</name> <groupId>com.yale</groupId> <artifactId>novel</artifactId> <version>1.0-SNAPSHOT</version> <properties> <!-- spring版本号 --> <spring.version>5.0.3.RELEASE</spring.version> <jsp.version>2.2</jsp.version> <servlet.version>3.1.0</servlet.version> <jstl.version>1.2</jstl.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${servlet.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>${jsp.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.62</version> </dependency> </dependencies> <build> <plugins> </plugins> </build> </project>

MyMvcConfig.java

package com.yale.config; import com.alibaba.fastjson.support.spring.FastJsonJsonView; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.web.servlet.config.annotation.*; @Configuration //开启Mvc功能 @EnableWebMvc //扫包 @ComponentScan("com.yale") public class MyMvcConfig implements WebMvcConfigurer { //配置视图解析器 // @Bean // public InternalResourceViewResolver viewResolver(){ // InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); // viewResolver.setPrefix("/WEB-INF/pages/"); // viewResolver.setSuffix(".jsp"); // viewResolver.setViewClass(JstlView.class); // return viewResolver; // } public void configureViewResolvers(ViewResolverRegistry registry) { registry.jsp("/WEB-INF/pages/", ".jsp"); registry.enableContentNegotiation(new FastJsonJsonView()); } public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer.favorPathExtension(true) .ignoreAcceptHeader(true) .parameterName("mediaType") .defaultContentType(MediaType.TEXT_HTML) .mediaType("html", MediaType.TEXT_HTML) .mediaType("json", MediaType.APPLICATION_JSON); } public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("login"); registry.addViewController("/toLogin").setViewName("login"); } }

WebInitializer.java

package com.yale.config; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; public class WebInitializer implements WebApplicationInitializer { public void onStartup(ServletContext servletContext) throws ServletException { AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); context.register(MyMvcConfig.class); context.setServletContext(servletContext); ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher",new DispatcherServlet(context)); //映射路径 servlet.addMapping("/"); servlet.setLoadOnStartup(1); } }
最新回复(0)