【SSM 框架】SpringMVC+Spring+Mybatis 整合SpringMvc(基本整合)
阿新 • • 發佈:2020-12-19
6. 整合 SpringMVC
6.1.匯入 spring-mvc 包
6.2.配置 web.xml
1)啟動 spring,載入 applicationContext.xml
2)啟動 springMVC,載入 spring-mvc.xml
<!-- 啟動SpringMVC -->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet. DispatcherServlet</servlet-class>
<!-- 引數:讀取spring-mvc.xml -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet- name>DispatcherServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
<!-- 啟動spring -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 修改路徑 -- >
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
6.3.配置 spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:contenxt="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 掃描Controller所在的包 -->
<contenxt:component-scan base-package="cn.sm1234.controller"/>
<!-- 註解驅動 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 檢視解析器:簡化在Controller類編寫的檢視路徑 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 字首 -->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!-- 字尾 -->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
6.4.編寫 Controller
package cn.sm1234.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/customer")
public class CustomerController {
@RequestMapping("/test")
public String test(){
return "test";
}
}
6.5.編寫頁面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'test.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
測試SpringMVC是否可用
</body>
</html>