Spring MVC 3.0 RESTful controller

本文介绍了一个基于Spring框架的RESTful风格API的设计与实现案例,通过具体代码展示了如何使用Spring MVC来创建RESTful控制器,并提供了详细的配置示例,包括路径参数、请求参数的处理方式及返回结果的格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. Controller 代码非常简单

 

package org.pprun.hjpetstore.web.rest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.pprun.hjpetstore.persistence.jaxb.Products;
import org.pprun.hjpetstore.service.rest.HjpetstoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
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.servlet.ModelAndView;

/**
 * A RESTful controller supplies search products by keyword which will be exposed to public access.
 * The access authenticated by api-key as Google/Yahoo/Amazon Web Service.
 *
 * @author <a href="mailto:quest.run@gmail.com">pprun</a>
 */
@Controller
public class HjpetstoreController extends BaseController {

    private static final Log log = LogFactory.getLog(HjpetstoreController.class);
    private HjpetstoreService hjpetstoreService;

    @Required
    @Autowired
    public void setHjpetstoreService(HjpetstoreService hjpetstoreService) {
        this.hjpetstoreService = hjpetstoreService;
    }

    /**
     * RESTful match path '/products/{keyword}' with apikey as request parameter.
     *
     * <p>
     * For example: user pprun <br />
     * {@code
     * curl -u pprun:pprunpprun -H 'Accept: application/xml' 'http://localhost:8080/hjpetstore/rest/products/dog?apikey=bc7163dab8eb79a9867b4604b46b0328e9ace555ef5d9526e1fcd748f9864bf85d59e97c044a2d9795736753c2b0d77cd085eb05d854e5849f42f37f85851220&page=1&max=100'
     * }
     *
     * @param apiKey
     * @param keyword
     * @return
     */
    @RequestMapping(value = "/products/{keyword}", method = RequestMethod.GET)
    public ModelAndView getProductsByKeyword(
            @RequestParam("apikey") String apiKey,
            @RequestParam("page") int page,
            @RequestParam("max") int max,
            @PathVariable("keyword") String keyword) {

        if (log.isDebugEnabled()) {
            log.debug("HjpetstoreController is processing request for keyword: " + keyword);
        }
        Products products = hjpetstoreService.searchProductList(apiKey, keyword, page, max);

        ModelAndView mav = new ModelAndView("products");
        mav.addObject(products);
        return mav;
    }
}
 

 

 

2. Spring context xml

 

    <!--
            To enable autodetection of such annotated controllers, you add component scanning to your configuration.
            The controllers are autodetected POJOs labeled with the @Controller annotation.
    -->
    <context:component-scan base-package="org.pprun.hjpetstore.web.rest"/>

    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>

    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <!--         19.9.2 HTTP Message Conversion
            several main media type converters have been registered,
            but if we overwrite tihs property, we have to list all our need-->
       
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
                    <property name="supportedMediaTypes">
                        <list>
                            <value>application/xml</value>
                            <value>text/xml</value>
                            <!-- curl set this type automatically -->
                            <value>application/x-www-form-urlencoded</value>
                        </list>
                    </property>
                    <property name="marshaller" ref="jaxb2Marshaller" />
                    <property name="unmarshaller" ref="jaxb2Marshaller" />
                </bean>
                <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
            </list>
        </property>
    </bean>

    <!-- view resolver -->
    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="mediaTypes">
            <map>
                <entry key="xml" value="application/xml"/>
                <entry key="html" value="text/html"/>
            </map>
        </property>
        <property name="viewResolvers">
            <list>
                <bean class="org.springframework.web.servlet.view.BeanNameViewResolver" p:order="1"/>

                <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
                    <property name="prefix" value="/WEB-INF/jsp/shop/"/>
                    <property name="suffix" value=".jsp"/>
                </bean>
            </list>
        </property>
    </bean>


    <!-- searchProducts rest GET -->
    <bean name="products"  class="org.springframework.web.servlet.view.xml.MarshallingView">
        <constructor-arg ref="jaxb2Marshaller" />
    </bean>


    <bean id="jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
        <property name="classesToBeBound">
            <list>
                <value>org.pprun.hjpetstore.persistence.jaxb.Products</value>
            </list>
        </property>
         we can depend on the xsd file for automatically validation
         <property name="schema" value="classpath:org/springframework/oxm/schema.xsd"/>
    </bean>-->
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值