Words as a mobile terminal program ape to write back-end service program is not very professional! It’s not. It’s not good performance and it’s not very robust, but it’s very helpful for understanding the overall business logic; Moreover, if you want to develop a simple mobile APP with a back end and a front end, it is good that one person can do all the work. Here’s how to build RestFul backend services using Spring MVC.

Let’s take a look at what this article is trying to achieve:

To access the URL: http://localhost:8080/user/loginByPwd.do? Username =ywl5320&password=123456

The renderings are as follows:



This is a simple restful type of back-end service. So let’s start building!

I. Environment construction

1.1. Install Tomact

Online many relevant tutorials, here is not introduced, if it is not in can also ask me.

1.2. Install Intellij IDEA

Download address (www.jetbrains.com/idea/downlo.) , crack also ask Baidu, very easy.

2. Create a project

2.1. Create an empty Maven project



2.2. Fill in GroupId (optional package name) and Artifactld (optional project name)



2.3. Enter the project name and storage path to create the project



Add Spring support

The previous step created an empty project for Maven. Now you need to add Spring support to make it a Web project.





This adds Spring support to the project.

Add Spring libraries (json, log, etc.) via Maven

After adding the repository to the file pom.xml, the code looks like this:

[html]
view plain
copy
print
?

  1. <?xml version=“1.0” encoding= “UTF-8”? >  
  2. <project xmlns=“http://maven.apache.org/POM/4.0.0”  
  3.          xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”  
  4.          xsi:schemaLocation=“http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd” >  
  5.     <modelVersion>4.0.0</modelVersion >  
  6.   
  7.     <groupId>com.ywl5320.appservice</groupId >  
  8.     <artifactId>AppService</artifactId >  
  9.     <version>1.0 the SNAPSHOT</version >  
  10.   
  11.     <properties>  
  12.         <project.build.sourceEncoding>UTF-8</ project.build.sourceEncoding>  
  13.         <spring.version>4.2.6. RELEASE</spring.version >  
  14.         <hibernate.version>5.0.12. The Final</ hibernate.version>  
  15.         <jackson.version>2.5.0</jackson.version >  
  16.     </properties>  
  17.   
  18.     <dependencies>  
  19.   
  20.         <! — spring –>  
  21.         <dependency>  
  22.             <groupId>org.springframework</ groupId>  
  23.             <artifactId>spring-core</ artifactId>  
  24.             <version>${spring.version}</ version>  
  25.         </dependency>  
  26.   
  27.         <dependency>  
  28.             <groupId>org.springframework</ groupId>  
  29.             <artifactId>spring-beans</ artifactId>  
  30.             <version>${spring.version}</ version>  
  31.         </dependency>  
  32.   
  33.         <dependency>  
  34.             <groupId>org.springframework</ groupId>  
  35.             <artifactId>spring-context</ artifactId>  
  36.             <version>${spring.version}</ version>  
  37.         </dependency>  
  38.   
  39.         <dependency>  
  40.             <groupId>org.springframework</ groupId>  
  41.             <artifactId>spring-web</ artifactId>  
  42.             <version>${spring.version}</ version>  
  43.         </dependency>  
  44.   
  45.         <! — SpringMVC requires configuration –>  
  46.         <dependency>  
  47.             <groupId>org.springframework</ groupId>  
  48.             <artifactId>spring-webmvc</ artifactId>  
  49.             <version>${spring.version}</ version>  
  50.         </dependency>  
  51.   
  52.         <! — log4j –>  
  53.         <dependency>  
  54.             <groupId>log4j</ groupId>  
  55.             <artifactId>log4j</ artifactId>  
  56.             <version>1.2.17</ version>  
  57.         </dependency>  
  58.   
  59.         <! — json –>  
  60.         <dependency>  
  61.             <groupId>com.alibaba</ groupId>  
  62.             <artifactId>fastjson</ artifactId>  
  63.             <version>1.2.3</ version>  
  64.         </dependency>  
  65.   
  66.         <dependency>  
  67.             <groupId>com.fasterxml.jackson.core</ groupId>  
  68.             <artifactId>jackson-annotations</ artifactId>  
  69.             <version>${jackson.version}</ version>  
  70.         </dependency>  
  71.   
  72.         <dependency>  
  73.             <groupId>com.fasterxml.jackson.core</ groupId>  
  74.             <artifactId>jackson-core</ artifactId>  
  75.             <version>${jackson.version}</ version>  
  76.         </dependency>  
  77.   
  78.         <dependency>  
  79.             <groupId>com.fasterxml.jackson.core</ groupId>  
  80.             <artifactId>jackson-databind</ artifactId>  
  81.             <version>${jackson.version}</ version>  
  82.         </dependency>  
  83.   
  84.         <! — servlet –>  
  85.         <dependency>  
  86.             <groupId>javax.servlet</ groupId>  
  87.             <artifactId>servlet-api</ artifactId>  
  88.             <version>3.0 – alpha – 1</ version>  
  89.             <scope>provided</ scope>  
  90.         </dependency>  
  91.   
  92.         <dependency>  
  93.             <groupId>javax.servlet</ groupId>  
  94.             <artifactId>jstl</ artifactId>  
  95.             <version>1.2</ version>  
  96.         </dependency>  
  97.   
  98.     </dependencies>  
  99.   
  100. </project>  

