SSM框架整合(超详细附带源码)

在学习完spring,springmvc,mybatis之后需要整合到一起,然后就可以开始找一个ssm+jsp项目,练练手了

1.各个工具的版本信息

MySQL版本:8.0.17 ,图像化工具:Navicat Premiun12
IDEA版本:2021.1.1 X64
JDK版本:17
tomcat版本:9
maven版本:3.6.3

这里不显示怎么创建maven的web-app工程和数据库的表(id,name,age),直接进入正题!!

2.在maven中导入相应的jar包

跟mybatis相关坐标:

<dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.22</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.5</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.5</version>
    </dependency>

与spring相关的坐标:

 <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.3.13</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>5.3.13</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.2.12.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.9.6</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>5.3.13</version>
    </dependency>

与spring mvc相关坐标:

 <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.12.RELEASE</version>
    </dependency>

与servlet及jsp相关坐标:

 <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.1</version>
    </dependency>

其他相关工具类

 <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.2.4</version>
    </dependency>

3.搭建骨架

在resource资源目录下分别建立spring,springmvc,mybatis,jdbc和mapper文件的配置文件

效果如下:

SSM框架整合(超详细附带源码)_第1张图片

具体代码如下:

jdbc.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql:///day23?serverTimezone=UTC
jdbc.username=root
jdbc.password=123456

applicationContext.xml和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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">

sqlMapConfig-spring.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>

UserMapper.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">

webapp下的WEB-INF文件中的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">

jsp文件

效果如下:
SSM框架整合(超详细附带源码)_第2张图片
如果你的web.xml文件是2.3版本及以前,那么当你使用JSTL或者EL表达式的时候,你需要在jsp页面的标签头加上 isELIgnored=“false”,否则JSTL或者EL表达式会失效(我这里是2.5版本)
jstl表达式失效原因

具体代码:
pages文件下的userList:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Titletitle>
head>
<body>
<h1>展示账户数据列表h1>
<table border="1px">
    <tr>
        <th>idth>
        <th>名字th>
        <th>年龄th>
    tr>
    <c:forEach items="${userList}" var="user">
        <tr>
        <td>${user.id}td>
        <td>${user.name}td>
        <td>${user.age}td>
        tr>
    c:forEach>
table>
body>
html>

webapp下的save:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Titletitle>
head>
<body>
   <h1>添加账户信息表单h1>
<form name="accountForm" action="${pageContext.request.contextPath}/user/save" method="post">
    名字<input type="text" name="name"><br>
    年龄<input type="text" name="age"><br>
       <input type="submit" value="提交">
form>
body>
html>

java文件中的骨架结构:

效果如下:
SSM框架整合(超详细附带源码)_第3张图片
具体代码:

domain包下User类:

public class User {
    private  int id;
    private String name;
    private int age;
    //就不复制了,浪费地方,自己去自动生成
    //构造方法
    //setXxx()/getXxx()
    //toString()
    }

dao包下的UserDao

public interface UserDao {
    //保存
    public void save(User user);
    //查找
    public List<User> findAll();
}

service包下UserService

public interface UserService {
    public void save(User user);
    public List<User> findAll();
}

service包的impl包下的UserServiceImpl

@Service("userService")
public class UserServiceImpl implements UserService {
    @Override
    public void save(User user) {
        
    }
    @Override
    public List<User> findAll() {
         return 0;
    }
}

controller包下UserController

@Controller
@RequestMapping("/user")
public class UserController {
}

4.对xml文件做具体配置

首先在applicationContext.xml配置


    <context:component-scan base-package="com.dao"/>
    <context:component-scan base-package="com.service"/>
    
 
 <context:property-placeholder location="classpath:jdbc.properties"/>
    <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    bean>
    
  
 <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="druidDataSource"/>
    <property name="configLocation" value="classpath:sqlMapConfig-spring.xml"/>
    
    <property name="mapperLocations" value="classpath:com/mapper/*.xml"/>
bean>  

    
<bean  class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.dao"/>
bean> 

spring-mvc.xml:


<context:component-scan base-package="com.controller"/>

    <mvc:annotation-driven>mvc:annotation-driven>

    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    bean>

    <mvc:default-servlet-handler>mvc:default-servlet-handler>
