移動大腦-SpringMVc搭建RestFul後臺服務(一)-環境搭建

 

我的視頻課程(基礎):《(NDK)FFmpeg打造Android萬能音頻播放器》

我的視頻課程(進階):《(NDK)FFmpeg打造Android視頻播放器》

我的視頻課程(編碼直播推流):《Android視頻編碼和直播推流》

 

目錄:

        移動大腦-SpringMVc搭建RestFul後臺服務(一)-環境搭建

        移動大腦-SpringMVc搭建RestFul後臺服務(二)-配置mysql數據庫

        移動大腦-SpringMVc搭建RestFul後臺服務(三)-RestFul接口編寫(模擬用戶註冊登錄)

        移動大腦-SpringMVc搭建RestFul後臺服務(四)-添加Token攔截器

        移動大腦-SpringMVc搭建RestFul後臺服務(五)-支付寶支付

        移動大腦-SpringMVc搭建RestFul後臺服務(六)-微信支付(Android)

        移動大腦-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

下載地址(https://www.jetbrains.com/idea/download/),破解也問問度娘吧,很容易的。

二、創建項目

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狀態

 

 

 

 

這樣一個簡單的服務器雛形就搭建好了,後面還會慢慢的添加諸如數據庫、攔截器等等功能,好了最後祝大家國慶中秋雙節快樂闔家歡樂!

源碼下載:GitHub(AppServiceRestFul

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章