<? The 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/xsd/maven-4.0.0.xsd" > < modelVersion > 4.0.0 < / modelVersion > < groupId > com. Ywl5320. Appservice < / groupId > < artifactId > appservice < / artifactId > 1.0 the SNAPSHOT < version > < / version > < properties > < project. Build. SourceEncoding > utf-8 < / project. Build. SourceEncoding > < spring version > 4.2.6. RELEASE < / spring. Version > < hibernate. Version > 5.0.12. The Final < / hibernate. Version > < Jackson version > 2.5.0 < / Jackson version > < / properties > < dependencies > <! -- spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <! <dependency> <groupId>org.springframework</groupId> <artifactId> Spring-webmvc </artifactId> <version>${spring.version}</version> </dependency> <! Log4j --> <dependency> <groupId>log4j</groupId> <artifactId> <version>1.2.17</version> </dependency> <! Alibaba </groupId> <artifactId>fastjson</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <! -- servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>3.0-alpha-1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId> JSTL </artifactId> <version>1.2</version> </dependency> </dependencies> </project>Copy the code

After adding, and building the project, you can right-click to add spring-related files.

Add beans.xml, springmVC.xml, and log4j.properties to resources


4.1 add beans.xml



The beans.xml file reads as follows: Spring automatically scans all annotations specified under the package name

[html]
view plain
copy
print
?

  1. <?xml version=“1.0” encoding= “UTF-8”? >  
  2. <beans xmlns=“http://www.springframework.org/schema/beans”  
  3.        xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”  
  4.        xmlns:context=“http://www.springframework.org/schema/context”  
  5.        xsi:schemaLocation=”http://www.springframework.org/schema/beans  
  6.        http://www.springframework.org/schema/beans/spring-beans.xsd  
  7.        http://www.springframework.org/schema/context  
  8.        http://www.springframework.org/schema/context/spring-context-4.2.xsd”>  
  9.   
  10.     <context:component-scan base-package=“com.ywl5320.appservice”  use-default-filters=“false”>  
  11.         <context:exclude-filter type=“annotation”  expression=“org.springframework.stereotype.Controller”/>  
  12.         <context:exclude-filter type=“annotation”  expression=“org.springframework.web.bind.annotation.ControllerAdvice”/>  
  13.     </context:component-scan>  
  14.   
  15. </beans>  

<? The XML version = "1.0" encoding = "utf-8"? > <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd "> < context: component - scan base-package="com.ywl5320.appservice" use-default-filters="false"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> <context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/> </context:component-scan> </beans>Copy the code

Springmvc.xml is as follows: Add servlet and annotation driver

[html]
view plain
copy
print
?

  1. <?xml version=“1.0” encoding= “UTF-8”? >  
  2. <beans xmlns=“http://www.springframework.org/schema/beans”  
  3.        xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”  
  4.        xmlns:context=“http://www.springframework.org/schema/context”  
  5.        xmlns:mvc=“http://www.springframework.org/schema/mvc”  
  6.        xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
  7.        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd  
  8.        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd”>  
  9.   
  10.     <context:component-scan base-package=“com.ywl5320.appservice” >  
  11.         <context:include-filter type=“annotation”  expression=“org.springframework.stereotype.Controller”/>  
  12.         <context:include-filter type=“annotation”  expression=“org.springframework.web.bind.annotation.ControllerAdvice”/>  
  13.     </context:component-scan>  
  14.   
  15.     <mvc:default-servlet-handler/>  
  16.     <mvc:annotation-driven/>  
  17. </beans>  