beans>

splMapConfig-spring.xml


<typeAliases>



    <package name="com.domain"/>
typeAliases>

web.xml


    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:applicationContext.xmlparam-value>
    context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>


<servlet>
    <servlet-name>dispatcherServletservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    <init-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:spring-mvc.xmlparam-value>
    init-param>
    <load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
    <servlet-name>dispatcherServletservlet-name>

    <url-pattern>/url-pattern>
servlet-mapping>

  
<filter>
    <filter-name>characterEncodingFilterfilter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    <init-param>
        <param-name>encodingparam-name>
        <param-value>utf-8param-value>
    init-param>
filter>
    <filter-mapping>
        <filter-name>characterEncodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

具体业务实现

保存功能:
首先在save.jsp中写入一个简单的form表单,在action属性中配置${pageContext.request.contextPath}/user/save,然后找到controller包下的UserController中填写

@Autowired
    private UserService userService;
    @RequestMapping(value = "/save",produces = "text/html;charset=utf-8")
    @ResponseBody
    public String save(User user) {
            userService.save(user);
        return "保存成功";
    }

然后在service包下的impl包下的UserServiceImpl填写:

   @Autowired
    private UserDao userDao;
    @Override
    public void save(User user) {
        userDao.save(user);
    }

然后在resources资源下的com包下的mapper包下的UserMapper.xml下填写

<mapper namespace="com.dao.UserDao">
 <insert id="save"  parameterType="user">
     insert into user values(#{id},#{name},#{age})
 insert>

1.这里我有个问题就是不知道namespace中填写的接口能否起别名,试了好像不行。
2.这里的parameterType="user"的user已经在sqlMapConfig-spring.xml文件起了别名
3.这里还有一个小坑我搞了半天才解决,如果你在java文件中给dao包起名叫mapper包和resources资源的UserMapper.xml的mapper包同名那么你在applicatonContext.xml文件可以不用写我标的红框SSM框架整合(超详细附带源码)_第4张图片直接写下面这句就那能同时都扫描了(我写的是dao,你们改一下)
SSM框架整合(超详细附带源码)_第5张图片
但是如果你跟我起的包名一样,一个是Dao包一个是Mapper包你就要在配置sessionFactory的bean中加上,否则就会出现mybatis找不到mapper配置文件错误

最后在applicationContext.xml文件中配置事务控制

    
    
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
    <property name="dataSource" ref="druidDataSource"/>
bean>
    
    <tx:advice  id="txadvice">
        <tx:attributes>
            <tx:method name="*"/>
        tx:attributes>
    tx:advice>
    
    <aop:config>
        <aop:advisor advice-ref="txadvice" pointcut="execution(* com.service.impl.*.*(..))"/>
    aop:config>

效果如下
在网页中搜索http://localhost/save.jsp出现

SSM框架整合(超详细附带源码)_第6张图片
成功
SSM框架整合(超详细附带源码)_第7张图片
查找功能:
首先在userList.jsp中填写
注意:这里得写上 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>这句话否则下面的不能用

<body>
<h1>展示账户数据列表h1>
<table border="1px">
    <tr>
        <th>idth>
        <th>名字th>
        <th>年龄th>
    tr>
    <c:forEach items="${userList}" var="user">
        <tr>
        <td>${user.id}td>
        <td>${user.name}td>
        <td>${user.age}td>
        tr>
    c:forEach>
table>
body>

然后在UserController中填写

@RequestMapping("/findAll")
    public ModelAndView findAll(){
        List<User> userList = userService.findAll();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("userList",userList);
        modelAndView.setViewName("userList");
        return modelAndView;
    }

然后在UserServiceImpl中填写

 @Override
    public List<User> findAll() {
         return userDao.findAll();
    }

最后在UserMapper.xml中填写

   <select id="findAll" resultType="user">
        select * from user
    select>

效果如下:
网页搜索http://localhost/user/findAll
SSM框架整合(超详细附带源码)_第8张图片
源码百度云盘链接 链接:
https://pan.baidu.com/s/1Zu7TQ8Wt4D04ozWcNwc3NA
提取码:zjfm

好了,SSM整合成功!!

你可能感兴趣的:(#,SSM框架整合,java,spring,sql,tomcat)