Spring MVC 学习笔记 一 创建项目

1:新建maven 工程
运行以下maven命令,建立一个jee5的web工程。

mvn archetype:generate -DinteractiveMode=false -DarchetypeGroupId=org.codehaus.mojo.archetypes -DarchetypeArtifactId=webapp-jee5 -Dversion=0.0.1-SNAPSHOT -DgroupId=net.zhepu -DartifactId=springmvc

2:修改pom.xml,增加spring mvc 3.0.5的依赖包及jetty plugin

 
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<org.springframework.version>3.0.5.RELEASE</org.springframework.version>

  
org.springframework
spring-webmvc
${org.springframework.version}

   
org.mortbay.jetty
jetty-maven-plugin
7.4.0.v20110414

10

/springmvc
src/main/resources/webdefault.xml


3:修改web.xml,增加如下配置

 
mvcServlet
org.springframework.web.servlet.DispatcherServlet

contextConfigLocation
classpath*:/spring/web/servlet-context.xml

1

 
mvcServlet
*.action

Spring-mvc缺省是在WEB-INF目录下找名称未${servlet-name}-context.xml的配置文件,这里通过contextconfiglocation的配置,将spring-mvc所需的配置文件指向到src\resources\spring\web目录下。

4:在src\resources\spring\web下,新建 servlet-context.xml,内容如下

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
<context:component-scan base-package="net.zhepu.web" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />


5:新增controller类

package net.zhepu.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/helloworld")
public class Helloworld {

 @RequestMapping(method=RequestMethod.GET)
public ModelAndView hello() {
ModelAndView mv = new ModelAndView();
mv.setViewName("helloworld");
return mv;
}
}

6:在/WEB-INF/jsp目录下,新建helloworld.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>

                    JSP Page                

Hello World!

   

7:运行mvn jetty:run 启动工程后,访问http://localhost:8080/springmvc/helloworld.action ,可以看到Hello World!,

springmvc01.rar (8.5 KB)