赞
踩
【写完博客后的补充:这里一次性给出全部依赖】
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>SSM</artifactId>
- <version>1.0-SNAPSHOT</version>
- <packaging>war</packaging>
-
- <name>SSM Maven Webapp</name>
- <!-- FIXME change it to the project's website -->
- <url>http://www.example.com</url>
-
- <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>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- <version>5.1.8.RELEASE</version>
- </dependency>
-
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.12</version>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-test</artifactId>
- <version>5.1.8.RELEASE</version>
- </dependency>
-
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>8.0.16</version>
- </dependency>
-
- <dependency>
- <groupId>org.mybatis</groupId>
- <artifactId>mybatis</artifactId>
- <version>3.4.5</version>
- </dependency>
-
- <dependency>
- <groupId>org.mybatis</groupId>
- <artifactId>mybatis-spring</artifactId>
- <version>1.3.1</version>
- </dependency>
-
- <dependency>
- <groupId>com.mchange</groupId>
- <artifactId>c3p0</artifactId>
- <version>0.9.5.2</version>
- </dependency>
-
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-tx</artifactId>
- <version>5.1.8.RELEASE</version>
- </dependency>
-
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-jdbc</artifactId>
- <version>5.1.8.RELEASE</version>
- </dependency>
-
- <dependency>
- <groupId>jstl</groupId>
- <artifactId>jstl</artifactId>
- <version>1.2</version>
- </dependency>
- <dependency>
- <groupId>taglibs</groupId>
- <artifactId>standard</artifactId>
- <version>1.1.2</version>
- </dependency>
- </dependencies>
-
- <build>
- <finalName>SSM</finalName>
- <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
- <plugins>
- <plugin>
- <artifactId>maven-clean-plugin</artifactId>
- <version>3.1.0</version>
- </plugin>
- <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
- <plugin>
- <artifactId>maven-resources-plugin</artifactId>
- <version>3.0.2</version>
- </plugin>
- <plugin>
- <artifactId>maven-compiler-plugin</artifactId>
- <version>3.8.0</version>
- </plugin>
- <plugin>
- <artifactId>maven-surefire-plugin</artifactId>
- <version>2.22.1</version>
- </plugin>
- <plugin>
- <artifactId>maven-war-plugin</artifactId>
- <version>3.2.2</version>
- </plugin>
- <plugin>
- <artifactId>maven-install-plugin</artifactId>
- <version>2.5.2</version>
- </plugin>
- <plugin>
- <artifactId>maven-deploy-plugin</artifactId>
- <version>2.8.2</version>
- </plugin>
- </plugins>
- </pluginManagement>
- </build>
- </project>
一、创建项目
1、使用Web模板,新建Maven项目:
2、导包,即添加Maven依赖:spring-webmvc、junit
- <dependencies>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- <version>5.1.8.RELEASE</version>
- </dependency>
-
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.12</version>
- <scope>test</scope>
- </dependency>
- </dependencies>
导包结果:
从上面这张依赖图可以看出,咱们明面上只导了两个包,实际上却有这么多包进来了,其中包括Spring、SpringMVC!
3、建好项目的结构:在main文件夹下新建java文件夹(要标记为Sources Root)和resources文件夹(要标记为Resources Root),然后在java文件夹下新建csdn.domain、csdn.dao、csdn.service、csdn.controller这几个包,建好后长这样:
二、搭建Spring的环境
1、在csdn.domain下新建Account类:
package csdn.domain; public class Account { private Integer id; private String name; private Double money; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getMoney() { return money; } public void setMoney(Double money) { this.money = money; } @Override public String toString() { return "Account{" + "id=" + id + ", name='" + name + '\'' + ", money=" + money + '}'; } }
2、在csdn.dao下新建AccountDao接口:
- package csdn.dao;
-
- import csdn.domain.Account;
-
- import java.util.List;
-
- public interface AccountDao {
- List<Account> findAll();
- void save(Account account);
- }
3、在csdn.dao下新建impl子包,再在impl子包下新建AccountDaoImpl类(两步可合并为一步,即直接在csdn.dao下新建impl.AccountDaoImpl类;后面也有类似的操作,不再赘述!):
- package csdn.dao.impl;
-
- import csdn.dao.AccountDao;
- import csdn.domain.Account;
- import org.springframework.stereotype.Repository;
-
- import java.util.List;
-
- @Repository("accountDao")
- public class AccountDaoImpl implements AccountDao {
- @Override
- public List<Account> findAll() {
- System.out.println("AccountDao实现类中的findAll方法到此一游~");
- return null;
- }
-
- @Override
- public void save(Account account) {
- System.out.println("AccountDao实现类中的save方法到此一游~");
- }
- }
4、在csdn.service下新建AccountService接口:
- package csdn.service;
-
- import csdn.domain.Account;
-
- import java.util.List;
-
- public interface AccountService {
- List<Account> findAll();
- void save(Account account);
- }
5、在csdn.service下新建impl子包,再在impl子包下新建AccountServiceImpl类:
- package csdn.service.impl;
-
- import csdn.dao.AccountDao;
- import csdn.domain.Account;
- import csdn.service.AccountService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
-
- import java.util.List;
-
- @Service("accountService")
- public class AccountServiceImpl implements AccountService {
- @Autowired
- private AccountDao accountDao;
-
- @Override
- public List<Account> findAll() {
- accountDao.findAll();
- System.out.println("我是AccountService实现类,我刚刚调用了dao~");
- return null;
- }
-
- @Override
- public void save(Account account) {
- accountDao.save(account);
- System.out.println("我是AccountService实现类,我刚刚调用了dao~");
- }
- }
6、在resources下新建spring.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">
- <context:component-scan base-package="csdn">
- <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
- </context:component-scan>
- </beans>
7.1、在main文件夹下新建test文件夹,并标记为Test Sources Root:
7.2、在pom.xml中新增spring-test依赖(开头有完整版pom.xml)
7.3、在test文件夹下新建SpringTest类:
import csdn.domain.Account; import csdn.service.AccountService; 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; @ContextConfiguration(locations = "classpath:spring.xml") @RunWith(SpringJUnit4ClassRunner.class) public class SpringTest { @Autowired private AccountService accountService; @Test public void test() { accountService.findAll(); //accountService.save(new Account()); } }
经测试,Spring没毛病!
三、搭建SpringMVC的环境
1、在webapp下新建css、js、image文件夹,在WEB-INF下新建pages文件夹:
2、在resources下新建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: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 https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
- <context:component-scan base-package="csdn">
- <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
- </context:component-scan>
- <mvc:annotation-driven />
-
- <mvc:resources mapping="/css/**" location="/css/" />
- <mvc:resources mapping="/js/**" location="/js/" />
- <mvc:resources mapping="/image/**" location="/image/" />
-
- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
- <property name="prefix" value="/WEB-INF/pages/" />
- <property name="suffix" value=".jsp" />
- </bean>
- </beans>
3、修改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>
-
- <filter>
- <filter-name>characterEncodingFilter</filter-name>
- <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
- </filter>
-
- <filter-mapping>
- <filter-name>characterEncodingFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
-
- <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:springmvc.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>
4、删除index.jsp,再新建index.jsp:
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <html>
- <head>
- <title>Title</title>
- </head>
- <body>
- <h3><a href="hello">toHello</a></h3>
- </body>
- </html>
5、在pages下新建hello.jsp:
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <html>
- <head>
- <title>Title</title>
- </head>
- <body>
- <h3>hello</h3>
- </body>
- </html>
6、在controller包下新建HelloController类:
- package csdn.controller;
-
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
-
- @Controller
- public class HelloController {
- @RequestMapping("/hello")
- public String hello() {
- return "hello";
- }
- }
7、添加Tomcat,并关联项目:
8、启动Web项目,经测试,SpringMVC没毛病!
四、Spring与SpringMVC的整合
1、修改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:spring.xml</param-value>
- </context-param>
-
- <filter>
- <filter-name>characterEncodingFilter</filter-name>
- <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
- </filter>
-
- <filter-mapping>
- <filter-name>characterEncodingFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
-
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
-
- <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:springmvc.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>
2、修改HelloController:
package csdn.controller; import csdn.service.AccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HelloController { @Autowired private AccountService accountService; @RequestMapping("/hello") public String hello() { accountService.findAll(); System.out.println("我是HelloController,我刚刚调用了accountService~"); return "hello"; } }
3、重启Tomcat,点击超链接,页面成功跳转,控制台输出:
Spring和SpringMVC整合成功!
五、搭建MyBatis的环境
1、增加Maven依赖:mysql-connector-java、mybatis(开头有完整版pom.xml)
2、准备好数据库,新建account表(id,name,money),填充若干条记录。
database:test port:3306 table:account
3、编写account表对应的实体类Account(前面已有)。
4、编写AccountDao接口(前面已有)。
5、在resources下新建csdn文件夹,再在csdn文件下新建dao文件夹,编写AccountDao.xml:
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE mapper
- PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mapper namespace="csdn.dao.AccountDao">
- <select id="findAll" resultType="csdn.domain.Account">
- select * from account
- </select>
-
- <insert id="save" parameterType="csdn.domain.Account">
- insert into account (name, money) values (#{name}, #{money})
- </insert>
- </mapper>
6、在resources下新建mybatis.xml:
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE configuration
- PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-config.dtd">
- <configuration>
- <environments default="mysql">
- <environment id="mysql">
- <transactionManager type="JDBC"></transactionManager>
- <dataSource type="POOLED">
- <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
- <property name="url" value="jdbc:mysql://localhost:3306/Test?characterEncoding=UTF8&serverTimezone=Asia/Shanghai"/>
- <property name="username" value="root"/>
- <property name="password" value="root"/>
- </dataSource>
- </environment>
- </environments>
-
- <mappers>
- <mapper resource="csdn/dao/AccountDao.xml" />
- </mappers>
- </configuration>
7、在test文件夹下新建MyBatisTest类:
- import csdn.dao.AccountDao;
- import csdn.domain.Account;
- import org.apache.ibatis.io.Resources;
- import org.apache.ibatis.session.SqlSession;
- import org.apache.ibatis.session.SqlSessionFactory;
- import org.apache.ibatis.session.SqlSessionFactoryBuilder;
- import org.junit.Test;
-
- import java.io.InputStream;
- import java.util.List;
-
- public class MyBatisTest {
- @Test
- public void test() throws Exception {
- InputStream in = Resources.getResourceAsStream("mybatis.xml");
- SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
- SqlSessionFactory factory = builder.build(in);
- SqlSession session = factory.openSession(true);
- AccountDao accountDao = session.getMapper(AccountDao.class);
- List<Account> accounts = accountDao.findAll();
- for(Account account: accounts) {
- System.out.println(account);
- }
- session.close();
- in.close();
- }
- }
经测试,MyBatis没毛病!
六、整合Spring和MyBatis
1、增加Maven依赖:mybatis-spring、c3p0、spring-tx、spring-jdbc(开头有完整版pom.xml)
2、修改spring.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">
- <context:component-scan base-package="csdn">
- <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
- </context:component-scan>
-
- <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
- <property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
- <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test?characterEncoding=UTF8&serverTimezone=Asia/Shanghai"></property>
- <property name="user" value="root"></property>
- <property name="password" value="root"></property>
- </bean>
-
- <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
- <property name="dataSource" ref="dataSource" />
- </bean>
-
- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" id="mapperScannerConfigurer">
- <property name="basePackage" value="csdn.dao" />
- </bean>
- </beans>
3、修改AccountDao接口:
- package csdn.dao;
-
- import csdn.domain.Account;
- import org.springframework.stereotype.Repository;
-
- import java.util.List;
-
- @Repository("accountDaoProxy")
- public interface AccountDao {
- List<Account> findAll();
- void save(Account account);
- }
4、在test文件夹下新建SpringAndMyBatisTest类:
- import csdn.dao.AccountDao;
- import csdn.domain.Account;
- import org.junit.Test;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
-
- import java.util.List;
-
- public class SpringAndMyBatisTest {
- @Test
- public void test() {
- ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
- AccountDao accountDao = context.getBean("accountDaoProxy", AccountDao.class);
- List<Account> accounts = accountDao.findAll();
- for (Account account : accounts) {
- System.out.println(account);
- }
-
- }
- }
经测试,没毛病!
七、Spring、SpringMVC、MyBatis三体合一
1、导入依赖:jstl、standard(开头有完整版pom.xml)
2、修改AccountServiceImpl类:
- package csdn.service.impl;
-
- import csdn.dao.AccountDao;
- import csdn.domain.Account;
- import csdn.service.AccountService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.beans.factory.annotation.Qualifier;
- import org.springframework.stereotype.Service;
-
- import java.util.List;
-
- @Service("accountService")
- public class AccountServiceImpl implements AccountService {
- @Autowired
- @Qualifier("accountDaoProxy")
- private AccountDao accountDao;
-
- @Override
- public List<Account> findAll() {
- return accountDao.findAll();
- }
-
- @Override
- public void save(Account account) {
- accountDao.save(account);
- }
- }
3、修改index.jsp:
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <html>
- <head>
- <title>Title</title>
- </head>
- <body>
- <h3><a href="hello">toHello</a></h3>
- <form method="post" action="save">
- name: <input type="text" name="name" /><br />
- money: <input type="text" name="money" /><br />
- <input type="submit" value="提交" />
- </form>
- </body>
- </html>
4、修改HelloController类:
- package csdn.controller;
-
- import csdn.domain.Account;
- import csdn.service.AccountService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.Model;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.servlet.ModelAndView;
-
- import java.util.List;
-
- @Controller
- public class HelloController {
- @Autowired
- private AccountService accountService;
-
- @RequestMapping("/hello")
- public String hello(Model model) {
- List<Account> accounts = accountService.findAll();
- model.addAttribute("accounts", accounts);
- return "hello";
- }
-
- @RequestMapping("/save")
- public String save(Account account) {
- accountService.save(account);
- return "forward:/hello"; //会请求上一个方法,hello方法
- }
- }
5、修改hello.jsp:
- <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
- <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
- <html>
- <head>
- <title>Title</title>
- </head>
- <body>
- <c:forEach items="${accounts}" var="account">
- <c:out value="${account.id}" />
- <c:out value="${account.name}" />
- <c:out value="${account.money}" />
- <br /><br />
- </c:forEach>
- </body>
- </html>
测试结果:
至此,SSM整合成功!
项目结构:
源码链接: https://pan.baidu.com/s/1jFvIhmCiy-tXhNDG3b_dlg 提取码: z8nb
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。