IDEA下
step1:创建一个web项目
step2:添加springmvc基本jar包 如下:
commons-logging-1.2.jar
spring-aop-4.3.18.RELEASE.jar
spring-beans-4.3.18.RELEASE.jar
spring-context-4.3.18.RELEASE.jar
spring-core-4.3.18.RELEASE.jar
spring-expression-4.3.18.RELEASE.jar
spring-web-4.3.18.RELEASE.jar
spring-webmvc-4.3.18.RELEASE.jar
step3:在web.xml里面配置dispatcherservlet
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--配置dispatcherservlet-->
<servlet>
<servlet-name>app</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--配置DispatcherServlet初始化参数:配置spring mvc配置文件的位置和名称-->
<!--配置视图解析器:如何把handler 方法返回值解析为实际的物理视图-->
<!--不配置采用默认的
默认配置为 /WEB-INF/<servlet-name>-servlet.xml
-->
<!--<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:app-servlet.xml</param-value>
</init-param>-->
<!--这个servlet是在web应用被加载的时候创建,而不是在发送请求的时候创建 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>app</servlet-name>
<!--回应所有的请求-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
step4:src下写HelloWorld类
package com.xiaosuanmiao.spring.mvc.handlers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloWorld {
/**
* 1.使用 @RequestMapping 注解来映射请求URL请求
* 2.返回值会通过试图解析器解析为实际的物理视图,对于InternalResourceViewResolver视图解析器 会做如下解析:
* 3.通过 + prefix + returnVal + 后缀这样的方式得到实际的物理视图 然后做转发操作
* @return
*
* 返回目标页面为 /WEB-INF/views/success.jsp
*/
@RequestMapping("/helloworld")
public String hello(){
System.out.println("Hello,World");
return "success";
}
}
step5:在web,xml里面配置的路径下写spring.mvc的配置文件
<?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-4.3.xsd
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.3.xsd">
<!--配置自动扫描的包-->
<context:component-scan base-package="com.xiaosuanmiao.spring.mvc.handlers"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
step6:springmvc配置文件里指定了结果返回的物理视图
step7:添加服务器 运行