移動大腦-SpringMVc搭建RestFul後臺服務(一)-環境搭建
目錄:
話說作為一個移動端的程式猿來寫後端服務程式是不是很不專業!其實不然,雖說不能達到很好的效能和很好的健壯性,但對於理解整體的業務邏輯是很有幫助的;再者如果要開發一個簡單的有後端有前端的移動APP來說,一個人也能完成所有工作,還是挺好的。這裡就給大家介紹怎樣用Spring mvc來搭建RestFul型別的後端服務。
還是先看看這篇文章要達到的效果:
訪問URL:http://localhost:8080/user/loginByPwd.do?username=ywl5320&password=123456(這裡為了方便測試,使用的是get方法,正式專案中應該用post方法)
效果圖如下:
這就是一個簡單的restful型別的後端服務程式了。那麼我們開始搭建吧!
一、環境搭建
1.1、安裝Tomact
網上很多相關的教程,這裡就不介紹了,如果是在不會也可以問我。
1.2、安裝Intellij idea
二、建立專案
2.1、建立空的maven專案
2.2、填寫GroupId(可填包名)和Artifactld(可填專案名稱)
2.3、填寫專案名稱和儲存路徑完成專案建立
二、新增Spring支援
上一步只是建立了maven的一個空專案,現在需要新增Spring的支援,使之成為一個web專案。
這樣就把為專案添加了Spring的支援了。
三、通過maven新增Spring的庫和一下基礎庫(json,日誌等)
在檔案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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.ywl5320.appservice</groupId> <artifactId>AppService</artifactId> <version>1.0-SNAPSHOT</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>4.2.6.RELEASE</spring.version> <hibernate.version>5.0.12.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> <!-- 使用SpringMVC需配置 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- json --> <dependency> <groupId>com.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>
新增完後,並構建一下專案才能右鍵新增spring相關的檔案。
四、在resources中新增beans.xml、springmvc.xml和log4j.properties
4.1、新增beans.xml
beans.xml檔案內容如下:spring自動掃描制定包名下的所有註解
<?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>
springmvc.xml如下:新增servlet和註解驅動
<?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>
log4j.properties內容如下:直接複製即可
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=WARN
五、配置web.xml
<?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">
<!-- 指定Spring 實體類(Bean)的配置檔案所在目錄,預設配置在WEB-INF目錄下,這裡我們resources裡面的,管理更方便-->
<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>
<!-- 配置 HiddenHttpMethodFilter: 把 POST 請求轉為 DELETE、PUT 請求 -->
<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>
web.xml中主要配置Spring的contextConfigLocation、listener、servlet和RestFul配置(post轉成delete和put)
這樣環境就搭建完成了。
六、最後建立測試檔案(這裡只用了action層,dao和service暫時沒用)
6.1、建立返回給移動端的實體類
FestFulBean.java
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;
}
}
UserAction.java
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("成功");
return restful;
}
}
其中的註解都是Spring中的基礎,不知道可以去看看相關的介紹,知道意思了就會覺得很簡單了。
七、配置war和tomact
7.1、配置war包
點選File開啟Project Structure
7.2、選擇Artifacts,並新增相關庫到war中,如圖:
7.3、配置tomact
7.3.1、開啟tomact配置視窗
7.3.2、點選新增tomact
7.3.3、填寫tomact名稱並新增7.2中建立的war檔案,如圖,點選右下角fix可自動新增
八、釋出專案並訪問
點選tomact叛變的執行按鈕即可,釋出成功左下邊會顯示OK狀態
這樣一個簡單的伺服器雛形就搭建好了,後面還會慢慢的新增諸如資料庫、攔截器等等功能,好了最後祝大家國慶中秋雙節快樂闔家歡樂!