接口:
接口实现类:
spring config xml文件:
调用文件类:
工厂静态方法实例:
工厂实例方法实例化:
工厂类:
文件:
测试类:
set方式注入:
p空间注入:
有参构造方法的方式进行依赖注入:
package Dao;
public class User {
private String name;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
'}';
}
}
package Impl;
import Dao.User;
import Dao.UserDao;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public class UserDaoImpl implements UserDao {
private int age;
private String name;
private List<String> list;
private Map<String, User> map;
private Properties properties;
public void setProperties(Properties properties) {
this.properties = properties;
}
public void setList(List<String> list) {
this.list = list;
}
public void setMap(Map<String, User> map) {
this.map = map;
}
public void setAge(int age) {
this.age = age;
}
public void setName(String name) {
this.name = name;
}
@Override
public void save() {
System.out.println(list);
System.out.println(map);
System.out.println(properties);
System.out.println("save running...");
}
}
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userDao" class="Impl.UserDaoImpl">
<property name="list">
<list>
<value>aaaa</value>
<value>bbbb</value>
<value>cccc</value>
</list>
</property>
<property name="map" >
<map>
<entry key="user1" value-ref="user1"></entry>
</map>
</property>
<property name="properties">
<props>
<prop key="a1">qqqqq</prop>
<prop key="a2">wwwww</prop>
</props>
</property>
</bean>
<bean id="user1" class="Dao.User">
<property name="name" value="玖" />
<property name="address" value="上海" />
</bean>
</beans>
如果配置文件中有多个相同类型的对象时,使用第一个,反之用第二种
例如:
getBean 方法,通过id ,获取文件中标签的内容,返回标签中class类型的数据
package Demo;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.jupiter.api.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.sql.DataSource;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
import java.util.ResourceBundle;
public class DataSourceTest {
@Test
public void test1() throws Exception { //测试手动创建c3p0连接池
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource(); //创建连接池
Properties properties = new Properties(); //创建文件类对象
String path = DataSourceTest.class.getClassLoader().getResource("druid.properties").getPath(); //获取文件对象
properties.load(new FileReader(path)); //加载文件
//加载mysql数据库
comboPooledDataSource.setDriverClass(properties.getProperty("driver"));
comboPooledDataSource.setJdbcUrl(properties.getProperty("url"));
comboPooledDataSource.setUser(properties.getProperty("user"));
comboPooledDataSource.setPassword(properties.getProperty("password"));
Connection connection = comboPooledDataSource.getConnection(); //连接mysql数据库
String sql = "select * from student"; //编写sql语句
PreparedStatement preparedStatement = connection.prepareStatement(sql); //创建sql对象
ResultSet resultSet = preparedStatement.executeQuery(); //将获取到的值存储在resultset集合中
while (resultSet.next()) { //遍历打印
System.out.println("编号:" + resultSet.getString("id") + " 姓名:" + resultSet.getString("name") + " 年龄:" + resultSet.getString("age") + " 员工号:" + resultSet.getString("region_id"));
}
connection.close();
preparedStatement.close();
}
@Test
public void test2() throws Exception { //测试手动创建druid连接池
DruidDataSource comboPooledDataSource = new DruidDataSource();
ResourceBundle druid = ResourceBundle.getBundle("druid"); //读取配置文件
//连接数据库信息
comboPooledDataSource.setDriverClassName(druid.getString("driver"));
comboPooledDataSource.setUrl(druid.getString("url"));
comboPooledDataSource.setUsername(druid.getString("user"));
comboPooledDataSource.setPassword(druid.getString("password"));
DruidPooledConnection connection = comboPooledDataSource.getConnection(); //获取连接对象
System.out.println(connection);
connection.close();
}
@Test
public void test3() throws Exception { //测试Spring容器产生数据源对象
ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
DataSource bean = classPathXmlApplicationContext.getBean(DataSource.class);
Connection connection = bean.getConnection();
String sql = "select * from student"; //编写sql语句
PreparedStatement preparedStatement = connection.prepareStatement(sql); //创建sql对象
ResultSet resultSet = preparedStatement.executeQuery(); //将获取到的值存储在resultset集合中
while (resultSet.next()) { //遍历打印
System.out.println("编号:" + resultSet.getString("id") + " 姓名:" + resultSet.getString("name") + " 年龄:" + resultSet.getString("age") + " 员工号:" + resultSet.getString("region_id"));
}
connection.close();
preparedStatement.close();
}
}
properties文件:
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/gb1 user=root password=123456
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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation=
"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.xsd
">
<!-- 加载外部的properties文件-->
<context:property-placeholder location="classpath:druid.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${driver}"/>
<property name="jdbcUrl" value="${url}"/>
<property name="user" value="${user}"/>
<property name="password" value="${password}"/>
</bean>
</beans>
测试类:
@Test
public void test3() throws Exception { //测试Spring容器产生数据源对象
ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
DataSource bean = classPathXmlApplicationContext.getBean(DataSource.class);
Connection connection = bean.getConnection();
String sql = "select * from student"; //编写sql语句
PreparedStatement preparedStatement = connection.prepareStatement(sql); //创建sql对象
ResultSet resultSet = preparedStatement.executeQuery(); //将获取到的值存储在resultset集合中
while (resultSet.next()) { //遍历打印
System.out.println("编号:" + resultSet.getString("id") + " 姓名:" + resultSet.getString("name") + " 年龄:" + resultSet.getString("age") + " 员工号:" + resultSet.getString("region_id"));
}
connection.close();
preparedStatement.close();
}
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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation=
"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.xsd
">
<!-- 加载外部的properties文件到spring容器中-->
<context:property-placeholder location="classpath:druid.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${driver}"/>
<property name="jdbcUrl" value="${url}"/>
<property name="user" value="${user}"/>
<property name="password" value="${password}"/>
</bean>
<context:component-scan base-package="Impl" />
<!-- 遍历这个目录下的所有注释-->
</beans>
注解的简单使用类:
userDao类:
package Impl;
import Dao.UserDao;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
//<bean name="userDao" class="Impl.UserDaoImpl"/>
//@Component("userDao")
@Repository("userDao")
public class UserDaoImpl implements UserDao {
@Value("${driver}") //寻找spring容器中的key为driver对应的值,将值注入给driver变量
private String driver;
@Override
public void save() {
System.out.println("save running...");
System.out.println(driver);
}
}
service类:
package Impl;
import Dao.UserDao;
import Service.UserService;
import org.junit.jupiter.api.parallel.ResourceLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
//<bean id="userService" class="Impl.UserServiceImpl">
//@Component("userService")
@Service("userService")
public class UserServiceImpl implements UserService{
// <property name="userDao" ref="userDao" />
@Autowired //从spring容器中寻找userDao类型的数据,找到后进行注入
@Qualifier("userDao") //从spring容器中寻找userDa的id的bean数据
private UserDao userDao;
// public void setUserDao(UserDao userDao) {
// this.userDao = userDao;
// }
@Override
public void save() {
userDao.save();
}
}
配置类:
核心配置类:
package config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
@Configuration //标志该类是Spring的核心配置类
//<context:component-scan base-package="Impl" />
//<!-- 遍历这个目录下的所有注释-->
@ComponentScan("Impl")
//<!-- 加载外部的properties文件到spring容器中-->
//<context:property-placeholder location="classpath:druid.properties"/>
@PropertySource("classpath:druid.properties")
@Import({DataSourceConfiguration.class}) //导入类
public class SpringCofiguration {
}
配置类:
package config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
public class DataSourceConfiguration {
//导入文件数据
@Value("${driver}")
private String driver;
@Value("${url}")
private String url;
@Value("${user}")
private String user;
@Value("${password}")
private String password;
@Bean("dataSource") //Spring会将当前方法的返回值以指定名称存储到Spring容器中
public DataSource getDataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(user);
dataSource.setPassword(password);
return dataSource;
}
}
测试类:
package Demo;
import Service.UserService;
import config.SpringCofiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class UserController {
public static void main(String[] args) {
// ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); //获取文件
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringCofiguration.class); //加载配置类
UserService userService = applicationContext.getBean(UserService.class);
userService.save();
}
}
package Demo;
import Service.UserService;
import config.SpringCofiguration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.sql.DataSource;
import java.sql.SQLException;
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration("classpath:applicationContext.xml")
@ContextConfiguration(classes = {SpringCofiguration.class})
public class SpringJunitTest {
@Autowired
private UserService userService;
@Autowired
private DataSource dataSource;
@Test
public void test1() throws SQLException {
userService.save();
System.out.println(dataSource.getConnection());
}
}
package config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
@Configuration //标志该类是Spring的核心配置类
//<context:component-scan base-package="Impl" />
//<!-- 遍历这个目录下的所有注释-->
@ComponentScan("Impl")
//<!-- 加载外部的properties文件到spring容器中-->
//<context:property-placeholder location="classpath:druid.properties"/>
@PropertySource("classpath:druid.properties")
@Import({DataSourceConfiguration.class}) //导入类
public class SpringCofiguration {
}
自定义ContextLoaderListener
web.xml文件:
注意:全局参数中文件名称报红,是正常现象,其实程序已经正常检测到文件
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>applicationContext.xml</param-value>
</context-param>
<!-- 配置监听器-->
<listener>
<listener-class>listener.ContextLoadLister</listener-class>
</listener>
<servlet>
<servlet-name>UserServlet</servlet-name>
<servlet-class>web.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>/userservlet</url-pattern>
</servlet-mapping>
</web-app>
工具类:
作用:当传递一个ServletContext 文本域对象时,返回app键对应的值
package listener;
import org.springframework.context.ApplicationContext;
import javax.servlet.ServletContext;
public class WebApplicationContextUtils {
public static ApplicationContext getWebApplicationContext(ServletContext servletContext){
return (ApplicationContext) servletContext.getAttribute("app");
}
}
监听类:
作用:当创建服务器时,自动创建文本域对象以及文本域对象值
package listener;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ContextLoadLister implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
ServletContext servletContext = servletContextEvent.getServletContext();
//读取web.xml中contextConfigLocation对应的全局参数
String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");
ApplicationContext app = new ClassPathXmlApplicationContext(contextConfigLocation); //通过参数获取xml文件中的内容
servletContext.setAttribute("app",app);
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
}
appLicationContext.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation=
"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.xsd
">
<!-- 加载外部的properties文件到spring容器中-->
<context:property-placeholder location="classpath:druid.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${driver}"/>
<property name="jdbcUrl" value="${url}"/>
<property name="user" value="${user}"/>
<property name="password" value="${password}"/>
</bean>
<context:component-scan base-package="Impl" />
<!-- 遍历这个目录下的所有注释-->
</beans>
服务器端:
package web;
import Service.UserService;
import config.SpringCofiguration;
import listener.WebApplicationContextUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); //获取文件
ServletContext servletContext = this.getServletContext(); //获取文本域对象
// ApplicationContext app = (ApplicationContext) servletContext.getAttribute("app"); //获取文本域中的app键对应的值
ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext); //传递文本域对象,调用WebApplicationContextUtils工具类的方法
UserService userService = app.getBean(UserService.class);
userService.save();
}
}
使用spring自带的工具类和监听类
pom.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>maven_spring_web</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
web.xml配置
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 配置监听器-->
<listener>
<listener-class>org.springframework.test.context.ContextConfiguration</listener-class>
</listener>
<servlet>
<servlet-name>UserServlet</servlet-name>
<servlet-class>web.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>/userservlet</url-pattern>
</servlet-mapping>
</web-app>
测试类:
package web;
import Service.UserService;
import config.SpringCofiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); //获取文件
ServletContext servletContext = this.getServletContext(); //获取文本域对象
// ApplicationContext app = (ApplicationContext) servletContext.getAttribute("app"); //获取文本域中的app键对应的值
//ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext); //传递文本域对象,调用WebApplicationContextUtils工具类的方法
WebApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext); //使用spring中自带的工具类和监听类
UserService userService = app.getBean(UserService.class);
userService.save();
}
}
第一步:
pom.xml文件配置:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>mave_spring_web_2</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
第二步:
web.xml文件配置:
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!-- 配置SpringMVC的前端控制器-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
第三步:
创建类:
package ttt;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class UserController {
@RequestMapping("/quick")
public String save(){
System.out.println("Controller save running...");
return "success.jsp";
}
}
success.jsp页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>success!</h1>
</body>
</html>
第五步:
spring_mvc.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
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.xsd
">
<!-- Controller的组件扫描-->
<context:component-scan base-package="ttt" />
</beans>
效果图:
当访问类时,自动跳转到jsp页面
<?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"
xsi:schemaLocation="
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.xsd
">
<!-- Controller的组件扫描-->
<context:component-scan base-package="ttt" />
<!-- 配置内部资源视图解析器-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- /jsp/success.jsp-->
<property name="prefix" value="/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
页面跳转的几种方式:
package ttt;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
@Controller
public class UserController {
@RequestMapping(value = "/quick2")
public ModelAndView save2(){
ModelAndView modelAndView = new ModelAndView();
//设置模型数据
modelAndView.addObject("username","白金");
//设置视图名称
modelAndView.setViewName("success");
return modelAndView;
}
@RequestMapping(value = "/quick3")
public ModelAndView save3(ModelAndView modelAndView){
//设置模型数据
modelAndView.addObject("username","银灰");
//设置视图名称
modelAndView.setViewName("success");
return modelAndView;
}
@RequestMapping(value = "/quick4")
public String save4(Model model){
model.addAttribute("username","内卫");
return "success";
}
@RequestMapping(value = "/quick5")
public String save5(HttpServletRequest request){
request.setAttribute("username","花官");
return "success";
}
@RequestMapping("/quick")
public String save(){
System.out.println("Controller save running...");
return "success";
}
}
pom.xml文件配置:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>mave_spring_web_2</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>
</project>
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"
xsi:schemaLocation="
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.xsd
">
<!-- Controller的组件扫描-->
<context:component-scan base-package="ttt" />
<!-- 配置内部资源视图解析器-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- /jsp/success.jsp-->
<property name="prefix" value="/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 配置处理器映射器-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> </bean>
</list>
</property>
</bean>
</beans>
package ttt;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import user.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Controller
public class UserController {
@RequestMapping(value = "/quick2")
public ModelAndView save2(){
ModelAndView modelAndView = new ModelAndView();
//设置模型数据
modelAndView.addObject("username","白金");
//设置视图名称
modelAndView.setViewName("success");
return modelAndView;
}
@RequestMapping(value = "/quick3")
public ModelAndView save3(ModelAndView modelAndView){
//设置模型数据
modelAndView.addObject("username","银灰");
//设置视图名称
modelAndView.setViewName("success");
return modelAndView;
}
@RequestMapping(value = "/quick4")
public String save4(Model model){
model.addAttribute("username","内卫");
return "success";
}
@RequestMapping(value = "/quick5")
public String save5(HttpServletRequest request){
request.setAttribute("username","花官");
return "success";
}
@RequestMapping("/quick6")
public void save6(HttpServletResponse response) throws IOException { //回写数据
response.getWriter().print("hello ");
}
@RequestMapping("/quick7")
@ResponseBody //响应体,告诉springMVC,当前方法的返回数据为响应体数据
public String save7() { //回写数据
return "hello joune";
}
@RequestMapping("/quick8")
@ResponseBody
public String save8() throws JsonProcessingException {
User user = new User();
user.setName("lisi");
user.setAge(18);
//利用json的转化工具,将对象转化为json格式的字符串返回
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(user);
return json;
}
@RequestMapping("/quick")
public String save(){
System.out.println("Controller save running...");
return "success";
}
}
spring_mvc.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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的组件扫描-->
<context:component-scan base-package="ttt" />
<!-- 配置内部资源视图解析器-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- /jsp/success.jsp-->
<property name="prefix" value="/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 配置处理器映射器-->
<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">-->
<!-- <property name="messageConverters">-->
<!-- <list>-->
<!-- <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> </bean>-->
<!-- </list>-->
<!-- </property>-->
<!-- </bean>-->
<!-- mvc的注解驱动-->
<mvc:annotation-driven/>
</beans>
获得User集合类型的参数
测试类:
VO封装类:
package user;
import java.util.List;
public class VO {
private List<User> userList;
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
@Override
public String toString() {
return "VO{" +
"userList=" + userList +
'}';
}
public VO(List<User> userList) {
this.userList = userList;
}
public VO() {
}
}
表单页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/mave_spring_web_2_war_exploded/quick14" method="post">
<input type="text" name="userList[0].name"><br>
<input type="text" name="userList[0].age"><br>
<input type="text" name="userList[1].name"><br>
<input type="text" name="userList[1].age"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
web.xml文件:
date转换器类:
package converter;
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateConverter implements Converter<String ,Date> {
@Override
public Date convert(String dataStr) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date=null;
try {
date = simpleDateFormat.parse(dataStr);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
配置文件spring_mvc.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
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 http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">
<!-- Controller的组件扫描-->
<context:component-scan base-package="ttt" />
<!-- 配置内部资源视图解析器-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- /jsp/success.jsp-->
<property name="prefix" value="/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 配置处理器映射器-->
<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">-->
<!-- <property name="messageConverters">-->
<!-- <list>-->
<!-- <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> </bean>-->
<!-- </list>-->
<!-- </property>-->
<!-- </bean>-->
<!-- mvc的注解驱动-->
<mvc:annotation-driven conversion-service="ConversionService"/>
<!-- 开放资源的访问-->
<mvc:resources mapping="/js/**" location="/js/" />
<!-- 如果找不到资源,则交由原始服务器-->
<mvc:default-servlet-handler/>
<!-- 声明转换器-->
<bean id="ConversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="converter.DateConverter" />
</list>
</property>
</bean>
</beans>
测试类:
其中:
JSESSIONID是Cookie请求头中键的名称,通过键的名称获取请求体
测试类:
spring_mvc配置类:
多文件上传
测试类:
upload.xml表单文件:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/mave_spring_web_2_war_exploded/quick24" method="post" enctype="multipart/form-data">
名称<input type="text" name="username"><br>
文件<input type="file" name="uploadFile"><br>
文件<input type="file" name="uploadFile"><br>
文件<input type="file" name="uploadFile"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
总结
package test;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import java.beans.PropertyVetoException;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
public class JdbcTempletTest {
public static void main(String[] args) throws IOException, PropertyVetoException {
Properties properties = new Properties();
String path = JdbcTempletTest.class.getClassLoader().getResource("jdbc.properties").getPath();
properties.load(new FileReader(path));
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(properties.getProperty("jdbc.driver"));
dataSource.setJdbcUrl(properties.getProperty("jdbc.url"));
dataSource.setUser(properties.getProperty("jdbc.username"));
dataSource.setPassword(properties.getProperty("jdbc.password"));
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);
int update = jdbcTemplate.update("insert into student values (5,\"泥岩\",16,5)");
System.out.println(update);
}
}
applicationContext.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 加载外部的properties文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- jdbc模板对象-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
测试类:
package test;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
public class JdbcTempletTest {
@Test
public void test1() throws IOException, PropertyVetoException {
Properties properties = new Properties();
String path = JdbcTempletTest.class.getClassLoader().getResource("jdbc.properties").getPath();
properties.load(new FileReader(path));
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(properties.getProperty("jdbc.driver"));
dataSource.setJdbcUrl(properties.getProperty("jdbc.url"));
dataSource.setUser(properties.getProperty("jdbc.username"));
dataSource.setPassword(properties.getProperty("jdbc.password"));
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);
int update = jdbcTemplate.update("insert into student values (5,\"泥岩\",16,5)");
System.out.println(update);
}
@Test
public void test2() throws IOException, PropertyVetoException, SQLException {
ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
DataSource bean = classPathXmlApplicationContext.getBean(DataSource.class); //通过bean标签的id名,获取数据
Connection connection = bean.getConnection();
String sql = "INSERT INTO student VALUES (6,\"凯尔希\",1900,6)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
int i = preparedStatement.executeUpdate();
System.out.println(i);
}
@Test
public void test3() throws IOException, PropertyVetoException, SQLException {
ApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
JdbcTemplate bean1 = classPathXmlApplicationContext.getBean(JdbcTemplate.class);
int update = bean1.update("INSERT INTO student VALUES (7,\"赫默\",28,7)");
System.out.println(update);
}
}
简单的CRUD操作:
package test;
import User.student;
import com.fasterxml.jackson.databind.deser.impl.BeanPropertyMap;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class JdbcTemplateCRUDTest {
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
public void testQueryAll() {
Object o = jdbcTemplate.queryForObject("select count(*) from student", long.class);
System.out.println(o);
}
@Test
public void Update() {
jdbcTemplate.update("insert into student values (8,\"守林人\",23,8)");
}
@Test
public void Delete() {
jdbcTemplate.update("DELETE FROM student WHERE id=2");
}
}
SpringMVC拦截器:
拦截器类:
package interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class MyInterceptor1 implements HandlerInterceptor {
//在目标方法执行之前
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws ServletException, IOException {
System.out.println("preHandle");
String param = request.getParameter("param");
if("yes".equals(param)){
return true;
}else {
request.getRequestDispatcher("/error.jsp").forward(request,response);
return false; //默认返回false,后面的方法都不会执行
}
}
//在目标方法执行之后,视图对象返回之前执行
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView){
modelAndView.addObject("name","sili");
System.out.println("postHandle");
}
//在流程都执行完毕后,执行
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,Object handler,Exception exception){
System.out.println("afterCompletion");
}
}
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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
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 http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">
<!-- Controller的组件扫描-->
<context:component-scan base-package="controllerTest" />
<!-- 配置内部资源视图解析器-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- /jsp/success.jsp-->
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 配置处理器映射器-->
<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">-->
<!-- <property name="messageConverters">-->
<!-- <list>-->
<!-- <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> </bean>-->
<!-- </list>-->
<!-- </property>-->
<!-- </bean>-->
<!-- mvc的注解驱动-->
<mvc:annotation-driven conversion-service="ConversionService"/>
<!-- 开放资源的访问-->
<mvc:resources mapping="/js/**" location="/js/" />
<!-- 如果找不到资源,则交由原始服务器-->
<mvc:default-servlet-handler/>
<!-- mvc注解驱动-->
<mvc:annotation-driven />
<!-- 声明转换器-->
<bean id="ConversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="converter.DateConverter" />
</list>
</property>
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传总文件大小-->
<property name="maxUploadSize" value="5242800" />
<!-- 上传单个文件的大小-->
<property name="maxUploadSizePerFile" value="5242800" />
<!-- 上传文件的编码器-->
<property name="defaultEncoding" value="UTF-8" />
</bean>
<!-- 配置拦截器-->
<mvc:interceptors>
<mvc:interceptor>
<!-- 对哪些资源进行拦截-->
<mvc:mapping path="/**/"/>
<!-- 拦截时,执行类-->
<bean class="interceptor.MyInterceptor1" />
</mvc:interceptor>
</mvc:interceptors>
</beans>
返回对象类:
package controllerTest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class controller {
@RequestMapping("/target")
public ModelAndView show(){
System.out.println("目标资源执行。。。。");
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("name" ,"joune");
modelAndView.setViewName("index");
return modelAndView;
}
}