Spring集成Mybatis
一、创建基本的Maven Web项目
0、pom.xml引入依赖: 打成war包
<?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>cn.linst</groupId>
<artifactId>learnmybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<name>learnmybatis</name>
<packaging>war</packaging>
<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>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- mybatis 依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.12</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.12</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
</dependencies>
<build>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
<!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!--<dependency>-->
<!--<groupId>cn.linst</groupId>-->
<!--<artifactId>learnmybatis</artifactId>-->
<!--</dependency>-->
</dependencies>
</plugin>
</plugins>
</build>
</project>
1、在src/main/web-app/WEB-INF/目录下 创建一个web.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
</web-app>
2、添加web相关依赖
<!-- web -->
<!-- 支持servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- jsp-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<!-- jstl-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
通常 Web容器都会自带 servlet-api和 jsp-api 的jar 包,为了避免 jar 包重复引起错误,需要将 servlet-api和jsp-api 的scope 配置为 provided。配置为 provided 时的jar 包在项目打包时,不会将依赖的 jar包打包到项目中, 项目运行时这些 jar 包需要由容器提供,这样就避免了重复 jar 包引起的错误。
3、添加一个jsp页面
在web-app目录下新建一个index.jsp页面,如:
index.jsp:
<%@ page import="java.util.Date" %>
<%@ page language="java" contentType="text/html;charset=UTF8" pageEncoding="UTF8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transit onal//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF8" >
<title>Index</title>
</head>
<p>
Hello Web!
</p>
<p>
<%
Date now= new Date();
%>
服务器时间: <fmt:formatDate value="<%=now%>" pattern="yyyy-MM-dd HH:mm:ss"/>
</p>
<body>
4、配置Tomcat
5、启动运行
访问http://localhost:8080/
即可页面。如:
二、集成Spring 和Spring MVC
1、pom.xml加入以下依赖:
<dependencyManagement>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-framework-bom -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>4.3.4.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
由于 Spring 要添加很多spring 组件的依赖, 为了在使用Spring不需要再配置每个依赖的版本号。使用spring-framework-bom,它是Spring 的一个项目清单文件。Spring 组件的版本由spring-framework-born 统一管理。
2、添加Spring 依赖
<dependencies>
<!--Spring 上下文, 核心依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<!-- spring jdbc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<!-- spring面向切面-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<!-- spring aop 依赖-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.2</version>
</dependency>
</dependencies>
3、添加springmvc依赖
<!-- spring mvc依赖 -->
<!-- spring web核心-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<!--spring mvc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<!--spring mvc-json依赖-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.7</version>
</dependency>
4、添加spring xml配置文件
applicationContext.xml:
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns="http://www.springframework.org/schema/beans"
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">
<context:component-scan base-package="cn.linst.services.impl" />
<bean id="dataSource" class="org.apache.ibatis.datasource.pooled.PooledDataSource">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/learnmybatis"/>
<property name="username" value="root"/>
<property name="password" value="QWERgood123"/>
</bean>
</beans>
5、添加springmvc的配置文件
mybatis-servlet.xml:
<?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
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">
<!--mvc:annotation-driven 启用 Controller 注解支持-->
<mvc:annotation-driven/>
<!--mvc:resources 配置了一个简单的静态资源映射规则。-->
<mvc:resources mapping="/static/**" location="static/"/>
<!--context:component-scan 扫描 controller 包下的类-->
<context:component-scan base-package="cn.linst.controller" />
<!--InternalResourceViewResolver 将视图名映射为 URL 文件-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp" />
</bean>
</beans>
web.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<!--这个配置用于在 Web 容器启动时根据 contextConfigLocation 配置的路径读取 Spring的配置文件,然后启动spring。-->
<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 ,需要增加如下配置-->
<servlet>
<servlet-name>mybatis</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:mybatis-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mybatis</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--编码过滤器配置-->
<filter>
<filter-name>SpringEncodingFilter</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>SpringEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
IndexController:
package cn.linst.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.Date;
@Controller
public class IndexController {
@RequestMapping(value = {"", "/index"})
public ModelAndView dicts() {
ModelAndView mv = new ModelAndView("index");
mv.addObject("now", new Date());
return mv;
}
}
index.jsp:
<%@ page import="java.util.Date" %>
<%@ page language="java" contentType="text/html;charset=UTF8" pageEncoding="UTF8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transit onal//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF8" >
<title>Index</title>
</head>
<p>
Hello Spring MVC!
</p>
<p>
<%
Date now= new Date();
%>
服务器时间: <fmt:formatDate value="<%=now%>" pattern="yyyy-MM-dd HH:mm:ss"/>
</p>
<body>
访问,http://localhost:8080/mybatis-spring/index
:
三、集成Mybatis
1、添加mybatis-spring依赖:
如:pom.xml:
<!--添加mybatis-spring-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
2、配置 SqlSessionFactoryBean
在Mybatis-Spring 中, SqlSessionFactoryBean 是用于 SqlSessionFactory 的。
在spring配置文件applicationContext.xml中配置这个工厂类。
如applicationContext.xml中sqlSessionFactory部分:
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns="http://www.springframework.org/schema/beans"
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">
<context:component-scan base-package="cn.linst.services.impl" />
<bean id="dataSource" class="org.apache.ibatis.datasource.pooled.PooledDataSource">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/learnmybatis"/>
<property name="username" value="root"/>
<property name="password" value="QWERgood123"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" >
<!--configLocation 用于配置 mybatis 配置 XML 路径-->
<property name="configLocation" value="classpath:mybatis-config.xml" />
<!--dataSource :用于配置数据源,该属性为必选项,-->
<property name="dataSource" ref="dataSource" />
<!--配置 SqlSessionFactoryBean 扫描 XML 映射文件的路径,-->
<!--
<property name="mapperLocations" >
<array>
<value >classpath:cn/linst/**/mapper/*.xml</value>
</array>
</property>
-->
<!--配置包中类的别名,包中的类在 XML 映射文件中使用时可以省略包名部分, 直接使用类名。-->
<property name="typeAliasesPackage" value="cn.linst.model" />
</bean>
</beans>
3、配置MapperScannerConfigurer
<!--配置 MapperScannerConfigurer-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" >
<!--用于配置基本的包路径。-->
<property name="basePackage" value="cn.linst.**.mapper" />
<!--annotationClass 用于过滤被扫描的接口,如果设置了该属性,那么mybatis 的接口只有包含该注解才会被扫描进去。-->
</bean>
四、demo
1、数据库表和实体model类创建
在原来数据表(RBAC的五张表,表结构可以参考Mybatis学习2)基础上加一张表,字典表
表结构:字典表及测试数据。
CREATE TABLE `sys_dict` (
`id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '主键',
`code` varchar(64) NOT NULL COMMENT '类别',
`name` varchar(64) NOT NULL COMMENT '字典名',
`value` varchar(64) NOT NULL COMMENT '字典值',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
INSERT INTO sys_dict VALUES ('1', '性别', '男','男');
INSERT INTO sys_dict VALUES ('2', '性别', '女', '女');
INSERT INTO sys_dict VALUES ('3', '季度' '第一季度', '1');
INSERT INTO sys_dict VALUES ('4', '季度', '第二季度', '2');
INSERT INTO sys_dict VALUES ('5', '季度', '第三季度', '3');
INSERT INTO sys_dict VALUES ('6', '季度', '第四季度', '4');
在src/main/java/下新建package cn.linst.model,再在目录下创建一个SysDict类。
SysDict:
package cn.linst.model;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
@Getter
@Setter
public class SysDict implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String code;
private String name;
private String value;
}
2、开发Mapper层(dao层)
Mapper 层也就是常说的数据访问层( dao 层)。使用 Mapper 接口和 XML 映射文件结合的方式进行开发。
DictMapper:
package cn.linst.mapper;
import cn.linst.model.SysDict;
import org.apache.ibatis.session.RowBounds;
import java.util.List;
public interface DictMapper {
SysDict selectByPrimaryKey(Long id);
/**
* 条件查询
*/
List<SysDict> selectBySysDict(SysDict sysDict , RowBounds rowBounds);
/**
* 新增
*/
int insert(SysDict sysDict);
/**
* 根据主键更新
* @param sysDict
* @return
*/
int updateById(SysDict sysDict);
/**
* 根据主键删除
*/
int deleteById(Long id);
}
DictMapper.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="cn.linst.mapper.DictMapper">
<!--在applicationContext配置SqlSessionFactoryBean时,
将 typeAliasesPackage 配置成了cn.linst.model,
所以这里设置 resultType 时可以 接使用类名,省略包名-->
<select id="selectByPrimaryKey" resultType="SysDict">
select id, code , name, `value` from sys_dict where id= #{id}
</select>
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
insert into sys_dict(code , name, `value`)
values ( #{code} , #{name}, #{value})
</insert>
<select id="selectBySysDict" resultType="cn.linst.model.SysDict">
select * from sys_dict
<where>
<if test="id != null" >
and = #{id}
</if>
<if test="code != null and code != ''" >
and code = #{code}
</if>
</where>
order by code, `value`
</select>
<delete id="deleteById">
delete from sys_dict where id=#{id}
</delete>
<update id="updateById">
update sys_dict
set code= #{code}, name= #{name} , value = #{value}
where id = #{id}
</update>
</mapper>
3、开发业务层(service)
DictService:
package cn.linst.services;
import cn.linst.model.SysDict;
import java.util.List;
public interface DictService {
SysDict findById(Long id);
List<SysDict> findBySysDict(SysDict sysDict,Integer offset, Integer limit);
// Service 层的 saveOrUpdate 方法对应 Mapper 中的 insert updateById 方法
boolean saveOrUpdate(SysDict sysDict);
boolean deleteById(Long id);
}
实现类DictServiceImpl:
package cn.linst.services.impl;
import cn.linst.mapper.DictMapper;
import cn.linst.model.SysDict;
import cn.linst.services.DictService;
import lombok.NonNull;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class DictServiceImpl implements DictService {
@Autowired
private DictMapper dictMapper;
@Override
public SysDict findById(@NonNull Long id) {
return dictMapper.selectByPrimaryKey(id);
}
@Override
public List<SysDict> findBySysDict(SysDict sysDict, Integer offset, Integer limit) {
RowBounds rowBounds = RowBounds.DEFAULT;
if (offset != null && limit != null) {
rowBounds = new RowBounds(offset, limit);
}
return dictMapper.selectBySysDict(sysDict, rowBounds);
}
@Override
public boolean saveOrUpdate(SysDict sysDict) {
if (sysDict.getId() == null) {
return dictMapper.insert(sysDict) == 1;
} else {
return dictMapper.updateById(sysDict) == 1;
}
}
@Override
public boolean deleteById(@NonNull Long id) {
return dictMapper.deleteById(id) == 1;
}
}
4、开发控制层(controller)
DictController:
package cn.linst.controller;
import cn.linst.model.SysDict;
import cn.linst.services.DictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
@Controller
@RequestMapping("/dicts")
public class DictController {
@Autowired
private DictService dictService;
/**
* 显示字典数据列表
* @param sysDict
* @param offset
* @param limit
* @return
*/
@RequestMapping
public ModelAndView dicts(SysDict sysDict, Integer offset, Integer limit) {
ModelAndView mv = new ModelAndView("dicts");
List<SysDict> dicts = dictService.findBySysDict(sysDict, offset, limit);
mv.addObject("dicts", dicts);
return mv;
}
/**
* 新增或修改字典信息,使用 get 跳转到页面
* @param id
* @return
*/
@RequestMapping(value = "add", method = RequestMethod. GET)
public ModelAndView add(Long id) {
ModelAndView mv = new ModelAndView("dict_add" );
SysDict sysDict;
if (id == null) {
//如果 id 不存在,就是新增数据,一个空对 即可
sysDict = new SysDict();
} else {
//如果 id 存在,就是修改据,把原有的数据查询出来
sysDict = dictService.findById(id);
}
mv.addObject("model", sysDict);
return mv;
}
/**
* 新增或修改字典信息,通过表单 post 提交数据
* @param sysDict
* @return
*/
@RequestMapping(value = "add", method=RequestMethod . POST )
public ModelAndView save(SysDict sysDict ) {
ModelAndView mv = new ModelAndView();
try {
dictService.saveOrUpdate(sysDict);
mv.setViewName("redirect:/dicts");
} catch (Exception e) {
mv.setViewName("dict_add");
mv.addObject("msg", e.getMessage());
mv.addObject("model", sysDict);
}
return mv;
}
@RequestMapping(value ="delete", method= RequestMethod.POST)
@ResponseBody
public ModelMap delete(@RequestParam Long id) {
ModelMap modelMap = new ModelMap();
try {
boolean success = dictService.deleteById(id);
modelMap.put("success", success);
} catch (Exception e) {
modelMap.put("success", false);
modelMap.put("msg", e.getMessage());
}
return modelMap;
}
}
5、开发视图层(View)
在WEB-INF中创建jsp目录,然后在jsp创建dicts.jsp,dict_add.jsp。
dicts.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transit onal//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<c:set var="path" value="${pageContext.request.contextPath}" />
<meta http-equiv="Content-Type" content="text/html;charset=UTF8">
<title>字典信息 </title>
<script src="${path}/static/jquery-3.1.1.min.js"></script>
</head>
<body>
<table>
<tr>
<th colspan="4">字典管理</th>
</tr>
<tr>
<th>类别名</th>
<th>字典名</th>
<th>字典值</th>
<th>操作【<a href="${path}/dicts/add">新增</a>】</th>
</tr>
<c:forEach items="${dicts}" var="dict" >
<tr id=”dict-${dict.id}">
<td>${dict.code}</td>
<td>${dict.name}</td>
<td>${dict.value}</td>
<td>
【<a href="${path}/dicts/add?id=${dict.id}">编辑</a>】
【<a href="javascript:;"
onclick="deleteById(${dict.id}, '${dict.name}')">删除</a>】
</td>
</tr>
</c:forEach>
</table>
<script>
function deleteById(id, label) {
var r = confirm("确定要删除"+label+"吗?");
if (r) {
$.ajax({
url :'${path}/dicts/delete',
data: {
id: id
},
dataType: 'json',
type: 'POST',
success: function (data) {
console.log(data);
if (data.success) {
console.log($('#dict-' + id));
$('#dict-' + id).remove()
} else {
alert(data.msg);
}
}
})
}
}
</script>
</body>
</html>
dist_add,jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transit onal//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<c:set var="path" value="${pageContext.request.contextPath}" />
<meta http-equiv="Content-Type" content="text/html;charset=UTF8">
<title>字典信息 </title>
</head>
<body>
<form action="${path}/dicts/add" method="post">
<input type="hidden" name="id" value="${model.id}" >
<table>
<c:if test="${msg != null}">
<tr>
<th colspan= "2" style= "color:red;max-width:400px;">${msg}</th>
</tr>
</c:if>
<tr>
<th colspan="2">字典维护</th>
</tr>
<tr>
<th>类别名</th>
<td>
<input type="text" name="code" value="${model.code}">
</td>
</tr>
<tr>
<th>字典名</th>
<td>
<input type="text" name="name" value="${model.name}">
</td>
</tr>
<tr>
<th>字典值</th>
<td>
<input type="text" name="value" value="${model.value}">
</td>
</tr>
<tr>
<th colspan="2">
<input type="submit" value="保存">
<input type="button" onclick="backToList()" value="取消">
</th>
</table>
</form>
<script>
function backToList () {
location.href ='${path}/dicts';
}
</script>
</body>
</html>
运行应用:
访问地址:http://localhost:8080/mybatis-spring/dicts
可进行crud