Spring3 REST MVC框架,提速你的Web开发

20 四月, 2010 (15:28) | J2EE框架, spring3 繁体 English    DeliciOus    分享到新浪微博
作者: H.E. | 您可以转载, 但必须以超链接形式标明文章原始出处和作者信息及版权声明
网址: http://www.javabloger.com/article/spring3-rest-mvc-example.html
豆瓣读书 向你推荐有关 J2EE框架spring3、 类别的图书。

最近在Java web 项目中需要采用非常简单的REST框架,Struts2、webwork、JSF 经过一番比较,最后选择了Spring3,理由只有一个 “简单好用,并满足需要”。很久以前就Rod Johnson大叔说 Spring3 全面支持REST风格的Web服务,"We're really seeing extensive interest and growth in REST, and it will have comprehensive support for RESTful Web services," said Johnson,今天亲自尝试了一下,真有点相识恨晚的感觉,如果在这次项目运用没有太大的问题,将来在其他项目会大量运用。

工作原理如图所示:
http://1aqpcg.bay.livefilestore.com/y1p_Q90l9w2JCMiEtgzkdikNQZoyy7Ic7GiCrm8Uk2GUhHZ1C80d7j2Ty4X0IWuydFepV3htprYHjptpEtq561o-7Ok_rkBgoZa/spring_rest_fm.png
*根据HTTP请求的URL,调用相应的DispatcherServlet控制器。
*提供一个视图是作为HTTP响应发送。

页面上最终运行效果,如图所示:

http://1aqpcg.bay.livefilestore.com/y1pu1qm8gBjr1VJ_9hg2BvILVMcD3tnvyc1WTPRVpkVTHqbP00tQTml9vMDJU_xnyfNrGls2OPS7Df-Z96_zPSMFbqsWXxxUr2t/topic_view.png
主要代码:

清单1:TopicController

package com.javabloger.springrest.action;

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("/topic")  //url映射的名称
public class TopicController {

    @RequestMapping(value = "/{id}",method=RequestMethod.GET)
    public String helloWorld(
            @PathVariable Long id,
            HttpServletRequest request,
            HttpServletResponse response) {
            request.setAttribute("message", "You Input Topci Id is: <b>"+id+"</b>");
        return  "topic" ;   // 对应 /WEB-INF/jsp 目录下的 topic.jsp 文件
    }
       
    @RequestMapping(value="/add")
    public String test(HttpServletRequest request,  
            HttpServletResponse response){
        System.out.println("Hello www.JavaBloger.com ");
        request.setAttribute("message", "Hello JavaBloger ! ,@RequestMapping(value='/add')");
        return "topic";  // 对应 /WEB-INF/jsp 目录下的 topic.jsp 文件
       
    }
}

清单2 :UserController
package com.javabloger.springrest.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.javabloger.springrest.pojo.Users;

@Controller
@RequestMapping("/user")

public class UserController {
     @RequestMapping(value="/login")
    public String test(HttpServletRequest request,  
            HttpServletResponse response,Users  userinfo){   // 非常方便可以直接在方法里面放入对象
         if (userinfo.getUsername().equals("username") &&
                 userinfo.getPassword().equals("password")
             )
         {
             request.setAttribute("user", userinfo);
             return "users/list";   //判断,将跳转不同的页面
         }
         else{
             return "users/loginerr";  //判断,将跳转不同的页面
         }
    }
}

清单3:web.xml
   <servlet>  
      <servlet-name>springmvc</servlet-name>  
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
      <load-on-startup>2</load-on-startup>  
   </servlet>  
 <servlet-mapping>  
     <servlet-name>springmvc</servlet-name>  
     <url-pattern>/</url-pattern>  
 </servlet-mapping>  

清单4:springmvc-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:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    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/tx 
            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 
            http://www.springframework.org/schema/jdbc 
            http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd">
    <bean
        class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
    <!– 自动搜索@Controller标注的类 –>
    <context:component-scan base-package="com.javabloger.springrest.action" />
    <bean
        class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
    <!– Default ViewResolver –>
    <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/" />
        <property name="suffix" value=".jsp"></property>
    </bean>
    <bean id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource"
        p:basename="i18n/messages" />
</beans>

 

<<完整的Spring3 REST代码例子下载>>


一些废话:
我个人非常非常喜欢没有xml配置框架,因为项目一大不仅需要对代码进行维护对xml文件还需要维护相当繁琐,在这个项目中除了采用Spring3的REST特性,还采用了Apache的dbutils对数据进行操作,传说中的SSH轻量级框架是针对EJB和J2EE而言的轻量级,对于上述这样的框架SSH还能称得上“轻量级”吗?也许SSH目前成为了标准,但不再是“轻量级J2EE框架”的代名词!

另外,还有一份专门介绍 Spring3 MVC的资料《Spring 3 MVC CodeMash 2009》,请看幻灯片:

豆瓣读书  向你推荐有关 J2EE框架 spring3、 类别的图书。



Creative Commons License
本文由J2ee企业顾问-黄毅创作,并已采用创作共用署名2.5中国大陆版许可证授权。

评论

Comment from fyunli
Time 2010年04月20日 at 4:31 下午

Struts2也可以用Annotation,萝卜青菜而已

Comment from H.E.
Time 2010年04月20日 at 5:09 下午

首先非常感谢您的关注,我是一个非常不喜欢xml的人,而且感观上spring3比Struts2简单些, 就像你说的 “萝卜青菜,各有所爱”。

BTW:你的站点上我也会经常关注的,刚刚找到了一个有用的东西,呵呵

Comment from icantellu
Time 2010年05月24日 at 11:58 上午

这两个配置重复了 还有 如果配置了 那么以上两个配置 可以不要了吧

Comment from icantellu
Time 2010年05月24日 at 12:08 下午

贴的 xml 怎么无法回复 奇怪
我说的两个配置 是指 DefaultAnnotationHandlerMapping 和 AnnotationMethodHandlerAdapter
如果配置了context:component-scan 那么这两个是可以省略的

Comment from 菜鸟
Time 2010年05月25日 at 6:45 下午

servlet的url模式必须是”/”吗?改成“/*”就不行了

Comment from fish4j
Time 2010年07月12日 at 10:26 下午

Controller之间怎样相互跳转呢?只能跳转到视图吗?

Comment from H.E.
Time 2010年09月29日 at 1:59 下午

to:fish4j

return “/article/list”; 这样只能到页面,

return “redirect:/article/login”; 这样可以掉转到 action

Comment from cc
Time 2011年06月15日 at 4:37 下午

如果请求参数一大堆,请求处理方法的参数难道也一大堆吗?
或者请求参数是 类名.属性,怎么办。

Comment from 啊啊
Time 2011年06月21日 at 5:53 下午

没有配置文件描绘请求的url和跳转的结果,这样太灵活,不能透过一个文件来统一管理一个模块的请求。如果项目的开发人员素质不高,没人监管,根本不知道一个模块到底有多少url请求。
我觉得太灵活,反而不是好事情

Comment from 王涛
Time 2011年07月29日 at 2:47 下午

spring 的rest还是蛮让人欣喜的,但是,仅仅是会用,没有深入理解其中的实现机制还是不够的,这种风格,不仅仅是在软件开发上,在软件架构上也是很不错的

评论

评论也是有版权的!




3156