SpringMVC(二)SpringMVC+MyBatis+Thymeleaf实例

版权声明:From Lay https://blog.csdn.net/Sadlay/article/details/84034171

SpringMVC实例

本文采用的环境是Spring Boot2+MyBatis+thymeleaf

数据库建表

CREATE TABLE `t_person` (
  `id` int(12) NOT NULL AUTO_INCREMENT,
  `person_name` varchar(60) NOT NULL,
  `note` varchar(256) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=utf8;

Maven依赖

<?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.lay</groupId>
    <artifactId>mvc</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>mvc</name>
    <description>Demo project for SpringMVC</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- dbcp2连接池 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
        </dependency>
        <!-- mabatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- thymeleaf依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!-- fastJson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastJson</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

application.properties配置文件

#数据库配置
spring.datasource.url=jdbc:mysql://192.168.3.253:3306/springboot_database?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456
# spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#指定数据连接池的类型
spring.datasource.type=org.apache.commons.dbcp2.BasicDataSource
#最大等待连接中的数量,设置0为没有限
spring.datasource.dbcp2.max-idle=10
#最大连接活动数
spring.datasource.dbcp2.max-total=50
#最大等待毫秒数,单位ms,超过时间会出错误信息
spring.datasource.dbcp2.max-wait-millis=10000
#数据库连接池初始化连接数
spring.datasource.dbcp2.initial-size=5
#设置默认的隔离级别为读写提交
spring.datasource.dbcp2.default-transaction-isolation=2
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.html

# mybatis配置
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package: com.lay.mvc.entity
#驼峰命名转换
mybatis.configuration.mapUnderscoreToCamelCase=true

#sql日志
logging.level.com.lay.mvc.dao=trace

实体Entity

package com.lay.mvc.entity;

import com.lay.mvc.enumeration.SexEnum;
import org.apache.ibatis.type.Alias;

/**
 * @Description:
 * @Author: lay
 * @Date: Created in 0:33 2018/11/11
 * @Modified By:IntelliJ IDEA
 */
@Alias("person")
public class Person {


    private static final long serialVersionUID = 3172000990909338544L;

    private Long id = null;

    private String personName = null;

    private String note = null;

    public Long getId() {
        return id;
    }

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

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }

    public String getPersonName() {
        return personName;
    }

    public void setPersonName(String personName) {
        this.personName = personName;
    }

    public static long getSerialversionuid() {
        return serialVersionUID;
    }


}

数据访问层DAO

package com.lay.mvc.dao;

import com.lay.mvc.entity.Person;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @Description:
 * @Author: lay
 * @Date: Created in 0:35 2018/11/11
 * @Modified By:IntelliJ IDEA
 */
@Mapper
@Repository
public interface PersonDao {

    //获取单个用户
    public Person getPerson(Long id);

    //新增用户
    public int insertPerson(Person person);

    //更新用户
    public int updatePerson(Person person);

    //获取全部用户
    public List<Person> getAllPersons();

    //查询用户
    public List<Person> findPersons(@Param("personName") String personName, @Param("note") String note);

    //删除用户
    public int deletePerson(Long id);

}

MyBatis Mappper映射文件

