本笔记做于 尚硅谷佟刚老师的springmvc4.x视频
步骤:
1. 导入Jar包
2. 在web.xml中配置DispatcherServlet
3. 加入springmvc的配置文件
4. 编写处理请求的servlet并标识为指定处理器
5. 编写视图文件
案例:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<!-- 配置转发器 -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!--设置srpingmvc.xml文件路径 -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
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:aop="http://www.springframework.org/schema/aop"
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/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
<!-- 开启注解扫描 -->
<context:component-scan base-package="com.xxjqr.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>
<!-- 比如处理器传回来"success",那么拼接后路径为:
/WEB-INF/views/success.jsp -->
</beans>
类
//实例化该控制器
@Controller
@RequestMapping("/springmvc")
public class HelloWorld {
/* 请求映射:
* 如果类上有@RequestMapping,那么请求路径是:项目/a+b
* 如果类上没有@RequestMapping,那么请求路径是:项目/b
* */
@RequestMapping("/helloworld")
public String hello(){
System.out.println("到了处理器了");
return "success";
}
}
视图
//index.jsp
<a href="helloworld">HelloWord</a><!--提交路径不要以/开头-->
//WEB-INF/views.success.jsp
成功了