spring mvc(一)开发环境搭建和HelloWorld程序

Spring MVC 3提供了基于注解、REST风格等特性,有些方面比Struts 2方便一些。

这里进行Spring MVC 3的开发环境搭建,即开发Hello World程序。

1,拷贝Spring MVC 3类库到WEB-INF/lib下,经测试至少需要如下几个,版本为Spring 3.1.1:

org.springframework.asm-3.1.1.RELEASE.jar
org.springframework.beans-3.1.1.RELEASE.jar
org.springframework.context-3.1.1.RELEASE.jar
org.springframework.core-3.1.1.RELEASE.jar
org.springframework.expression-3.1.1.RELEASE.jar
org.springframework.web-3.1.1.RELEASE.jar
org.springframework.web.servlet-3.1.1.RELEASE.jar
commons-logging.jar

最后一个,Spring库中未带,但需要加入。此外,如果后面用到JSR303验证,还需要hibernate的的validation实现包(使用hibernate-validator 4.3):
hibernate-validator-4.3.0.Final.jar
hibernate-validator-annotation-processor-4.3.0.Final.jar
validation-api-1.0.0.GA.jar
jboss-logging-3.1.0.CR2.jar

2,首先创建Web工程,修改web.xml,加入
  <servlet>
      <servlet-name>spring</servlet-name>
       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
       >
  </servlet>
  <servlet-mapping>
      <servlet-name >spring</servlet-name>
      <url-pattern>/</url-pattern>
  </servlet-mapping>

然后创建<servlet-name>-servlet.xml文件,这里对应的就是spring-servlet.xml,放在web.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来处理,因此映射到"/"上面(包括静态页面),
>不加经测试也未见出错,而且如果要修改spring-servlet.xml的配置位置或名字,
可以加       
<init-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>/WEB-INF/spring-servlet.xml</param-value>
</init-param>
但一定要放到>前面,否则xml校验出错(经测试)。

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

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

package controller;
// import 略
@Controller
public class HelloController{
     )
     public String hello(){
         return "hello";
     }
}

然后在/WEB-INF/jsp/下创建hello.jsp即可用如下地址访问:

http://localhost:8080/<context-path>/hello
原文地址:https://www.cnblogs.com/shenming/p/3807734.html