<? The XML version = "1.0" encoding = "utf-8"? > <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd "> < context: component - scan base-package="com.ywl5320.appservice"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/> </context:component-scan> <mvc:default-servlet-handler/> <mvc:annotation-driven/> </beans>Copy the code

Log4j. properties contains the following contents

[html]
view plain
copy
print
?

  1. log4j.rootLogger=WARN, stdout, R    
  2. log4j.appender.stdout=org.apache.log4j.ConsoleAppender    
  3. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout    
  4. # Pattern to output the caller’s file name and line number.  
  5. #log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) – %m%n  
  6. # Print the date in ISO 8601 format  
  7. log4j.appender.stdout.layout.ConversionPattern=%d [%t] %-5p %c – %m%n    
  8. log4j.appender.R=org.apache.log4j.RollingFileAppender    
  9. log4j.appender.R.File=example.log    
  10. log4j.appender.R.MaxFileSize=100KB    
  11. # Keep one backup file  
  12. log4j.appender.R.MaxBackupIndex=1    
  13. log4j.appender.R.layout=org.apache.log4j.PatternLayout    
  14. log4j.appender.R.layout.ConversionPattern=%p %t %c – %m%n    
  15. # Print only messages of level WARN or above in the package com.foo.  
  16. log4j.logger.com.foo=WARN    

log4j.rootLogger=WARN, stdout, R log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout # Pattern to output the caller's file name and line number. #log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n # Print the date in ISO 8601 format log4j.appender.stdout.layout.ConversionPattern=%d [%t] %-5p %c - %m%n  log4j.appender.R=org.apache.log4j.RollingFileAppender log4j.appender.R.File=example.log log4j.appender.R.MaxFileSize=100KB # Keep one backup file log4j.appender.R.MaxBackupIndex=1 log4j.appender.R.layout=org.apache.log4j.PatternLayout log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n # Print  only messages of level WARN or above in the package com.foo. log4j.logger.com.foo=WARNCopy the code

Configure web.xml

[html]
view plain
copy
print
?

  1. <?xml version=“1.0” encoding= “UTF-8”? >  
  2. <web-app xmlns=“http://xmlns.jcp.org/xml/ns/javaee”  
  3.          xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”  
  4.          xsi:schemaLocation=“http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd”  
  5.          version=“3.1”>  
  6.   
  7.     <! Spring entity class (Bean) configuration file in web-INF directory –>  
  8.     <context-param>  
  9.         <param-name>contextConfigLocation</ param-name>  
  10.         <param-value>classpath:beans.xml</ param-value>  
  11.     </context-param>  
  12.   
  13.     <listener>  
  14.         <listener-class>org.springframework.web.context.ContextLoaderListener </listener-class>  
  15.     </listener>  
  16.   
  17.     <! — The front controller of this Spring Web application, responsible for handling all application requests –>  
  18.     <servlet>  
  19.         <servlet-name>springDispatcherServlet</ servlet-name>  
  20.         <servlet-class>org.springframework.web.servlet.DispatcherServlet </servlet-class>  
  21.         <init-param>  
  22.             <param-name>contextConfigLocation</ param-name>  
  23.             <param-value>classpath:springmvc.xml </param-value>  
  24.         </init-param>  
  25.         <load-on-startup>1</load-on-startup >  
  26.     </servlet>  
  27.   
  28.     <! — Map all requests to the DispatcherServlet for handling –>  
  29.     <servlet-mapping>  
  30.         <servlet-name>springDispatcherServlet</ servlet-name>  
  31.         <url-pattern>/</url-pattern >  
  32.     </servlet-mapping>  
  33.   
  34.     <! HiddenHttpMethodFilter: convert POST requests to DELETE, PUT requests –>  
  35.     <filter>  
  36.         <filter-name>HiddenHttpMethodFilter</ filter-name>  
  37.         <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter </filter-class>  
  38.     </filter>  
  39.   
  40.     <filter-mapping>  
  41.         <filter-name>HiddenHttpMethodFilter</ filter-name>  
  42.         <url-pattern>/ *</url-pattern >  
  43.     </filter-mapping>  
  44.   
  45.   
  46. </web-app>  

<? The XML version = "1.0" encoding = "utf-8"? > <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" Version = "3.1" > <! -- Specify the directory where the configuration file of the Spring entity class (Bean) is located. The default configuration file is in web-INF. <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:beans.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <! -- The front controller of this Spring Web application, responsible for handling all application requests --> <servlet> <servlet-name>springDispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <! -- Map all requests to the DispatcherServlet for handling --> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <! - the configuration HiddenHttpMethodFilter: Convert POST requests to DELETE, PUT requests --> <filter> <filter-name>HiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>HiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>Copy the code

