本筆記做于 尚硅谷佟剛老師的springmvc4.x視頻
步驟:
1. 導(dǎo)入Jar包
Paste_Image.png
2. 在web.xml中配置DispatcherServlet
3. 加入springmvc的配置文件
4. 編寫處理請求的servlet并標(biāo)識為指定處理器
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">
<!-- 配置轉(zhuǎn)發(fā)器 -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!--設(shè)置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
成功了