---
title: "spring rest 案例"
author: "lauy"
date: "2012-09-07T07:59:41Z"
tags: ["srping rest"]
categories: ["企业架构"]
slug: "spring-rest"
draft: false
lastmod: "2012-09-09T20:01:54Z"
id: 1673209
url: "https://lauy.iteye.com/blog/1673209"
---

![spring rest](http://hi.csdn.net/attachment/201106/21/4381500_1308662225n5vx.jpg)

      这是一个rest风格的访问，Spring从3.0开始将全面支持rest。不得不感叹Spring的强悍。

      项目结构：

![结构](http://hi.csdn.net/attachment/201106/21/4381500_1308664259VTRg.jpg)

      第一步永远是配置，使用框架永远都是先有配置，在web.xml中的配置：

&lt;?xml version="1.0" encoding="UTF-8"?&gt;  
&lt;web-app version="3.0"  
    xmlns="http://java.sun.com/xml/ns/javaee"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  
    http://java.sun.com/xml/ns/javaee/web-app\_3\_0.xsd"&gt;  
  &lt;display-name&gt;&lt;/display-name&gt;     
  &lt;context-param&gt;  
        &lt;!--rest配置文件的路径，貌似不配置也是加载这个地址，这个地方有点疑问，大家指点指点--&gt;  
      &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;  
      &lt;param-value&gt;/WEB-INF/rest-servlet.xml&lt;/param-value&gt;  
  &lt;/context-param&gt;  
  &lt;listener&gt;  
      &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;  
  &lt;/listener&gt;  
  &lt;servlet&gt;  
        &lt;!-- 配置一个Servlet，有这个Servlet统一调度页面的请求 --&gt;  
      &lt;servlet-name&gt;rest&lt;/servlet-name&gt;  
      &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;  
      &lt;load-on-startup&gt;2&lt;/load-on-startup&gt;  
  &lt;/servlet&gt;  
  &lt;servlet-mapping&gt;  
        &lt;!-- 映射路径，不要写成了/\*那样会拦截所有的访问，连JSP页面都访问不了 --&gt;  
      &lt;servlet-name&gt;rest&lt;/servlet-name&gt;  
      &lt;url-pattern&gt;/&lt;/url-pattern&gt;  
  &lt;/servlet-mapping&gt;  
  &lt;welcome-file-list&gt;  
      &lt;welcome-file&gt;/index.jsp&lt;/welcome-file&gt;  
  &lt;/welcome-file-list&gt;  
&lt;/web-app&gt;

   第二步：配置rest-servlet.xml这个文件

&lt;?xml version="1.0" encoding="UTF-8"?&gt;  
&lt;beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee"  
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:aop="http://www.springframework.org/schema/aop"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"  
    default-lazy-init="true"&gt;

  &lt;description&gt;Spring公共配置&lt;/description&gt;

  &lt;!--检测注解--&gt;  
  &lt;context:component-scan base-package="com.liqiu" /&gt;  
  &lt;bean   class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /&gt;  
  &lt;bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /&gt;  
&lt;!-- 注册视图解析器，说白了就是根据返回值指定到某个页面 --&gt;     
  &lt;bean id="viewResolver"   class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt;  
    &lt;property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /&gt;  
    &lt;property name="prefix" value="/"&gt;&lt;/property&gt; &lt;!--页面文件的路径，在根目录下--&gt;  
   &lt;/bean&gt;  
&lt;/beans&gt;

 第三步：具体实现类

package com.liqiu.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;

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;

@Controller  
@RequestMapping("/simple")  
public class SimpleController {  
    //映射路径/simple/index当访问这个路径时，执行这个方法  
    @RequestMapping("/index")  
    public String index(HttpServletRequest request ,HttpServletResponse response){  
               //response,request会自动传进来  
        request.setAttribute("message", "Hello,This is a example of Spring3 RESTful!");  
        return "index.jsp";  
    }  
    //根据ID获取不同的内容，通过@PathVariable 获得属性  
    @RequestMapping(value="/{id}",method=RequestMethod.GET)  
    public String get(@PathVariable String id,HttpServletRequest request ,HttpServletResponse response) throws IOException{  
        request.setAttribute("message", "Hello,This is a example of Spring3 RESTful!&lt;br/&gt;ID:"+id+"");  
        //response.getWriter().write("You put id is : "+id);  
        return "index.jsp";  
        //return null;  
    }  
}

index.jsp页面：

&lt;%@ page language="java" pageEncoding="UTF-8"%&gt;  
&lt;html&gt;  
  &lt;head&gt;  
    &lt;title&gt;Spring3 RESTful&lt;/title&gt;  
   &lt;/head&gt;  
   
  &lt;body&gt;  
    ${message}  
   &lt;/body&gt;  
&lt;/html&gt;

在浏览器中输入：[http://localhost:8080/SpringREST/simple/index/](http://localhost:8080/SpringREST/simple/index/) ，就可以看到效果。

    也可以在页面输入不同的参数，获得不同的内容，输入地址：[http://localhost:8080/SpringREST/simple/88888](http://localhost:8080/SpringREST/simple/88888) ，这次执行的就是get方法，通过注解获取ID值，效果：

![spring rest id](http://hi.csdn.net/attachment/201106/21/4381500_1308663322wMmm.jpg)

    关于Spring rest 对于Ajax的支持，其实响应Ajax就是通过response返回一个字符串到页面，既然能获得response对象，那问题就迎刃而解了，我们改造下get方法：

@RequestMapping(value="/{id}",method=RequestMethod.GET)  
    public String get(@PathVariable String id,HttpServletRequest request ,HttpServletResponse response) throws IOException{  
        //request.setAttribute("message", "Hello,This is a example of Spring3 RESTful!&lt;br/&gt;ID:"+id+"");  
        response.getWriter().write("You put id is : "+id);  
        //return "index.jsp";  
        return null;  
    }

   改造index.jsp页面：

&lt;%@ page language="java" pageEncoding="UTF-8"%&gt;  
&lt;html&gt;  
  &lt;head&gt;  
    &lt;title&gt;Spring3 RESTful&lt;/title&gt;  
    &lt;SCRIPT TYPE="text/javascript"&gt;  
            function go(value){  
                var url = "/SpringREST/simple/"+value+"/";  
                var request =  new XMLHttpRequest();  
                request.open("GET", url, true);  
                request.setRequestHeader("Content-Type","application/x-javascript;");  
                request.onreadystatechange = function() {  
                    if (request.readyState == 4) {  
                        if (request.status == 200){  
                            if (request.responseText) {  
                                document.getElementById("text").innerHTML = request.responseText;  
                            }  
                        }  
                    }  
                };  
                request.send(null);  
            }  
        &lt;/SCRIPT&gt;  
  &lt;/head&gt;  
   
  &lt;body&gt;  
    ${message}  
    &lt;br&gt;  
    Input the id of you will access object:&lt;input id="id" type="text" size="7"&gt;&lt;input type="button" value="Go" onclick="go(document.getElementById('id').value)"&gt;  
      &lt;div id="text"&gt;&lt;/div&gt;  
  &lt;/body&gt;  
&lt;/html&gt;

访问[http://localhost:8080/SpringREST/simple/index/](http://localhost:8080/SpringREST/simple/index/) ，在页面里的输入框中输入值，可以看到返回的数据：

![spring rest ajax](http://hi.csdn.net/attachment/201106/21/4381500_1308663986636w.jpg)

转载：http://blog.csdn.net/leecho571/article/details/6559758