`

Spring MVC 3学习笔记+教程(一)开发环境搭建和HelloWorld程序

 
阅读更多

Spring MVC 3提供了基于注解、REST风格等特性,有些方面比Struts 2方便一些。
这里进行Spring MVC 3的开发环境搭建,即开发Hello World程序。
1. 首先创建Web工程(请参照E:\积累\通用代码\eclipse\Eclipse怎么创建Web工程.doc),在web.xml加入如下内容:

<servlet>
  <servlet-name>spring</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>                                  
   <param-name>contextConfigLocation</param-name>
   <param-value>/WEB-INF/springConfigure/spring-servlet.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>spring</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>

然后创建<servlet-name>-servlet.xml文件,这里对应的就是spring-servlet.xml,路径如下:

WebContent\WEB-INF\springConfigure\spring-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:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
            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">
 
  <mvc:annotation-driven/>
  <context:component-scan base-package="controller"/>  
  <bean 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>
     <property name="suffix" value=".jsp"></property>
   </bean>    
</beans>
1)所有请求都要由DispatcherServlet来处理,因此映射到"/"上面(包括静态页面);

2)在spring-servlet.xml中,引入了mvc和context两个命名空间,其中<mvc:annotation-driven/>表示这里使用注解进行开发,<context:component-scan>指明注解所在的包名,InternalResourceViewResolver这个类的配置,说明逻辑视图转换成物理视图的前缀和后缀,其viewClass的属性如果是jsp的话经测试,不设置也可。

2 需加入工程必需的Jar包,由于eclipse4. 2 不能给web 工程加Jar包,所以需要手动将它们copy到lib路径下,需加入的包如下:

 

 

 3 在controller包下创建HelloController.java,代码如下:

package controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller

public class HelloController {
 @RequestMapping("/hello")
    public String hello(){
        return "hello";
    }

}
然后在/WEB-INF/jsp/下创建hello.jsp即可用如下地址访问:
http://localhost:8080/<context-path>/hello

 

  • 大小: 300.6 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics