SSM-Spring-22:Spring+Mybatis+JavaWeb的整合

释放双眼,带上耳机,听听看~!

 

 

————吾亦无他,唯手熟尔,谦卑若愚,好学若饥————-

 

 

众所周知,框架Spring来整合别的框架,但是Mybatis出现的晚,Spring就没有给他提供支持,那怎么办呢?Mybatis说,我吃点亏,我给你提供整合的jar,所以那个整合的jar包就叫mabatis-spring。jar

由于SpringMVC和Spring天然集成,所以,Spring整合了Mabatis就证明你ssm整合就搞定了

 

整合并不只是jar包的堆砌,而是一个框架的部分功能要交给另外一个框架进行完成,调度

 

写个案例,购买添加图书的Spring+Mabatis+JavaWeb的案例

 

步骤开始:

1.引入jar包,修改build节点:

我之前案例的节点,可能这个案例用不到,但是也一块扔上来了

 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
1<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
3    <parent>
4        <artifactId>Y2167DAWNALLDEMO</artifactId>
5        <groupId>cn.dawn</groupId>
6        <version>1.0-SNAPSHOT</version>
7    </parent>
8    <modelVersion>4.0.0</modelVersion>
9    <artifactId>02Spring</artifactId>
10    <packaging>war</packaging>
11    <name>02Spring Maven Webapp</name>
12    <url>http://maven.apache.org</url>
13    <dependencies>
14        <!--单元测试的依赖  ctrl+shif+/-->
15        <dependency>
16            <groupId>junit</groupId>
17            <artifactId>junit</artifactId>
18            <version>4.12</version>
19            <scope>test</scope>
20        </dependency>
21
22        <!--Spring-->
23        <dependency>
24            <groupId>org.springframework</groupId>
25            <artifactId>spring-beans</artifactId>
26            <version>4.2.0.RELEASE</version>
27        </dependency>
28
29        <dependency>
30            <groupId>org.springframework</groupId>
31            <artifactId>spring-context</artifactId>
32            <version>4.2.0.RELEASE</version>
33        </dependency>
34
35        <!--aop使用的jar-->
36        <dependency>
37            <groupId> org.aspectj</groupId >
38            <artifactId> aspectjweaver</artifactId >
39            <version> 1.8.7</version>
40        </dependency>
41
42
43        <!--spring jdbc-->
44        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
45        <dependency>
46            <groupId>org.springframework</groupId>
47            <artifactId>spring-jdbc</artifactId>
48            <version>4.2.0.RELEASE</version>
49        </dependency>
50
51
52        <dependency>
53            <groupId>mysql</groupId>
54            <artifactId>mysql-connector-java</artifactId>
55            <version>5.1.39</version>
56        </dependency>
57
58
59
60        <!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
61        <dependency>
62            <groupId>c3p0</groupId>
63            <artifactId>c3p0</artifactId>
64            <version>0.9.1.2</version>
65        </dependency>
66
67        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
68        <dependency>
69            <groupId>org.apache.commons</groupId>
70            <artifactId>commons-dbcp2</artifactId>
71            <version>2.1.1</version>
72        </dependency>
73
74        <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
75        <dependency>
76            <groupId>com.alibaba</groupId>
77            <artifactId>druid</artifactId>
78            <version>1.1.6</version>
79        </dependency>
80
81
82
83        <!--mybatis jar包-->
84        <dependency>
85            <groupId>org.mybatis</groupId>
86            <artifactId>mybatis</artifactId>
87            <version>3.2.2</version>
88        </dependency>
89
90        <!--Mybatis+Spring整合-->
91        <dependency>
92            <groupId>org.mybatis</groupId>
93            <artifactId>mybatis-spring</artifactId>
94            <version>1.2.1</version>
95        </dependency>
96
97        <!-- Spring整合JavaWeb的包 -->
98        <dependency>
99            <groupId>org.springframework</groupId>
100            <artifactId>spring-web</artifactId>
101            <version>4.2.0.RELEASE</version>
102        </dependency>
103
104        <!--javaee  jar-->
105        <dependency>
106            <groupId>javaee</groupId>
107            <artifactId>javaee-api</artifactId>
108            <version>5</version>
109        </dependency>
110
111        <!--jstl表达式-->
112        <dependency>
113            <groupId>jstl</groupId>
114            <artifactId>jstl</artifactId>
115            <version>1.2</version>
116        </dependency>
117
118
119
120    </dependencies>
121    <build>
122        <resources>
123            <resource>
124                <directory>src/main/java</directory>
125                <includes>
126                    <include>**/*.xml</include>
127                </includes>
128            </resource>
129        </resources>
130    </build>
131</project>
132

 

2.准备数据库:


 

 

3.分层开发开始:

3.1entity层

Book实体类

 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
1package cn.dawn.day23ssm.entity;
2
3public class Book {
4    private Integer bookID;
5    private String bookName;
6    private String bookAuthor;
7    private Integer bookPrice;
8
9    public Book() {
10    }
11
12    public Book(String bookName, String bookAuthor, Integer bookPrice) {
13        this.bookName = bookName;
14        this.bookAuthor = bookAuthor;
15        this.bookPrice = bookPrice;
16    }
17
18    public Integer getBookID() {
19        return this.bookID;
20    }
21
22    public void setBookID(Integer bookID) {
23        this.bookID = bookID;
24    }
25
26    public String getBookName() {
27        return this.bookName;
28    }
29
30    public void setBookName(String bookName) {
31        this.bookName = bookName;
32    }
33
34    public String getBookAuthor() {
35        return this.bookAuthor;
36    }
37
38    public void setBookAuthor(String bookAuthor) {
39        this.bookAuthor = bookAuthor;
40    }
41
42    public Integer getBookPrice() {
43        return this.bookPrice;
44    }
45
46    public void setBookPrice(Integer bookPrice) {
47        this.bookPrice = bookPrice;
48    }
49}
50

 

3.2dao层

接口IBookDAO

 


1
2
3
4
5
6
7
8
9
10
11
12
1package cn.dawn.day23ssm.dao;
2
3import cn.dawn.day23ssm.entity.Book;
4
5/**
6 * Created by Dawn on 2018/3/17.
7 */
8public interface IBookDAO {
9    //添加
10    public int insertBook(Book book) throws Exception;
11}
12

 

