Spring+SpringMVC+MyBatis整合代码

整体文件

在这里插入图片描述

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_3_1.xsd"
         version="3.1">
    <!--加载ApplicationContext.xml-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:ApplicationContext.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!--加载spring-mvc.xml-->
    <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>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <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>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

ApplicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
       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 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--加载perperties配置文件的信息-->
    <context:property-placeholder location="classpath:*.properties"/>

    <!--加载druid资源-->
    <bean id="dataSource" 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>

    <!--spring整合mybatis后控制的创建连接用的对象-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="typeAliasesPackage" value="com.myclod.domain"/>
        <!-- 配置分页-->
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <props>
                            <prop key="helperDialect">mysql</prop>
                            <prop key="reasonable">true</prop>
                        </props>
                    </property>
                </bean>
            </array>
        </property>
    </bean>

    <!--加载mybatis映射配置的扫描,将其作为spring的bean进行管理-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.myclod.dao"/>
    </bean>
<!--事务管理器-->
    <bean id="transactionManager1" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager1"/>
</beans>

spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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="com.myclod">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <mvc:annotation-driven/>
    <!--静态资源加载-->
    <mvc:default-servlet-handler/>

    <!--自定义消息转换器的编码,解决后台传输json回前台时,中文乱码问题-->
    <mvc:annotation-driven >
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter" >
                <property name = "supportedMediaTypes">
                    <list>
                        <value>application/json;charset=utf-8</value>
                        <value>text/html;charset=utf-8</value>
                        <!-- application 可以在任意 form 表单里面 enctype 属性默认找到 -->
                        <value>application/x-www-form-urlencoded</value>
                    </list>
                </property>
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" ></bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

</beans>

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.23.32:3306/SSM?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
#useSSL=true
#useUnicode=true&characterEncoding=utf-8

controller下的StudentController.java

package com.myclod.controller;

import com.github.pagehelper.PageInfo;
import com.myclod.domain.GeneralResylt;
import com.myclod.domain.Student;
import com.myclod.service.StudentDaoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;

@Controller
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentDaoService studentDaoService;

    @RequestMapping("save")
    @ResponseBody
    public GeneralResylt save(@RequestBody Student student){
        GeneralResylt resylt = new GeneralResylt();
        int i = studentDaoService.save(student);
        if (i>0){
            resylt.setFlag(true);
            resylt.setMsg("添加成功");
            return resylt;
        }else {
            resylt.setFlag(false);
            resylt.setMsg("添加失败");
            resylt.setCode(1048);
            return resylt;
        }
    }

    @RequestMapping("delete")
    @ResponseBody
    public GeneralResylt delete(@RequestBody Student student){
        GeneralResylt resylt = new GeneralResylt();
        int i = studentDaoService.deleteById(student);
        if (i>0){
            resylt.setFlag(true);
            resylt.setMsg("删除成功");
            return resylt;
        }else {
            resylt.setFlag(false);
            resylt.setMsg("删除失败");
            resylt.setCode(1050);
            return resylt;
        }
    }

    @RequestMapping("update")
    @ResponseBody
    public GeneralResylt update(@RequestBody Student student){
        GeneralResylt resylt = new GeneralResylt();
        int i = studentDaoService.update(student);
        if (i>0){
            resylt.setFlag(true);
            resylt.setMsg("修改成功");
            return resylt;
        }else {
            resylt.setFlag(false);
            resylt.setMsg("修改失败");
            resylt.setCode(1052);
            return resylt;
        }
    }

    @RequestMapping("findall")
    @ResponseBody
    public GeneralResylt findall(){
        GeneralResylt resylt = new GeneralResylt();
        List<Student> all = studentDaoService.findAll();
        resylt.setData(all);
        resylt.setFlag(true);
        resylt.setMsg("查询全部成功");
        return resylt;
    }

    @RequestMapping("findbyid")
    @ResponseBody
    public GeneralResylt findbyid(@RequestBody Student student){
        GeneralResylt resylt = new GeneralResylt();
        Student all = studentDaoService.findById(student);
        resylt.setData(all);
        resylt.setFlag(true);
        resylt.setMsg("查询单个成功");
        return resylt;
    }

    @RequestMapping("findpage")
    @ResponseBody
    public GeneralResylt findpage(int i,int j){
        GeneralResylt resylt = new GeneralResylt();
        PageInfo findpage = studentDaoService.findpage(i, j);
        resylt.setFlag(true);
        resylt.setMsg("分页查询成功");
        resylt.setData(findpage);
        return resylt;
    }
}

