构建项目
引入jar包
- spring-aop-4.2.0.RELEASE.jar
- spring-beans-4.2.0.RELEASE.jar
- spring-context-4.2.0.RELEASE.jar
- spring-core-4.2.0.RELEASE.jar
- spring-expression-4.2.0.RELEASE.jar
- spring-web-4.2.0.RELEASE.jar
- spring-webmvc-4.2.0.RELEASE.jar
- commons-logging-1.2.jar
创建web.xml
代码语言:javascript复制<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<!-- Spring跳转Servlet配置 -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<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>
</web-app>
创建springmvc.xml
springmvc.xml应与上方classpath:springmvc.xml匹配
代码语言:javascript复制<?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-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
<!-- 配置自动扫描的包 -->
<context:component-scan base-package="com.sanchan.server.controller"></context:component-scan>
<!-- 配置视图解析处理器:将Controller方法返回解析为实际的物理视图 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
#创建Controller 在src下创建com.sanchan.server.controller.HelloWorld
代码语言:javascript复制package com.sanchan.server.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
//表示该类为Spring的处理器,监听相关操作
@Controller
public class HelloWorld {
/**
* 1、用@RequestMapping来映射请求的URL
* 2、返回值会通过视图解析器解析为实际的物理视图,对于org.springframework.web.servlet.view.
* InternalResourceViewResolver视图解析器,会做如下解析:
* prefix【在springmvc.xml中配置的prefix值】 下面return返回的值 suffix【在springmvc.xml中配置的suffix值】
* @return
*/
@RequestMapping("/helloworld")
public String hello() {
System.out.print("hello world");
return "success";
}
}
在WEB-INF下创建/views/success.jsp
这样就完成了一个简单的spring mvc