基础还是创建一个Dynamic web project.
WEB-INF/lib中添加必需的jar。
- commons-logging-1.1.3.jar
- spring-aop-4.3.6.RELEASE.jar
- spring-beans-4.3.6.RELEASE.jar
- spring-context-4.3.6.RELEASE.jar
- spring-core-4.3.6.RELEASE.jar
- spring-expression-4.3.6.RELEASE.jar
- spring-web-4.3.6.RELEASE.jar
- spring-webmvc-4.3.6.RELEASE.jar
这些jar在spring中都有。
配置web.xml
<servlet> <servlet-name>springDispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置Spring mvc下的配置文件的位置和名称 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
src下创建springmvc.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.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 配置自动扫描的包 --> <context:component-scan base-package="com.awu.springmvc"> </context:component-scan> <!-- 配置视图解析器 如何把handler 方法返回值解析为实际的物理视图 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name = "prefix" value="/WEB-INF/views/"></property> <property name = "suffix" value = ".jsp"></property> </bean> </beans>
Tip:<context:component-scan base-package="com.awu.springmvc"> 中为相应controllers的package目录。
bean中配置的为views的解析目录。
示例代码:
package com.awu.springmvc.handlers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class Helloworld { @RequestMapping("/helloworld") public String hello(){ System.out.println("hello world"); return "success"; } }
返回字符串为“success”,那么在配置文件指定的目录下(views)创建同名jsp文件:success.jsp。