spring4整合rest风格配置

最近手头上有个新项目,打算采用前端js渲染+后端调用restful风格api获取数据。于是决定把之前一个项目的springMVC改造成符合restful风格的框架。找了很多资料,也遇到不少坑,下面把相关心得整理下。

很多人以为resutful是一种标准,要按照什么标准才行,其实restful是一种软件架构风格,设计风格而不是标准,只是提供了一组设计原则和约束条件。说白了它就是个风格,所有的软件框架设计都是为了提升效率,而不是死板的标准。

1配置web.xml

<filter>
        <filter-name>HttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>HttpMethodFilter</filter-name>
        <url-pattern>*.json</url-pattern>
    </filter-mapping>
     <filter-mapping>
        <filter-name>HttpMethodFilter</filter-name>
        <url-pattern>*.xml</url-pattern>
    </filter-mapping>
     <filter-mapping>
        <filter-name>HttpMethodFilter</filter-name>
        <url-pattern>*.htm</url-pattern>
    </filter-mapping>

restful风格是面向资源,http1.1协议天生自带get(查询),post(创建),put("修改"),delete("删除")4种请求方式,但是因为部分浏览器ajax和表单提交只支持get和post,该filter就是用于实现put和delete提交请求。

<form action="demo/test.json">
		<input type="hidden" name="method" value="put">

	</form>

2.添加springMVC配置,因为上一个项目是采用velocity模板渲染页面,因此也保留了对velocity模板渲染的

<!-- velocity config -->
    <bean id="velocityConfigurer" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
    	<property name="configLocation"><value>classpath:velocity.properties</value></property>   
        <property name="resourceLoaderPath">
            <value>view</value>
        </property>
        <property name="velocityProperties">
            <props>
                <prop key="input.encoding">UTF-8</prop>
                <prop key="output.encoding">UTF-8</prop>
                <prop key="contentType">text/html;charset=UTF-8</prop>
                <prop key="velocimacro.library">macro/macros.vm</prop>
            </props>
        </property>
    </bean>

	<bean id="VelocityViewResolver"
        class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver">
        <property name="order" value="2" />
        <property name="viewClass"
            value="com.lyun.web.servlet.view.velocity.CspVelocityLayoutView">
        </property>
<!--       是否缓存模板   -->
        <property name="cache" value="false" />
        <property name="contentType" value="text/html;charset=UTF-8"></property>
<!--       	是否使用spring对宏定义的支持 -->
        <property name="exposeSpringMacroHelpers" value="true"></property>
        <property name="prefix" value=""></property>
        <property name="suffix" value=".vm"></property>
<!--        toolbox配置文件路径  -->
        <property name="toolboxConfigLocation"
            value="/WEB-INF/toolbox.xml">
        </property>
        <property name="layoutUrl" value="layout/default.vm"></property>
        <property name="layoutKey" value="layout"></property>
        <property name="screenContentKey" value="screen_content"></property>
    </bean> 
    <!-- 根据客户端的不同的请求决定不同的view进行响应, 如 /blog/1.json /blog/1.xml -->  
    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">  
    	<property name="order" value="1" />
        <!-- 设置为true以忽略对Accept Header的支持 -->  
        <property name="ignoreAcceptHeader" value="true" />  
          
        <!-- 在没有扩展名时即: "/blog/1" 时的默认展现形式 -->  
        <property name="defaultContentType" value="text/html" />  
  
        <!-- 扩展名至mimeType的映射,即 /blog.json => application/json -->  
        <property name="mediaTypes">  
            <map>  
                <entry key="html" value="text/html" />  
                <entry key="pdf" value="application/pdf" />  
                <entry key="xsl" value="application/vnd.ms-excel" />  
                <entry key="xml" value="application/xml" />  
                <entry key="json" value="application/json" />  
            </map>  
        </property>  
      
        <!-- 用于开启 /blog/123?format=json 的支持 -->  
        <property name="favorParameter" value="false" />  
        <property name="viewResolvers">  
            <list>  
                <bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />  
      <!--           <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
                    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />  
                    <property name="prefix" value="/pages" />  
                    <property name="suffix" value=".jsp"></property>  
                </bean>   -->
            </list>  
        </property>  
        <property name="defaultViews">  
            <list>  
                <!-- for application/json -->  
                <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />  
                <!-- for application/xml -->  
                
                <bean class="org.springframework.web.servlet.view.xml.MarshallingView">   
                    <property name="marshaller">   
                        <bean class="org.springframework.oxm.xstream.XStreamMarshaller">
                        	
                        </bean>
                    </property>   
                </bean>   
                
            </list>  
        </property>  
    </bean>

3controller演示

@RequestMapping(value = "/test", method = RequestMethod.POST)
	@ResponseStatus(HttpStatus.CREATED)
	// 201
	public UserDetails createUser() {

		UserDetails userDetails = new UserDetails();
		userDetails.setUserName("Krishna");
		userDetails.setEmailId("[email protected]");
		userDetails.setBirthday(new Date());
		return userDetails; // json
	}

	@RequestMapping(value = "/test", method = RequestMethod.PUT)
	// 205
	@ResponseStatus(HttpStatus.RESET_CONTENT)
	public UserDetails updateUser() {
		UserDetails userDetails = new UserDetails();
		userDetails.setUserName("Krishna");
		userDetails.setEmailId("[email protected]");
		userDetails.setBirthday(new Date());
		return userDetails;
	}

相关推荐