JavaWeb專案入門

MEMORYLORRY發表於2017-05-13

SpringMVC專案入門(Maven)

原始碼請見共享目錄CSDN/Java Web(Maven)/1.SpringMVC專案入門

一、目標

  • 自定義控制器(controller)
  • 使用json解析(FastJson&Jackson)

二、工程結構

新建一個maven-archetype-webapp工程,增加程式碼,專案結構如下:
這裡寫圖片描述

三、匯入jar檔案

在pom.xml增加如下spring-webmvc的依賴,spring-webmvc底層依賴的jar可不填,maven會通過網路去找到spring-aop、spring-beans等jar。

pom.xml 中部分程式碼

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.8.RELEASE</version>
        </dependency>
    </dependencies>

這裡寫圖片描述

四、程式碼

4.1、自定義控制器

第一步:在工程的src/main/java目錄下的cn.dectfix.controller包中新建Test.java,程式碼如下:

package cn.dectfix.controller;

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

@Controller
public class Test {
    @RequestMapping("foo1")
    @ResponseBody
    public String foo1(){
        System.out.println("Hello World1!");
        return "Hello";
    }
    @RequestMapping("foo2")
    @ResponseBody
    public String foo2(){
        System.out.println("Hello World2!");
        return "Hello";
    }
}
  • 使用@Controller註解註釋該類是控制器類;
  • 使用@RequestMapping註解指定每個方法的訪問URL,這裡我定義了http://127.0.0.1/foo1http://127.0.0.1/foo1foo2兩個控制器。
  • 使用@ResponseBody註解,指定控制器將內容或物件作為 HTTP 響應正文返回。

第二步:在工程的src/main/resources目錄下,新建spring-mvc.xml檔案,詳細程式碼如下:

<?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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
            http://www.springframework.org/schema/mvc   
            http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd   
            http://www.springframework.org/schema/context   
            http://www.springframework.org/schema/context/spring-context-3.0.xsd   
            http://www.springframework.org/schema/aop   
            http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
            http://www.springframework.org/schema/tx   
            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">
    <!-- 掃描actions元件 -->
    <context:component-scan base-package="cn.dectfix.controller"></context:component-scan>
</beans>    

spring-mvc.xml檔案中,context:component-scan標籤是用於掃描出被@Controller/@Service等註解註釋的類。這裡我們要寫控制器,會用到@Controller註解。

第三步:配置web.xml檔案,增加Spring MVC的DispatcherServlet,用於攔截帶斜槓的URL,同時也可以增加攔截帶*.js等的請求。(注意web.xml中contextConfigLocation引數的值是第一步中的檔案位置

web.xml 程式碼

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
    <display-name>Archetype Created Web Application</display-name>
    <!-- 配置springmvc -->
    <servlet>
        <servlet-name>springMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.js</url-pattern>
    </servlet-mapping>
</web-app>

第四步:啟動工程,並訪問http://127.0.0.1/foo1,可以看到控制檯和網頁顯示出的資訊如下圖:
這裡寫圖片描述

4.2、json解析

在4.1節中定義的如public String foo1(){…}返回值為String型別的控制器,能夠正常的返回字串,那麼能不能返回整型、浮點、布林、引用等型別呢?答案是需要用json解析!

繼續在4.1的基礎上增加User.java和Test2.java的程式碼!

package cn.dectfix.controller;

public class User {
    private String username;
    private String password;
    private int uid;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public int getUid() {
        return uid;
    }
    public void setUid(int uid) {
        this.uid = uid;
    }
}
package cn.dectfix.controller;

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

@Controller
public class Test2 {
    @RequestMapping("test1")
    @ResponseBody
    public int helo1(){
        return 1;
    }
    @RequestMapping("test2")
    @ResponseBody
    public boolean helo2(){
        return true;
    }
    @RequestMapping("test3")
    @ResponseBody
    public User helo3(){
        User u = new User();
        u.setUid(10010);
        u.setUsername("memorylorry");
        u.setPassword("123456");
        return u;
    }
}

寫完後,允許起伺服器,發現訪問test1、test2、test3這些控制器,都顯示資源型別不接受,那這裡需要用到json解析,下面分FaskJson和Jackson解析來說明。
這裡寫圖片描述

4.2.1 方法1-使用FastJson解析

在pom.xml中增加依賴(fastjson內部用到了jackson):

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.29</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.7.5</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.7.5</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.7.5</version>
</dependency> 

在spring-mvc.xml檔案中,增加FastJson外掛,發現遇到錯誤了,說mvc:annotation-drivern中的children項是空的。
這裡寫圖片描述

修改beans標籤的xsi:schemaLocation的xsd的版本都改為4.3問題得以解決,最後spring-mvc.xml改成了如下所示:

<?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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
            http://www.springframework.org/schema/beans/spring-beans-4.3.xsd   
            http://www.springframework.org/schema/mvc   
            http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd   
            http://www.springframework.org/schema/context   
            http://www.springframework.org/schema/context/spring-context-4.3.xsd   
            http://www.springframework.org/schema/aop   
            http://www.springframework.org/schema/aop/spring-aop-4.3.xsd   
            http://www.springframework.org/schema/tx   
            http://www.springframework.org/schema/tx/spring-tx-4.3.xsd ">
    <!-- 掃描actions元件 -->
    <context:component-scan base-package="cn.dectfix.conntroller"></context:component-scan>

        <mvc:annotation-driven>

        <mvc:message-converters>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/plain;charset=UTF-8</value>
                        <value>text/html;charset=UTF-8</value>
                        <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>

4.2.2 方法2-使用Jackson解析

在pom.xml中增加Jackson的依賴:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.7.5</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.7.5</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.7.5</version>
    </dependency> 

在spring-mvc.xml檔案中,增加Jackson外掛,spring-mvc.xml改成了如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
    ">
    <context:component-scan base-package="cn.dectfix.controller" />
    <context:component-scan base-package="cn.dectfix.dto" />
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/plain;charset=UTF-8</value>
                        <value>text/html;charset=UTF-8</value>
                        <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>

在完成4.2.1或4.2.2節的json解析配置後,訪問test3地址,會直接向頁面輸出如下內容。

這裡寫圖片描述

相關文章