路径为/resources/mapper/personMapper.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.lay.mvc.dao.PersonDao">
    <select id="getPerson" parameterType="long" resultType="person">
		select id,person_name,note from t_person where id=#{id}
	</select>
    <insert id="insertPerson" useGeneratedKeys="true" keyProperty="id" >
		insert into t_person(person_name,note) values(#{personName},#{note})
	</insert>
    <update id="updatePerson">
        update t_person
        <set>
            <if test="personName!=null">person_name=#{personName},</if>
            <if test="note!=null">note=#{note}</if>
        </set>
        where id=#{id}
    </update>
    <select id="getAllPersons" resultType="person">
		select id,person_name,note from t_person
	</select>
    <select id="findPersons" resultType="person">
        select id,person_name,note from t_person
        <where>
            <if test="personName!=null">
                and person_name=#{personName}
            </if>
            <if test="note!=null">
                and note=#{note}
            </if>
        </where>
    </select>
    <delete id="deletePerson" parameterType="long">
		delete from t_person where id=#{id}
	</delete>
</mapper>

服务层Service

package com.lay.mvc.service;

import com.lay.mvc.entity.Person;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * @Description:
 * @Author: lay
 * @Date: Created in 0:39 2018/11/11
 * @Modified By:IntelliJ IDEA
 */
public interface PersonService {

    //获取单个用户
    public Person getPerson(Long id);

    //新增用户
    public Person insertPerson(Person person);

    //更新用户名
    public Person updatePerson(Long id, String personName);

    //获取全部用户
    public List<Person> getAllPersons();

    //查询用户
    public List<Person> findPersons(String personName,String note);

    //删除用户
    public int deletePerson(Long id);


}

服务层实现类ServiceImpl

package com.lay.mvc.service.impl;

import com.lay.mvc.dao.PersonDao;
import com.lay.mvc.entity.Person;
import com.lay.mvc.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description:
 * @Author: lay
 * @Date: Created in 0:40 2018/11/11
 * @Modified By:IntelliJ IDEA
 */
@Service
public class PersonServiceImpl implements PersonService {


    @Autowired
    PersonDao personDao ;

    @Override
    @Transactional
    public Person getPerson(Long id) {
        return personDao.getPerson(id);
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, timeout = 1, propagation = Propagation.REQUIRES_NEW)
    public Person insertPerson(Person person) {
        personDao.insertPerson(person);
        return person;
    }

    @Override
    @Transactional
    public Person updatePerson(Long id, String personName) {
        Person person = this.getPerson(id);
        if (person == null) {
            return null;
        }
        person.setPersonName(personName);
        personDao.updatePerson(person);
        return person;
    }

    @Override
    public List<Person> getAllPersons() {

        return personDao.getAllPersons();
    }

    @Override
    public List<Person> findPersons(String personName, String note) {
        return personDao.findPersons(personName,note);
    }

    @Override
    @Transactional
    public int deletePerson(Long id) {
        return personDao.deletePerson(id);
    }

}

控制器Controller

package com.lay.mvc.controller;

import com.lay.mvc.entity.Person;
import com.lay.mvc.enumeration.SexEnum;
import com.lay.mvc.service.PersonService;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Description:
 * @Author: lay
 * @Date: Created in 0:25 2018/11/11
 * @Modified By:IntelliJ IDEA
 */
@RequestMapping(value = "/person")
@Controller
public class PersonController {

    //注入用户服务类
    @Autowired
    PersonService personService;

    //获取人员列表
    @RequestMapping("/table")
    public ModelAndView table() {
        List<Person> personList = personService.getAllPersons();
        ModelAndView mv = new ModelAndView();
        mv.setViewName("person/table");
        mv.addObject("personList", personList);
        return mv;
    }

    @RequestMapping("/list")
    @ResponseBody
    public List<Person> list(
            @RequestParam(value = "personName", required = false) String personName,
            @RequestParam(value = "note", required = false) String note) {
        List<Person> personList = personService.findPersons(personName, note);
        return personList;
    }

}

启动类

配置Mapper扫描

package com.lay.mvc;

import org.apache.ibatis.annotations.Mapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication
@MapperScan(basePackages = "com.lay.mvc.dao", annotationClass = Mapper.class)
public class MvcApplication {

    public static void main(String[] args) {
        SpringApplication.run(MvcApplication.class, args);
    }

}

视图页面

目录:/resources/templates/person/table

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <meta charset="UTF-8">
    <title>用户列表</title>
    <link rel="stylesheet" type="text/css" href="https://www.jeasyui.com/easyui/themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="https://www.jeasyui.com/easyui/themes/icon.css">
    <link rel="stylesheet" type="text/css" href="https://www.jeasyui.com/easyui/themes/color.css">
    <link rel="stylesheet" type="text/css" href="https://www.jeasyui.com/easyui/demo/demo.css">
    <script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="https://www.jeasyui.com/easyui/jquery.easyui.min.js"></script>
    <script type="text/javascript">
        function onSearch() {
            //指定请求路径
            var opts=$("#dg").datagrid("options");
            opts.url="./list";
            //获取查询参数
            var personName=$("#personName").val();
            var note=$("#note").val();
            //组织参数
            var params={};
            if(personName!=null&&personName.trim()!=""){
                params.personName=personName;
            }
            if(note!=null&&note.trim()!=""){
                params.note=note;
            }
            //重新载入表格数据
            $("#dg").datagrid("load",params);
        }
    </script>
</head>
<body>
    <div style="margin: 20px 0;"></div>
    <div class="easyui-layout" style="width: 100%;height: 350px">
        <div data-options="region:'north'" style="height: 50px">
            <form id="searchForm" method="post">
                <table>
                    <tr>
                        <td>用户名称:</td>
                        <td><input id="personName" name="personName" class="easyui-textbox" data-options="prompt:'请输入用户名'" style="width: 100%;height: 32px"></td>
                        <td>备注:</td>
                        <td><input id="note" name="note" class="easyui-textbox" data-options="prompt:'请输入备注'" style="width: 100%;height: 32px"></td>
                        <td><a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-search'" style="width: 80px" onclick="onSearch()">查询</a> </td>
                    </tr>
                </table>
            </form>
        </div>
        <div data-options="region:'center',title:'用户列表',iconCls:'icon-ok'">
            <table id="dg" class="easyui-datagrid" data-options="border:false,singleSelect:true,fit:true,fitColumns:true">
                <thead>
                    <tr>
                        <th data-options="field:'id'" width="80">编号</th>
                        <th data-options="field:'personName'" width="100">用户名称</th>
                        <th data-options="field:'note'" width="80">备注</th>
                    </tr>
                </thead>
                <tbody>
                    <!--使用forEach渲染数据模型-->
                    <tr th:each="person:${personList}">
                        <td th:text="${person.id}"></td>
                        <td th:text="${person.personName}"></td>
                        <td th:text="${person.note}"></td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</body>
</html>

测试

打开浏览器输入http://localhost:8080/person/table

猜你喜欢

转载自blog.csdn.net/Sadlay/article/details/84034171