同名的IBookDAO.xml配置文件

 


1
2
3
4
5
6
7
8
9
10
11
12
13
1<?xml version="1.0" encoding="UTF-8" ?>
2<!DOCTYPE mapper
3        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
4        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
5<mapper namespace="cn.dawn.day23ssm.dao.IBookDAO">
6
7    <insert id="insertBook">
8        INSERT  INTO book(bookname,bookauthor,bookprice) VALUES (#{bookName},#{bookAuthor},#{bookPrice})
9    </insert>
10
11
12</mapper>
13

 

3.3service层

IBookService接口:

 


1
2
3
4
5
6
7
8
9
10
11
12
1package cn.dawn.day23ssm.service;
2
3import cn.dawn.day23ssm.entity.Book;
4
5/**
6 * Created by Dawn on 2018/3/17.
7 */
8public interface IBookService {
9    //添加
10    public int insertBook(Book book) throws Exception;
11}
12

 

BookServiceImpl刚才那个接口的实现类

 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
1package cn.dawn.day23ssm.service;
2
3import cn.dawn.day23ssm.dao.IBookDAO;
4import cn.dawn.day23ssm.entity.Book;
5import org.springframework.transaction.annotation.Transactional;
6
7/**
8 * Created by Dawn on 2018/3/17.
9 */
10public class BookServiceImpl implements IBookService {
11    private IBookDAO dao;
12
13    //开启事务
14    @Transactional
15    public int insertBook(Book book) throws Exception {
16        return dao.insertBook(book);
17    }
18
19    public IBookDAO getDao() {
20        return dao;
21    }
22
23    public void setDao(IBookDAO dao) {
24        this.dao = dao;
25    }
26}
27

 

此处我做了事务的开启

3.我的习惯是在此处开始写配置文件,走个单测再去和javaweb打交道

所以此处的步骤就是三个大配置文件

3.1jdbc.properties

 


1
2
3
4
5
1jdbc.driver=com.mysql.jdbc.Driver
2jdbc.url=jdbc:mysql:///s2228
3jdbc.username=root
4jdbc.password=
5

 

3.2mybatis-config.xml

 


1
2
3
4
5
6
7
8
9
10
1<?xml version="1.0" encoding="UTF-8" ?>
2<!DOCTYPE configuration
3        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
4        "http://mybatis.org/dtd/mybatis-3-config.dtd">
5<configuration>
6    <typeAliases>
7        <package name="cn.dawn.day23ssm.entity"></package>
8    </typeAliases>
9</configuration>
10

 

此处的mybatis只做了别名,但是这个案例中没有用,只是提一下,如果做查询的时候,别名从这儿设置,我一会也给把加入spring的地方也标出来

它的mappers,properties都不从这儿设置,这就印证了我之前的一句话,整合并不只是jar包的堆砌,而是一个框架的部分功能要交给另外一个框架进行完成,调度

3.3ApplicationContext-day23ssm.xml(你们可以改这个名字的,一会调用的时候改掉就可以了,不要学死,灵活应变,举一反三)

 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
1<?xml version="1.0" encoding="UTF-8"?>
2<beans xmlns="http://www.springframework.org/schema/beans"
3       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4       xmlns:aop="http://www.springframework.org/schema/aop"
5       xmlns:p="http://www.springframework.org/schema/p"
6       xmlns:context="http://www.springframework.org/schema/context"
7       xmlns:tx="http://www.springframework.org/schema/tx"
8       xsi:schemaLocation="http://www.springframework.org/schema/beans
9       http://www.springframework.org/schema/beans/spring-beans.xsd
10       http://www.springframework.org/schema/aop
11       http://www.springframework.org/schema/aop/spring-aop.xsd
12       http://www.springframework.org/schema/context
13       http://www.springframework.org/schema/context/spring-context.xsd
14       http://www.springframework.org/schema/tx
15       http://www.springframework.org/schema/tx/spring-tx.xsd">
16
17    <!--配置jdbc。properties-->
18    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
19
20
21    <!--阿里的Druid-->
22    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
23        <property name="driverClassName" value="${jdbc.driver}"></property>
24        <property name="url" value="${jdbc.url}"></property>
25        <property name="username" value="${jdbc.username}"></property>
26        <property name="password" value="${jdbc.password}"></property>
27    </bean>
28    
29
30    <!--dao层-->
31    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
32        <property name="dataSource" ref="dataSource"></property>
33        <!--这儿的mybatis配置文件中只做别名,其他的都由spring整合了-->
34        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
35    </bean>
36    <!--映射扫描器-->
37    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
38        <property name="basePackage" value="cn.dawn.day23ssm.dao"></property>
39    </bean>
40    <!--service-->
41    <bean id="bookService" class="cn.dawn.day23ssm.service.BookServiceImpl">
42        <property name="dao" ref="IBookDAO"></property>
43    </bean>
44    <!--事务管理器-->
45    <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
46        <property name="dataSource" ref="dataSource"></property>
47    </bean>
48    <!--事务开启,注解版-->
49    <tx:annotation-driven transaction-manager="dataSourceTransactionManager"></tx:annotation-driven>
50
51</beans>
52

 

4.jsp页面和servlet

4.1jsp页面

success.jsp

 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
1<%--
2  Created by IntelliJ IDEA.
3  User: Dawn
4  Date: 2018/3/17
5  Time: 14:39
6  To change this template use File | Settings | File Templates.
7--%>
8<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
9<html>
10<head>
11    <title>添加成功</title>
12</head>
13<body>
14    <h2 style="text-align: center;color: red">添加${bookName}成功</h2>
15</body>
16</html>
17

 

addBook.jsp

 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
1<%--
2  Created by IntelliJ IDEA.
3  User: Dawn
4  Date: 2018/3/17
5  Time: 14:41
6  To change this template use File | Settings | File Templates.
7--%>
8<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
9<html>
10<head>
11    <title>添加图书页面</title>
12</head>
13<body>
14    <form method="post" action="${pageContext.request.contextPath}/BookServlet">
15        书名:<input type="text" name="bookName">
16        作者:<input type="text" name="bookAuthor">
17        价格:<input type="text" name="bookPrice">
18        <input type="submit" value="添加图书">
19    </form>
20</body>
21</html>
22

 

4.2servlet层

BookServlet

 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
1package cn.dawn.day23ssm.servlet;
2
3import cn.dawn.day23ssm.entity.Book;
4import cn.dawn.day23ssm.service.IBookService;
5import org.springframework.context.ApplicationContext;
6import org.springframework.context.support.ClassPathXmlApplicationContext;
7import org.springframework.web.context.support.WebApplicationContextUtils;
8
9import javax.servlet.ServletException;
10import javax.servlet.http.HttpServlet;
11import javax.servlet.http.HttpServletRequest;
12import javax.servlet.http.HttpServletResponse;
13import java.io.IOException;
14
15/**
16 * Created by Dawn on 2018/3/17.
17 */
18public class BookServlet extends HttpServlet {
19    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
20        //解决乱码
21        request.setCharacterEncoding("utf-8");
22        //获取书名
23        String bookName = request.getParameter("bookName");
24        //获取作者
25        String bookAuthor = request.getParameter("bookAuthor");
26        //获取价格
27        String bookPriceStr = request.getParameter("bookPrice");
28        Integer bookPrice=Integer.parseInt(bookPriceStr);
29        //创建图书对象
30        Book book=new Book(bookName,bookAuthor,bookPrice);
31        //创建service对象  
32     //采用优雅的方式:  
33     //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++  
34
35        ApplicationContext applicationContext= WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());  
36      
37        //ApplicationContext applicationContext=new ClassPathXmlApplicationContext("ApplicationContext-day23ssm.xml");
38        IBookService bookService = (IBookService)applicationContext.getBean("bookService");
39        //调用方法
40        try {
41            int result = bookService.insertBook(book);
42            //根据返回结果判断是否成功
43            if (result>0){
44                //把结果传过去
45                request.setAttribute("bookName",bookName);
46                //成功,转发到Index页面
47                request.getRequestDispatcher("/success.jsp").forward(request,response);
48
49            }else {
50                //失败,重定向到刚才的页面
51                response.sendRedirect("/ssm/addBook.jsp");
52            }
53
54        } catch (Exception e) {
55            e.printStackTrace();
56        }
57
58
59    }
60
61    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
62        doPost(request,response);
63    }
64}
65

 

