`

Spring3.0实现REST实例

阅读更多
转自:http://blog.csdn.net/leecho571/article/details/6559758

关于REST是什么东西,在这里我就不再多说,大家可以去http://blog.csdn.net/pilou5400/archive/2010/12/24/6096861.aspx看看介绍,直接切入主题:



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


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

<?xml version="1.0" encoding="UTF-8"?>
<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">
  <display-name></display-name>	
  <context-param>
        <!--rest配置文件的路径,貌似不配置也是加载这个地址,这个地方有点疑问,大家指点指点-->
  	<param-name>contextConfigLocation</param-name>
  	<param-value>/WEB-INF/rest-servlet.xml</param-value>
  </context-param>
  <listener>
  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <servlet>
        <!-- 配置一个Servlet,有这个Servlet统一调度页面的请求 -->
  	<servlet-name>rest</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	<load-on-startup>2</load-on-startup>
  </servlet>
  <servlet-mapping>
        <!-- 映射路径,不要写成了/*那样会拦截所有的访问,连JSP页面都访问不了 -->
  	<servlet-name>rest</servlet-name>
  	<url-pattern>/</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
  	<welcome-file>/index.jsp</welcome-file>
  </welcome-file-list>
</web-app>




第二步:配置rest-servlet.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: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">

  <description>Spring公共配置</description>

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



第三步:具体实现类
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!<br/>ID:"+id+"");
		//response.getWriter().write("You put id is : "+id);
		return "index.jsp";
		//return null;
	}
}





index.jsp页面:

<%@ page language="java" pageEncoding="UTF-8"%>
<html>
  <head>
    <title>Spring3 RESTful</title>
   </head>
  
  <body>
    ${message}
   </body>
</html>


在浏览器中输入:http://localhost:8080/SpringREST/simple/index/,就可以看到效果。

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

关于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!<br/>ID:"+id+"");
		response.getWriter().write("You put id is : "+id);
		//return "index.jsp";
		return null;
	}


改造index.jsp页面:
<%@ page language="java" pageEncoding="UTF-8"%>
<html>
  <head>
    <title>Spring3 RESTful</title>
    <SCRIPT TYPE="text/javascript">
            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);
            }
        </SCRIPT>
  </head>
  
  <body>
    ${message}
    <br>
    Input the id of you will access object:<input id="id" type="text" size="7"><input type="button" value="Go" onclick="go(document.getElementById('id').value)">
  	<div id="text"></div>
  </body>
</html>



访问http://localhost:8080/SpringREST/simple/index/,在页面里的输入框中输入值,可以看到返回的数据
分享到:
评论

相关推荐

    Spring3.0 rest 实例

    Spring3.0 rest 实例,实现rest风格的访问

    spring mvc 3.0 rest 风格

    spring mvc 包括 实现各种结构url 和get post 方式 跳转传参 提交等实例,有注释 是初学springmvc 必备入门级 参考.只需5分钟,看了代码就能让你掌握 spring mvc rest 的各种实现

    [spring 3.0] mvc 整合 restful 、maven实例 下载

    NULL 博文链接:https://nothing-whoami.iteye.com/blog/1740669

    Spring+3.x企业应用开发实战光盘源码(全)

     第15章:对Spring MVC框架进行详细介绍,对REST风格编程方式进行重点讲解,同时还对Spring 3.0的校验和格式化框架如果和Spring MVC整合进行讲解。  第16章:有别于一般书籍的单元测试内容,本书以当前最具实战的...

    陈开雄 Spring+3.x企业应用开发实战光盘源码.zip

     第15章:对Spring MVC框架进行详细介绍,对REST风格编程方式进行重点讲解,同时还对Spring 3.0的校验和格式化框架如果和Spring MVC整合进行讲解。  第16章:有别于一般书籍的单元测试内容,本书以当前最具实战的...

    Spring.3.x企业应用开发实战(完整版).part2

     Spring3.0引入了众多Java开发者翘首以盼的新功能和新特性,如OXM、校验及格式化框架、REST风格的Web编程模型等。这些新功能实用性强、易用性高,可大幅降低Java应用,特别是JavaWeb应用开发的难度,同时有效提升...

    Spring3.x企业应用开发实战(完整版) part1

     Spring3.0引入了众多Java开发者翘首以盼的新功能和新特性,如OXM、校验及格式化框架、REST风格的Web编程模型等。这些新功能实用性强、易用性高,可大幅降低Java应用,特别是JavaWeb应用开发的难度,同时有效提升...

    Spring攻略(第二版 中文高清版).part1

    1.1 实例化Spring IoC容器 1 1.1.1 问题 1 1.1.2 解决方案 1 1.1.3 工作原理 3 1.2 配置Spring IoC容器中的Bean 4 1.2.1 问题 4 1.2.2 解决方案 4 1.2.3 工作原理 4 1.3 调用构造程序创建Bean 14 ...

    Spring 3 Reference中文

    第2 章 Spring 3.0 的新特性和增强 21 2.1 Java 5.. 21 2.2 改进的文档. 21 2.3 新的文章和教程. 21 2.4 新的模块组织方式和构建系统.. 22 2.5 新特性概述. 22 2.5.1 为Java 5 更新...

    Spring攻略(第二版 中文高清版).part2

    1.1 实例化Spring IoC容器 1 1.1.1 问题 1 1.1.2 解决方案 1 1.1.3 工作原理 3 1.2 配置Spring IoC容器中的Bean 4 1.2.1 问题 4 1.2.2 解决方案 4 1.2.3 工作原理 4 1.3 调用构造程序创建Bean 14 ...

    spring-embedded-database-master-edited:添加了Spring配置

    简单笔记记录REST应用 ### 1。 使用的技术 Maven的3.0 春天4.1.6.RELEASE HSQLDB 2.3.2 ### 2。 在本地运行该项目$ git clone $ mvn软件包 ### 3。 将war文件导入运行中的Tomcat实例 ### 4。 您可以a)添加注释...

    spring3.1中文参考文档

    第2章 Spring 3.0的新特性和增强 ............................................................................................................ 22 2.1 Java 5 .................................................

    ambari-webpage-embedder-view:允许包装现有的WebUI页面并将其显示为Ambari视图

    作为插件实现,它使用来将网页内容作为视图内联。 安装后, Ambari Webpage Embedder View可用于嵌入多个网页。 只需为每个新网页创建一个新的视图实例。 您可以使用Ambari 向导或View REST API( )。 嵌入式网页...

Global site tag (gtag.js) - Google Analytics