体验Spring3 MVC,替换Struts2

    体验Spring3 MVC,替换Struts2

    2013-01-26 10:32:20     我来说两句       
    收藏    我要投稿

    Java的WEB框架中,Struts2应该是最著名的,不过最近试了试Spring3 MVC,感觉好爽啊,几乎像ASP.Net MVC3一样舒服,以后就用它了。简单记录一下过程,没有技术含量。
    1、准备包
    下载的是spring framework 3.2.0,从中抽取以下jar到工程的WEB-INF/lib下:
    spring-beans-3.2.0.RELEASE.jar
    spring-context-3.2.0.RELEASE.jar
    spring-core-3.2.0.RELEASE.jar
    spring-expression-3.2.0.RELEASE.jar
    spring-web-3.2.0.RELEASE.jar
    spring-webmvc-3.2.0.RELEASE.jar
    另外还需要几个第三方jar包,记录日志和处理json:
    commons-logging-1.1.1.jar
    jackson-core-als-1.9.11.jar
    jackson-mapper-asl-1.9.11.jar
     
    2、WEB-INF/web.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns="http://java.sun.com/xml/ns/javaee"
             xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
             xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                                 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
             id="WebApp_ID" version="2.5">
     
        <!--站点名-->
        <display-name>mvc</display-name>
       
        <!--指定spring配置文件-->
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-servlet.xml</param-value>
        </context-param>
      
        <listener>      
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>      
        </listener>  
       
        <servlet>
            <!--servlet名字,随意-->
            <servlet-name>spring</servlet-name>      
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>      
            <load-on-startup>1</load-on-startup>      
        </servlet>      
     
        <servlet-mapping>
            <!--servlet名字-->
            <servlet-name>spring</servlet-name>    
            <!--拦截所有请求,对静态文件会有问题,在spring-servlet.xml中解决-->
            <url-pattern>/</url-pattern>      
        </servlet-mapping>  
       
        <welcome-file-list>
            <welcome-file>index.htm</welcome-file>
            <welcome-file>index.jsp</welcome-file>
        </welcome-file-list>
    </web-app>
     
    3、WEB-INF/spring-servlet.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:context="http://www.springframework.org/schema/context"
     xmlns:p="http://www.springframework.org/schema/p"
     xmlns:mvc="http://www.springframework.org/schema/mvc"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     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.xsd
          http://www.springframework.org/schema/mvc
          http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
           
         <!-- 启动注解驱动的Spring MVC功能,注册请求url和注解POJO类方法的映射-->
         <mvc:annotation-driven />
     
         <!-- 启动包扫描功能,以便注册带有@Controller、@Service、@repository、@Component等注解的类成为spring的bean -->
         <context:component-scan base-package="com.test.mvc.web" />
     
         <!-- 对模型视图名称的解析,在WEB-INF/jsp目录下找对应的jsp文件 -->
         <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
          
        <!--放过/scripts下的静态文件-->
        <mvc:resources mapping="/scripts/**" location="/scripts/" />
    </beans>
     
    4、WEB-INF/applicationContext.xml
    spring的配置文件,由于我们不使用它的其它功能,暂时放个空的就好了。
    <?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:util="http://www.springframework.org/schema/util"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                http://www.springframework.org/schema/util
                http://www.springframework.org/schema/util/spring-util-3.0.xsd">
    </beans>
     
    5、写Controller
    package com.test.mvc.web;
     
    import org.springframework.stereotype.*;
    import org.springframework.web.bind.annotation.*;
    import org.springframework.web.servlet.*;
     
    /**
     * 控制器,用Controller注解
     */
    @Controller
    public class HomeController {
     
        /**
         * 映射到/welcome
         */
        @RequestMapping(value = "/welcome")
        public ModelAndView welcome(){
             
             ModelAndView mv = new ModelAndView("welcome");     //使用welcome.jsp,如果不写,根据url默认也是welcome.jsp
             mv.addObject("hello", "Hello");    //model中增加一个名为hello的字符串
              
             Client client = new Client();
             client.setName("User");
             mv.addObject("client", client);    //再增加一个名为client的自定义对象
     
             return mv;
        }
         
        /**
         * 如果不需要Model,直接返String更简单,对应的view为login_page.jsp
         */
        @RequestMapping(value = "/login")
        public String login(){
            return "login_page";
        }
         
        /**
         * 一个返回json的方法,用ResponseBody标识
         * 可以在url中定义参数中,实现RESTful真是太简单了
         * 传参很灵活,可以从url中取,也可以定义普通的
         */
        @RequestMapping(value="/client/{name}", method = RequestMethod.GET)
        @ResponseBody
        public Client getClient(@PathVariable String name, String title){
            Client client = new Client();
            client.setName(title+ " " + name);
             
            return client;
        }
    }
    里面用到了Client,很简单的POJO:
    package com.test.mvc.web;
     
    /**
     * 自定义一个POJO
     */
    public class Client {
        private String name;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    }
     
    6、写视图
    根据spring-servlet.xml中的配置,视图要放到WEB-INF/jsp下,新建welcome.jsp:
    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Spring MVC</title>
    <script src="scripts/jquery-1.4.2.js"></script>
    <script>
    $(function(){
        $("#btnGet").click(function(){
            $.ajax({
                type: 'GET',
                url : 'client/Tian',   //通过url传递name参数
                dataType : 'json',
                data: {title: "Mr"},   //通过data传递title参数
                success : function(data) {
                    alert(data.name);   
                },
                error : function(data) {   
                    alert(data.responseText);
                }   
            });  
        });
    });
    </script>
    </head>
    <body>
    <!-- 显示model中的hello字符串和client对象的name -->
    ${hello}
    ${client.name}
    <br/>
    <input id="btnGet" type="button" value="get client" />
    </body>
    </html>
     
    一切就绪,把Tomcat跑起来吧,用浏览器访问 localhost:8080/mvc/welcome 就能看到页面了。

posted @ 2013-07-15 15:05  IT小绵羊VS程序猿  阅读(657)  评论(6)    收藏  举报