SpringMVC構建Restful。

由於spring是依賴jackson來生成json,須要添加jar包。html

pom.xml文件添加依賴。java

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.3</version>
</dependency>

web.xml文件web

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="2.2">
    <display-name>mybatis</display-name>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-application.xml</param-value>
    </context-param>
    <filter>
        <description>字符集過濾器</description>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <description>字符集編碼</description>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <listener>
        <description>spring監聽器</description>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- 防止spring內存溢出監聽器 -->
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>
    <!-- spring mvc servlet -->
    <servlet>
        <description>spring mvc servlet</description>
        <servlet-name>springMvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <description>spring mvc 配置文件</description>
            <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>
    <!-- 配置session超時時間,單位分鐘 -->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
</web-app>
View Code

其中是注意設置spring mvc servlet中攔截請求路徑。redis

spring-application.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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">

    <!-- 引入屬性文件 -->
    <context:property-placeholder location="classpath:config.properties" />

    <!-- 自動掃描(自動注入) -->
    <context:component-scan base-package="sy.service" />
    
    <import resource="spring-mybatis.xml"/>
    <!-- <import resource="spring-redis.xml"/> -->
    <!-- <import resource="spring-memcached.xml"/>
    <import resource="spring-mongodb.xml"/>
    <import resource="spring-security.xml"/> -->
</beans>
View Code

spring-mvc.xml文件mongodb

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-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/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <!-- 自動掃描controller包下的全部類,使其認爲spring mvc的控制器 -->
    <context:component-scan base-package="sy.controller" />

    <!-- 避免IE執行AJAX時,返回JSON出現下載文件 -->
    <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </bean>

    <!-- 啓動Spring MVC的註解功能,完成請求和註解POJO的互相轉換映射 輸出對象轉JSON的支持 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter" /><!-- json轉換器 -->
            </list>
        </property>
    </bean>

    <!-- 對模型視圖名稱的解析,即在模型視圖名稱添加先後綴 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsp" />

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding">
            <value>UTF-8</value>
        </property>
        <property name="maxUploadSize">
            <value>32505856</value><!-- 上傳文件大小限制爲31M,31*1024*1024 -->
        </property>
        <property name="maxInMemorySize">
            <value>4096</value>
        </property>
    </bean>

</beans>
View Code

這個文件中對restful的支持主要是HttpMessageConverter的配置。json

HttpMessageConverter接口,須要開啓<mvc:annotation-driven  />。瀏覽器

測試Controller編寫spring-mvc

pojo類restful

package sy.model;

import java.util.Date;

public class Myuser {
    private Integer id;

    private String name;

    private String sex;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex == null ? null : sex.trim();
    }

    @Override
    public String toString() {
        return "Myuser [id=" + id + ", name=" + name + ", sex=" + sex
                + ", province=" + province + ", createdate=" + createdate
                + ", updatedate=" + updatedate + "]";
    }
    
}
View Code

Controller類

package sy.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
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;

import com.alibaba.fastjson.JSONObject;

import sy.model.Myuser;

@Controller
public class RestfulController {
    
    @RequestMapping(value="/hello",produces = "text/plain;charset=UTF-8")
    public @ResponseBody
    String hello1(){
        return "index";
    }
    
    @RequestMapping(value="/hello")
    String hello2(){
        return "index";
    }
    
    @RequestMapping(value = "/say/{msg}", produces = "application/json;charset=UTF-8")
    public @ResponseBody
    String say(@PathVariable(value = "msg") String msg) {
        return "{\"msg\":\"you say:'" + msg + "'\"}";
    }
@RequestMapping(value = "/user/{id:\\d+}", method = RequestMethod.GET) public @ResponseBody Myuser getuser(@PathVariable("id") int id) throws UnsupportedEncodingException { Myuser myuser = new Myuser(); myuser.setName("張三"); myuser.setSex("男"); myuser.setId(id); return myuser; } @RequestMapping(value = "/user/{id:\\d+}", method = RequestMethod.DELETE) public @ResponseBody Object deleteuser(@PathVariable("id") int id) { JSONObject jsonObject = new JSONObject(); jsonObject.put("msg", "刪除人員信息成功"); return jsonObject; } @RequestMapping(value = "/user", method = RequestMethod.POST) public @ResponseBody Object adduser(Myuser user) { JSONObject jsonObject = new JSONObject(); jsonObject.put("msg", "註冊人員信息成功"); return jsonObject; } @RequestMapping(value = "/user", method = RequestMethod.PUT) public @ResponseBody Object updateuser(Myuser user) { JSONObject jsonObject = new JSONObject(); jsonObject.put("msg", "更新人員信息成功"); return jsonObject; } @RequestMapping(value = "/user", method = RequestMethod.PATCH) public @ResponseBody List<Myuser> listuser(@RequestParam(value = "name", required = false, defaultValue = "") String name) { List<Myuser> lstusers = new ArrayList<Myuser>(); Myuser myuser = new Myuser(); myuser.setName("張三"); myuser.setSex("男"); myuser.setId(101); lstusers.add(myuser); Myuser myuser2 = new Myuser(); myuser2.setName("李四"); myuser2.setSex("女"); myuser2.setId(102); lstusers.add(myuser2); Myuser myuser3 = new Myuser(); myuser3.setName("王五"); myuser3.setSex("男"); myuser3.setId(103); lstusers.add(myuser3); return lstusers; } }

restful的實現主要是依賴@ResponseBody、@RequestBody註解和HttpMessageConverter來實現pojo對象和對應協議的轉換。

Spring 3.X系列增長了新註解@ResponseBody,@RequestBody 

  • @RequestBody 將HTTP請求正文轉換爲適合的HttpMessageConverter對象。
  • @ResponseBody 將內容或對象做爲 HTTP 響應正文返回,並經過Adapter調用合適的HttpMessageConverter來轉換對象,寫入HttpResponse輸出流,返回給瀏覽器。

HttpMessageConverter接口,須要開啓<mvc:annotation-driven  />。 
AnnotationMethodHandlerAdapter將會初始化7個轉換器,能夠經過調用AnnotationMethodHandlerAdapter的getMessageConverts()方法來獲取轉換器的一個集合 List<HttpMessageConverter> 

引用
ByteArrayHttpMessageConverter 
StringHttpMessageConverter 
ResourceHttpMessageConverter 
SourceHttpMessageConverter 
XmlAwareFormHttpMessageConverter 
Jaxb2RootElementHttpMessageConverter 
MappingJacksonHttpMessageConverter
有關@ResponseBody,@RequestBody,@PathVariable 的詳細信息,參考《@ResponseBody,@RequestBody,@PathVariable 》
好比上述controller中的hello1和hello2方法,其中hello1使用了註解@ResponseBody,那麼會將string經過httpMsessageConverter直接轉換,寫入response;而hello2方法沒有使用註解,那麼就會根據spring-mvc.xml中配置的解析器,尋找jsp頁面,並寫入response,返回給瀏覽器。
 
總結:
  1.和springmvc配置不同的地方主要是controller中的方法也是用@ResponseBody註解,將Object轉成相對應的協議(通常是xml和json)寫入到response中,返回給瀏覽器。
  2.必定要開啓<mvc:annotation-driven  />
  3.方法RequestMapping設置必定要遵循Restful規範風格。
相關文章
相關標籤/搜索