Web. XML is used to configure Spring’s contextConfigLocation, listener, servlet, and RestFul configuration (POST to DELETE and PUT).

The environment is set up. Create test file (only action layer, dao and service are not used for the time being)



6.1. Create an entity class to be returned to mobile

FestFulBean.java

[java]
view plain
copy
print
?

  1. package com.ywl5320.appservice.bean;  
  2.   
  3. / * * 
  4.  * Created by ywl on 2017-10-2. 
  5. * /  
  6. public class FestFulBean<T> {  
  7.   
  8.     private int status;  
  9.     private T data;  
  10.     private String msg;  
  11.   
  12.     public int getStatus() {  
  13.         return status;  
  14.     }  
  15.   
  16.     public void setStatus(int status) {  
  17.         this.status = status;  
  18.     }  
  19.   
  20.     public T getData() {  
  21.         return data;  
  22.     }  
  23.   
  24.     public void setData(T data) {  
  25.         this.data = data;  
  26.     }  
  27.   
  28.     public String getMsg() {  
  29.         return msg;  
  30.     }  
  31.   
  32.     public void setMsg(String msg) {  
  33.         this.msg = msg;  
  34.     }  
  35. }  

package com.ywl5320.appservice.bean; /** * Created by ywl on 2017-10-2. */ public class FestFulBean<T> { private int status; private T data; private String msg; public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public T getData() { return data; } public void setData(T data) { this.data = data; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; }}Copy the code

UserAction.java

[java]
view plain
copy
print
?

  1. package com.ywl5320.appservice.action;  
  2.   
  3. import com.ywl5320.appservice.bean.FestFulBean;  
  4. import org.springframework.stereotype.Controller;  
  5. import org.springframework.web.bind.annotation.RequestMapping;  
  6. import org.springframework.web.bind.annotation.RequestMethod;  
  7. import org.springframework.web.bind.annotation.RequestParam;  
  8. import org.springframework.web.bind.annotation.ResponseBody;  
  9.   
  10. / * * 
  11.  * Created by ywl on 2017-10-2. 
  12. * /  
  13. @Controller  
  14. @RequestMapping(“/user”)  
  15. public class UserAction {  
  16.   
  17.     @ResponseBody  
  18.     @RequestMapping(value=“/loginByPwd.do”, method= RequestMethod.GET)  
  19.     public FestFulBean<String> loginByPwd(@RequestParam String username,  @RequestParam String password)  
  20.     {  
  21.         FestFulBean<String> restful = new FestFulBean<String>();  
  22.         restful.setData(“hello, “ + username + ” welcom to my website!”);  
  23.         restful.setStatus(0);  
  24.         restful.setMsg(“Success”);  
  25.         return restful;  
  26.     }  
  27.   
  28. }  

package com.ywl5320.appservice.action; import com.ywl5320.appservice.bean.FestFulBean; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; /** * Created by ywl on 2017-10-2. */ @Controller @RequestMapping("/user") public class UserAction { @ResponseBody @RequestMapping(value="/loginByPwd.do", method= RequestMethod.GET) public FestFulBean<String> loginByPwd(@RequestParam String username, @RequestParam String password) { FestFulBean<String> restful = new FestFulBean<String>(); restful.setData("hello, " + username + " welcom to my website!" ); restful.setStatus(0); Restful. SetMsg (" success "); return restful; }}Copy the code

The annotations are all basic in Spring. If you don’t know, you can go to the related introduction. Once you know the meaning, you will feel very simple.

Configure WAR and Tomact

7.1. Configure the WAR Package

Click File to open Project Structure



7.2. Select Artifacts and add libraries to the WAR, as shown in the figure below:



7.3. Configure tomAct

7.3.1. Open the TomAct configuration window



7.3.2 click Add TomAct



7.3.3 fill in the name of TOMact and add the WAR file created in 7.2, as shown in the picture. Click Fix in the lower right corner to add it automatically



Publish the project and visit

Click the Tomact Mutiny run button and the OK status will be displayed below the left of the successful release



Such a simple server prototype is built, behind will slowly add such functions as database, interceptor and so on, well finally I wish you a happy National Day Mid-Autumn Festival double festival happy family!