这儿有我之前埋的一个坑,我这儿用的javaee是5的版本,不是6.0,没法用注解版,所以还得到web.xml中配置一道

4.3web。xml

 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
1<!DOCTYPE web-app PUBLIC
2 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
3 "http://java.sun.com/dtd/web-app_2_3.dtd" >
4
5<web-app>
6  <display-name>Archetype Created Web Application</display-name>
7
8  <context-param>
9    <param-name>contextConfigLocation</param-name>
10    <param-value>classpath:ApplicationContext-day23ssm.xml</param-value>
11  </context-param>
12  <!--监听器-->
13  <listener>
14    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
15  </listener>
16  <servlet>
17    <servlet-name>BookServlet</servlet-name>
18    <servlet-class>cn.dawn.day23ssm.servlet.BookServlet</servlet-class>
19  </servlet>
20  <servlet-mapping>
21    <servlet-name>BookServlet</servlet-name>
22    <url-pattern>/BookServlet</url-pattern>
23  </servlet-mapping>
24  <welcome-file-list>
25    <welcome-file>index.jsp</welcome-file>
26  </welcome-file-list>
27</web-app>
28

 

 

这儿有一处之前没有见到过

**
servlet处的**

****ApplicationContext applicationContext= WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());


1
2
3
4
5
6
7
8
1和web.xml中的监听器和配置这是什么呢?  
2这是一个优雅的方式,  
3 总所周知,你将之前单测的那种方式你直接拖过来用,那在servlet中会造成什么后果呢?  
4  就是每一次访问servlet你就对spring容器进行一次初始化工作,这里面的bean因为是单例的,所以都会生成一次,相当耗损性能  
5 那么怎么办?  
6  你想servletcontext就是在web容器中从一开始到结束过程中都可以访问到的,那么我们在web容器一启动的时候就将spring容器放到servletcontext中岂不美哉,之后就不用new了  
7  
8

 

 

——-笔者:晨曦Dawn——-****

转载请注明出处:http://www.cnblogs.com/DawnCHENXI/p/8597436.html

给TA打赏
共{{data.count}}人
人已打赏
安全技术

C++迭代器

2022-1-11 12:36:11

安全漏洞

AMD 漏洞被“暴力”公开 Linux 之父愤怒回应

2018-3-16 11:12:22

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索