Springboot returns json or xml or html according to the url suffix

Keywords: Programming Java xml JSON Spring

Springboot is based on the url suffix Return json or xml; Returns html based on the suffix name. Author: liuren

Copyright notice: This is an original article, following CC 4.0 BY-SA copyright agreement. Please attach the original source link and this notice for reprint.

Initializing the Springboot project

1, pom.xml package introduced first

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.4.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>cn.codepeople</groupId>
	<artifactId>springboot-json-xml</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>springboot-json-xml</name>
	<description>Springboot according to url Suffix return json perhaps xml perhaps html</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
        </dependency>
        
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

Project structure chart

Start project configuration

application.properties

spring.thymeleaf.mode=HTML  #Suffix name
spring.thymeleaf.encoding=utf-8  #Encoding format
spring.thymeleaf.cache=false #Use cache or not

Spring boot configuration

WebMvcConfig.java

package cn.codepeople.web.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

	@Override
	protected void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
		configurer.favorPathExtension(true) //Is suffix supported
			.parameterName("mediaType")
		   .defaultContentType(MediaType.APPLICATION_JSON) 
		   .mediaType("xml", MediaType.APPLICATION_XML)   //Return xml data when the suffix name is xml
		   .mediaType("html", MediaType.TEXT_HTML)              //Return to the html page when the suffix name is html
		   .mediaType("json", MediaType.APPLICATION_JSON);//Return json data when the suffix name is json
	}

}

New Bean entity class

User.java

package cn.codepeople.web.entity;

import java.util.Date;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class User {

	private Long id;
	
	private String userName;
	
	private String age;
	
	private Date  birthdy;
	
	private boolean delFlag;

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}

	public Date getBirthdy() {
		return birthdy;
	}

	public void setBirthdy(Date birthdy) {
		this.birthdy = birthdy;
	}

	public boolean isDelFlag() {
		return delFlag;
	}

	public void setDelFlag(boolean delFlag) {
		this.delFlag = delFlag;
	}
	
	
	
}

New UserService.java interface

UserService.java

package cn.codepeople.web.service;

import java.util.List;

import cn.codepeople.web.entity.User;

public interface UserService {

	List<User> listUser();

}

New UserServiceImpl implementation class

UserServiceImpl.java

package cn.codepeople.web.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Service;

import cn.codepeople.web.entity.User;
import cn.codepeople.web.service.UserService;

@Service
public class UserServiceImpl implements UserService {

	@Override
	public List<User> listUser() {
		List<User> list = new ArrayList<User>();
		User user = new User();
		user.setId(1L);
		user.setAge("12");
		user.setDelFlag(true);
		user.setUserName("zhang1");
		user.setBirthdy(new Date());
		list.add(user);
		User userx = new User();
		userx.setId(2L);
		userx.setAge("23");
		userx.setDelFlag(true);
		userx.setUserName("zhang2");
		userx.setBirthdy(new Date());
		list.add(userx);
		return list;
	}

}

New controller class

package cn.codepeople.web.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.codepeople.web.entity.User;
import cn.codepeople.web.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;
	
	@RequestMapping("/list")
	@ResponseBody
	private List<User> listUser(){
		
		return userService.listUser();
		
	}
	
	@RequestMapping("/index")
	public String user() {
		return "list.html";
	}
}

Modify SpringbootJsonXmlApplication.java startup class

package cn.codepeople.web;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootJsonXmlApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringbootJsonXmlApplication.class, args);
	}

}

Create a new list.html file in the templates directory

list.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
Springboot according to url Suffix return json perhaps xml perhaps html ->>>
</body>
</html>

Launch success page

The access address is: http://127.0.0.1:8080/user/list.json

The access address is:< http://127.0.0.1:8080/user/list.xml

The access address is:< http://127.0.0.1:8080/user/index.html

I don't understand one thing. If you have a deep understanding, please help me to answer it. The default format in WebMvcConfig.java is json

But if I return the xml format file without suffix, is it because I didn't make the default format configuration in the controller? If no suffix is added, follow the

Should WebMvcConfig.java configuration return json?

Blog address: https://www.codepeople.cn

=====================================================================

The official account of WeChat:

Posted by srdva59 on Mon, 30 Mar 2020 09:33:51 -0700