service下的StudentDaoService.java

package com.myclod.service;

import com.github.pagehelper.PageInfo;
import com.myclod.domain.Student;

import java.util.List;

public interface StudentDaoService {

    public int save(Student student);

    int deleteById(Student student);

    int update(Student student);

    public List<Student> findAll();

    Student findById(Student student);

    public PageInfo findpage(int i , int j);
}

service的实现类StudentDaoServiceImpl.java

package com.myclod.service.imp;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.myclod.dao.StudentDao;
import com.myclod.domain.Student;
import com.myclod.service.StudentDaoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentDaoServiceImpl implements StudentDaoService {

    @Autowired
    private StudentDao studentDao;


    @Override
    public int save(Student student) {
        int i = studentDao.save(student);
        return i;
    }

    @Override
    public int deleteById(Student student) {
        System.out.println(student.getId());
        return studentDao.deleteById(student);
    }

    @Override
    public int update(Student student) {
        return studentDao.update(student);
    }

    @Override
    public List<Student> findAll() {
        return studentDao.findAll();
    }

    @Override
    public Student findById(Student student) {
        System.out.println(student.getId());
        return studentDao.findById(student);
    }

    @Override
    public PageInfo findpage(int i, int j) {
        PageHelper.startPage(i,j);
        List<Student> all = studentDao.findAll();
        PageInfo pageInfo = new PageInfo(all);
        return pageInfo;
    }


}

service层调用dao层StudentDao.java

package com.myclod.dao;

import com.myclod.domain.Student;

import java.util.List;

public interface StudentDao {
     int save(Student student);

     int deleteById(Student student);

     int update(Student student);

     List<Student> findAll();

     Student findById(Student student);
}

dao层映射到resources包中对应的StudentDao.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="com.myclod.dao.StudentDao">

    <insert id="save" parameterType="com.myclod.domain.Student" >
        insert into student(name,age) values(#{name},#{age})
    </insert>

    <delete id="deleteById" parameterType="com.myclod.domain.Student">
        delete from student where id = #{id}
    </delete>
    <update id="update" parameterType="com.myclod.domain.Student">
        update student set name = #{name}, age=#{age} where id = #{id}
    </update>

    <select id="findAll" resultType="com.myclod.domain.Student">
        select * from student
    </select>
    <select id="findById" resultType="com.myclod.domain.Student" parameterType="com.myclod.domain.Student">
        select * from student where id = #{id}
    </select>

</mapper>

domain中的实体类GeneralResylt.java

package com.myclod.domain;

public class GeneralResylt<T> {
    private T data;
    private Boolean flag;
    private String msg;
    private Integer code;

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public Boolean getFlag() {
        return flag;
    }

    public void setFlag(Boolean flag) {
        this.flag = flag;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }
}

domain实体类Student.java

package com.myclod.domain;

public class Student {
    private Integer id;
    private String name;
    private Integer age;

    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 Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

异常处理包exception中的NormalException.java

package com.myclod.exception;

import com.myclod.domain.GeneralResylt;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Component
@ControllerAdvice
public class NormalException {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public GeneralResylt handleException(){
        GeneralResylt generalResylt = new GeneralResylt();
        generalResylt.setMsg("操作失败");
        generalResylt.setFlag(false);
        generalResylt.setCode(1048);
        return generalResylt;
    }
}

maven的配置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>com.myclod</groupId>
  <artifactId>SSM-Demo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>SSM-Demo 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.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.3</version>
    </dependency>
    <!--mysql环境-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.47</version>
    </dependency>
    <!--spring整合jdbc-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.1.9.RELEASE</version>
    </dependency>
    <!--spring整合mybatis-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.3</version>
    </dependency>
    <!--druid连接池-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.16</version>
    </dependency>
    <!--分页插件坐标-->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.1.2</version>
    </dependency>
    <!--springmvc环境-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.1.9.RELEASE</version>
    </dependency>
    <!--jackson相关坐标3个-->
    <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-core</artifactId>
        <version>2.9.0</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.9.0</version>
    </dependency>-->
    <!--servlet环境-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>

    <!--junit单元测试-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>
    <!--spring整合junit-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>5.1.9.RELEASE</version>
    </dependency>
  </dependencies>

  <build>
    <!--设置插件-->
    <plugins>
      <!--具体的插件配置-->
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.1</version>
        <configuration>
          <port>80</port>
          <path>/</path>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值