JAVA--Mybatis-Spring-SpringMVC框架整合

我的未来我决定 提交于 2020-01-07 22:40:23

------Mybatis-Spring-SpringMVC框架整合示例-----

mybatis SQL映射文件

<?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="com.bdit.dao.IUserDao">
     <!--查询所有的操作-->
    <select id="findAll" resultType="com.bdit.model.User">
        select * from user
    </select>

    <!--根据id去查询-->
    <select id="findByid" resultType="com.bdit.model.User" parameterType="int">
        select  *  from user where id=#{id}
    </select>

    <!--保存信息-->
    <insert id="insert" parameterType="com.bdit.model.User">
        insert  into user(userName,gender,address)values(#{userName},#{gender},#{address})
    </insert>

    <!--修改信息-->
    <update id="update" parameterType="com.bdit.model.User">
        update user set userName=#{userName},gender=#{gender},address=#{address} where id=#{id}
    </update>

    <!--删除信息:根据用户的id去删除-->
    <delete id="delete" parameterType="com.bdit.model.User">
        delete  from user where id=#{id}
    </delete>

<!--    &lt;!&ndash;模糊查询&ndash;&gt;-->
<!--   <select id="findName" parameterType="java.lang.String" resultType="com.model.User">-->
<!--       select * from user  where username like '%${value}%'-->
<!--   </select>-->

<!--    &lt;!&ndash;使用聚合函数查询表中的总记录数&ndash;&gt;-->
<!--    <select id="totalcont"  resultType="java.lang.Integer">-->
<!--        select  count(id) from user-->
<!--    </select>-->

<!--    <select id="finaAlll" resultMap="Map">-->
<!--        select  *  from  user-->
<!--    </select>-->
<!--    <resultMap id="Map" type="com.model.VOUser">-->
<!--    <id column="id"  property="stuId"/>-->
<!--    <result column="username" property="username"/>-->
<!--    <result column="age" property="stuage"/>-->
<!--    <result column="address" property="stuaddress"/>-->
<!--    </resultMap>-->
</mapper>

Mybatis配置文件

<?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>

    <typeAliases>
        <!--        <typeAlias type="User" alias="User"/>-->
        <!--如果有多个,则批量定义,扫描整个包下的类,别名为类名,(首字母大小写都可以)-->
        <package name="com.bdit.model"/>
    </typeAliases>


    <!--配置Mybatis的环境-->
    <environments default="mysql">
        <!--配置mysql的环境-->
        <environment id="mysql">
            <!--配置事物的类型-->
            <transactionManager type="JDBC"/>
            <!--配置连接数据库的信息,用的数据源是(连接池)-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/ab_wzy?serverTimezone=GMT"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <!--告知mybatis映射文件的位置-->
    <!--SQL映射文件mybatis是不认识的,所有需要告知-->
    <mappers>
        <mapper resource="com/bdit/dao/IUserDao.xml"/>
        <!--基于注解的方式-->
        <!--<mapper class="com.bdit.dao.IUserDao"/>-->

        <!--注册指定包下的所有 mapper接口:也就是所谓的DAO接口-->
        <!--       <package name="com.bdit.dao"/>-->
    </mappers>
</configuration>

Spring【配置文件】

<?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:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       https://www.springframework.org/schema/beans/spring-beans.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
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
">
    <!--引入外部属性文件-->
    <context:property-placeholder location="classpath:ab.properties"></context:property-placeholder>
    <!--自动扫描指定的包-->
    <context:component-scan base-package="com.bdit">
        <!--Spring就不在扫描@Contrellor的类-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!--开启注解事务的支持-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>

    <!--阿里的数据源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${driverClassName}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${user}"/>
        <property name="password" value="${password}"/>
    </bean>

    <!--配置mybatis的Session工场-->
    <bean id="sessionFactoryBean"   class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"/>
        <!--加载 mybatis 的配置文件 SqlMapConfig.xml-->
        <property name="configLocation" value="classpath:SqlMapConfig.xml "/>
    </bean>

    <!--配置自动扫描所有的 Mapper 接口和文件-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.bdit.dao"/>
    </bean>


    <!--配置Spring的事物管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--事务通知的配置和事务管理器对象的引用-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--<tx:attributes>用来配置事务的属性标签-->
        <tx:attributes>
            <!--<tx:method>用来指定方法的名称-->
            <tx:method name="findAll*" read-only="true" isolation="REPEATABLE_READ" propagation="SUPPORTS"/>
            <tx:method name="findByid*" read-only="true" isolation="REPEATABLE_READ" propagation="SUPPORTS"/>
            <tx:method name="insert*"  read-only="false" isolation="REPEATABLE_READ" propagation="REQUIRED"/>
            <tx:method name="update*" read-only="false"  isolation="REPEATABLE_READ" propagation="REQUIRED"/>
            <tx:method name="delete*" read-only="false"  isolation="REPEATABLE_READ" propagation="REQUIRED"/>
            <!--如果这样配置的话针对整个Dao接口的实现类都有效,我们一般分来配置-->
            <tx:method name="*" read-only="false" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    <!-- 配置AOP切面-->
    <aop:config>
        <!-- 配置AOP切入点-->
        <aop:pointcut id="txPointcut" expression="execution(* com.bdit.Service.impl.*.*(..))"/>
        <!--配置事务的通知和切入点的关联关系-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    </aop:config>


</beans>

SpringMVC【配置文件】

<?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"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
      https://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd
      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
    <!--配置 springmvc 要扫描的包-->
    <context:component-scan base-package="com.bdit">
        <!--指定扫描包的规则,SpringMVC只扫描包含@Controller的类-->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!--自动加载处理器映射器、处理器适配器-->
    <!--引用自定义的类型转换器-->
    <mvc:annotation-driven>

    </mvc:annotation-driven>

    <!--配置视图解析器-->
    <bean  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--视图所在的位置,也就是前缀-->
        <property name="prefix" value="/WEB-INF/pags/"/>
        <!--所使用视图技术的后缀名-->
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--在 springmvc 中设置,静态资源不要过滤
     location 表示路径,mapping 表示文件或过滤规则,**表示该目录下的文件以及子文件夹-->
    <mvc:resources mapping="/css/**" location="/css/"/>
    <mvc:resources mapping="/js/**" location="/js/"/>
    <mvc:resources mapping="/images/**" location="/images/"/>
</beans>

Web.xml的配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
  <!--啥时候加载Spring的配置文件-->
  <!--手动指定Spring的配置文件-->
  <!--相当于配置了一个上下文的初始化参数-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:Spring.xml</param-value>
  </context-param>
  <!--配置Spring提供的监听器,用于启动服务时加载Spirng的配置文件,
  该监听器只能加载/WEB-INF/目录中名称为applicationContext.xml中的文件-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!--配置 Spring mvc 框架的编码过滤器-->
  <filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <!--设置过滤器的属性值-->
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <!--启动过滤器-->
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <!--配置过滤器的映射路径-->
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <!--HiddentHttpMethodFilter过滤器来实现RESTFul 风格-->
  <filter>
    <filter-name>hiddenHttpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>hiddenHttpMethodFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <!--配置 spring mvc 的核心控制器-->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--配置初始化参数,用于读取 springmvc 的配置文件-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:SpringMVC.xml</param-value>
    </init-param>
    <!--配置 servlet 实例创建的节点,应用加载时就创建-->
    <load-on-startup>0</load-on-startup>
  </servlet>
  <!--配置映射的路径-->
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

ab.properties属性文件

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/ab_wzy?serverTimezone=GMT
user=root
password=root

准备实体类

package com.bdit.model;

import java.io.Serializable;

public class User implements Serializable {
    private static final long serialVersionUID = 5841583645389273544L;
    private Integer id;
    private String userName;
    private String gender;
    private String address;
    public User(){

    }

    public static long getSerialVersionUID() {
        return serialVersionUID;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", gender='" + gender + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

准备实体类

package com.bdit.model;

import java.io.Serializable;

public class User implements Serializable {
    private static final long serialVersionUID = 5841583645389273544L;
    private Integer id;
    private String userName;
    private String gender;
    private String address;
    public User(){

    }

    public static long getSerialVersionUID() {
        return serialVersionUID;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", gender='" + gender + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

准备持久层DAO

import java.util.List;

//编写持久层Dao接口
public interface IUserDao {

    //查询所有的信息
    public List<User> findAll();
    //根据id去查询
    public User findByid(Integer id);
    //添加的方法
    public int insert(User  user);
    //更新的方法
    public int update(User  user);
    //删除的方法
    public int delete(Integer id);
}

准备业务层接口和业务层的实现类

package com.bdit.Service;

import com.bdit.model.User;

import java.util.List;

//编写业务层接口
public interface IUserServiceDao{
    //查询所有的信息
    public List<User> findAll();
    //根据id去查询
    public User findByid(Integer id);
    //添加的方法
    public int insert(User  user);
    //更新的方法
    public int update(User  user);
    //删除的方法
    public int delete(Integer id);
}
实现类
package com.bdit.Service.impl;

import com.bdit.Service.IUserServiceDao;
import com.bdit.dao.IUserDao;
import com.bdit.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class UserServiceimpl implements IUserServiceDao {

    @Autowired
    private IUserDao  userDao;

    public void setUserDao(IUserDao userDao) {
        this.userDao = userDao;
    }

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

    @Override
    public User findByid(Integer id) {
        return userDao.findByid(id);
    }

    @Override
    public int insert(User user) {
        return  userDao.insert(user);
    }

    @Override
    public int update(User user) {
        return  userDao.update(user);
    }

    @Override
    public int delete(Integer id) {
        return  userDao.delete(id);
    }
}

准备控制器Controller

import com.bdit.Service.impl.UserServiceimpl;
import com.bdit.model.User;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

//用户控制器
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserServiceimpl userService;

    @RequestMapping("/list")  //查询用户信息的方法
    public ModelAndView  user(){
        ModelAndView  mav=new ModelAndView();
        List<User>list=userService.findAll();
        //指定响应的客户端
        mav.addObject("list",list);
        //指定要跳转的逻辑视图
        mav.setViewName("list");
        return mav;
    }
    //添加用户信息的方法

    @RequestMapping("/insert")
    public String insert(User  user){
        int i=userService.insert(user);
         if(i>0){
             return "forward:/WEB-INF/pags/success.jsp";
         }else{
             return "error";
         }
    }

    //编辑用户的信息
    @RequestMapping("/edit/{id}")
    public ModelAndView edit(@PathVariable("id")Integer  id){
        ModelAndView  Mav=new ModelAndView();
        User  user=userService.findByid(id);
        //指定响应的客户端
        Mav.addObject("user",user);
        Mav.setViewName("edit");
        return Mav;
    }

    //用户信息的修改页面
    @RequestMapping("/update")
    public String update(User  user){
       int  i=userService.update(user);
       if(i>0){
           return "redirect:/user/list";
       }else{
           return  "error";
       }
    }
    //用户信息的修改页面
    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable("id")Integer id){
        int  i=userService.delete(id);
        if(i>0){
            return "redirect:/user/list";
        }else{
            return  "error";
        }
    }
}

准备前端页面

用户信息的添加页面

<%@page contentType="text/html; charset=utf-8" language="java" %>
<html>
<body>
<h2>Hello World 恭喜你SSM配置成功!</h2>

<a href="user/list" style="color:green">查询用户的信息</a>

<form action="user/insert" method="post">
    用户名:<input type="text" name="userName"><br>
    性别:<input type="radio" name="gender" value="男">男
    <input type="radio" name="gender" value="女">女<br>
    住址:<input type="text" name="address"><br>
    <input type="submit" value="提交">
</form>

</body>
</html>

用户信息的展示页面

<%--
  Created by IntelliJ IDEA.
  User: Lenovo-T410
  Date: 2020/1/7
  Time: 18:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>用户信息的查询页面</title>
</head>
<body>
<h2 style="color: green"align="center">用户信息的展示页面</h2>
<table width="100%" border="100%" style="background: blanchedalmond">
    <tr align="center">
        <th>用户ID</th>
        <th>用户名</th>
        <th>性别</th>
        <th>住址</th>
        <th>操作</th>
    </tr>
    <c:forEach items="${list}" var="user">
        <tr align="center">
            <td>
               ${user.id}
            </td>
            <td>
                ${user.userName}
            </td>
            <td>
                ${user.gender}
            </td>
            <td>
                ${user.address}
            </td>
            <td>
                <a href="${pageContext.request.contextPath}/user/edit/${user.id}">编辑</a>
                <a href="${pageContext.request.contextPath}/user/delete/${user.id}">删除</a>
            </td>
        </tr>
    </c:forEach>
</table>
</body>
</html>

用户的编辑页面

<%--
  Created by IntelliJ IDEA.
  User: Lenovo-T410
  Date: 2020/1/7
  Time: 20:01
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>用户信息的编辑页面</title>
</head>
<body>
<h2>用户信息的编辑页面</h2>

<form action="${pageContext.request.contextPath}/user/update" method="post">
    用户名:<input type="text" name="userName" value=${user.userName}><br>
    性别:
  <c:if test="${user.gender=='男'}">
      <input type="radio" name="gender" value="男" checked>男
      <input type="radio" name="gender" value="女">女<br>
  </c:if>
  <c:if test="${user.gender=='女'}">
      <input type="radio" name="gender" value="男" checked >男
      <input type="radio" name="gender" value="女"  checked >女<br>
  </c:if>

    住址:<input type="text" name="address" value="${user.address}"><br>
    <input type="submit" value="修改">
    <input type="hidden" name="id" value="${user.id}">
</form>

</body>
</html>来源:站长平台
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!