Recently I have started to contact the SpringMVC framework. This framework is very convenient to use. After the framework is built, the code is almost the same pattern. Of course, to get to this point, you must ensure that your SpringMVC related configuration has been completed and the configuration is correct!
As my first blog about S-flat ringMVC, this blog mainly talks about how to configure SpringMVC and can make it return to the bean entity normally. The bean entity here is generally returned to the front end in the form of a Json string.
The development tool used is eclipse, which is also a relatively popular development tool. It can be considered to be used by everyone, but the proficiency level is different!
The specific configuration is as follows:
web.xml:
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd" id="WebApp_ID" version="3.1"> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <display-name>ReturnJsonDemo</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:dispatcher-servlet.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping></web-app>
dispatcher-servlet.xml:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <mvc:default-servlet-handler /> <context:component-scan base-package="com.zyq.springmvc.controller"> <context:exclude-filter type="annotation" expression="org.springframework.steretype.Service" /> </context:component-scan> <context:annotation-config /> <mvc:annotation-driven> <mvc:message-converters> <bean> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8</value> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <bean > <property name="supportedMediaTypes"> <list> <value>application/json; charset=UTF-8</value> <value>application/x-www-form-urlencoded; charset=UTF-8</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven></beans>
There is also an applicationContext.xml, but I don't write anything in it, so I won't give it!
Create a new index.jsp, which is used as the main interface to test whether the return value of each interface is normal! The code is also given here:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Main Page</title></head><body> <h1>Welcome Main Page!!!</h1> <form action="/ReturnJsonDemo/first"> <input type="submit" value="first" /> </form> <form action="/ReturnJsonDemo/second"> <input type="submit" value="second" /> </form> <form action="/ReturnJsonDemo/third"> <input type="submit" value="third" /> </form> <form action="/ReturnJsonDemo/fourth"> <input type="submit" value="fourth" /> </form></body></html>
At this point, all the configurations are basically completed, and then a Controller is declared. The specific code is relatively simple, and they are basically in a fixed format!
MainController.java
package com.zyq.springmvc.controller;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import org.springframework.steretype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import com.zyq.springmvc.bean.CommonBean;import com.zyq.springmvc.bean.SonBean;@Controllerpublic class MainController { @RequestMapping("/first") @ResponseBody public CommonBean getFirst(){ CommonBean bean = new CommonBean(); bean.setResultCode("success"); bean.setTimeStamp(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(System.currentTimeMillis())); bean.setData("this is first message"); return bean; } @RequestMapping("/second") @ResponseBody public CommonBean getSecond(){ CommonBean bean = new CommonBean(); bean.setResultCode("ss"); bean.setTimeStamp(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(System.currentTimeMillis())); List<String> data = new ArrayList<>(); data.add("JAVA"); data.add("C"); data.add("PYTHON"); data.add("C++"); bean.setData(data); return bean; } @RequestMapping("/third") @ResponseBody public CommonBean getThird(){ CommonBean bean = new CommonBean(); bean.setResultCode("success"); bean.setTimeStamp(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(System.currentTimeMillis())); Map<String, String> data = new HashMap<>(); data.put("first", "JAVA"); data.put("second","PYTHON"); data.put("third", "C++"); data.put("fourth", "C"); bean.setData(data); return bean; } @RequestMapping("/fourth") @ResponseBody public CommonBean getFourth(){ CommonBean bean = new CommonBean(); bean.setResultCode("success"); bean.setTimeStamp(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(System.currentTimeMillis())); SonBean sonBean = new SonBean(); sonBean.setAge(25); sonBean.setName("Hacker's Delight"); sonBean.setGender("male"); bean.setData(sonBean); return bean; }}The running effect of the code is as follows:
It seems that different browsers have different request operations for interfaces. When using the eclipse request interface, a json file will be downloaded, and the content of the file is a json string.
When configuring a complete project, you need to use the springframework jar package and the related jar package of jackson. The tomcat8.5 I use prompts an error when running, and you need to introduce the common-log jar package.
When declaring an interface that returns a json string, be sure to use the @ResponseBody annotation, which will write the return data of the interface to the body area in the response, which is to pass it back to the front end.
When I was testing, I encountered a problem. When returning beans, I can only return class packages, but not class inheritance or interface inheritance. For example:
If you return a ParentBean, which contains a ChildBean inside, that's OK!
If when the interface is defined, the returned parent class is the actual returned subclass, and the error is reported at this time, and the subclass cannot be converted into parent class, it means that you cannot convert the String object into an object object. In this regard, it should be based on the parent class that cannot find the attributes of the subclass, which leads to the inability to convert the bean object to a json string normally. Therefore, it is not allowed to declare beans in the interface in the framework and the subclass of the bean is returned (these reasons are just personal guesses, and the specific reasons also require analysis of the code in the framework)!
OK, that's all about returning json strings! Attach the source code of the demo, the jar package you need is also inside, you can download it yourself if you need it!
Source code download
The above example explanation of using SpringMVC to return json strings is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.