1.新建web project
2.右键项目,给项目添加spring框架如图,不需要勾选任何一个选项。
3.在WebRoot/WEB-INF目录下添加web.xml内容如下:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <!--configure the setting of springmvcDispatcherServlet and configure the mapping--> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-servlet.xml</param-value> </init-param> <!-- <load-on-startup>1</load-on-startup> --> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
servlet模块添加了springmvc的调度器,如果需要改springmvc的配置文件的名字,可以更改springmvc-servlet.xml这个名字为指定名字。
servlet-mapping连接了这个servlet,并能够定义url-pattern,一般使用/而不是/*。
4.在src目录下添加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:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <!-- scan the package and the sub package --> <context:component-scan base-package="com.controller"/> <!-- don't handle the static resource --> <mvc:default-servlet-handler /> <!-- if you use annotation you must configure following setting --> <mvc:annotation-driven /> <!-- configure the InternalResourceViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"> <!-- 前缀 --> <property name="prefix" value="/WEB-INF/jsp/" /> <!-- 后缀 --> <property name="suffix" value=".jsp" /> </bean> </beans>
base-package指定你的controller所在的包,prefix和suffix分别指定了view所在的位置和后缀,这个配置文件连接了controller和view。
5.新建controller,所在包应为springmvc-servlet.xml中指定的base-package
结构如下:
内容如下:
package com.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/Hello") public class HelloController { @RequestMapping("/hello") public String hello(){ return "hello"; } }
6.新建view,所在位置应为springmvc-servlet.xml中的prefix,后缀为指定后缀,名称与controller中返回的字符串相同。
内容自拟。
至此,一个springmvc的hello world项目配置完毕。