前言:项目中使用到了jquery-1.8.3.js框架。
mysql数据库设计;
配置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>org.example</groupId>
<artifactId>spring-mybatis-mvc</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>spring-mybatis-mvc</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.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<spring.version>5.2.7.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
<!--spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring test-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!--springMvc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<!---->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<!--spring mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
</dependency>
<!--spring事务处理-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- JDBC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--alibaba 连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.74</version>
</dependency>
<!--utils-->
<dependency>
<groupId>org.example</groupId>
<artifactId>util</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!---->
</dependencies>
<build>
<finalName>spring-mybatis-mvc</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_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-war-plugin</artifactId>
<version>3.2.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>
</plugins>
</pluginManagement>
</build>
</project>
1、配置数据库连接属性:(spring.xml)
#mysql
mysql_name=数据库账户
mysql_pwd=数据库密码
mysql_url=jdbc:mysql://localhost:3306/数据库名称?characterEncoding=utf-8&serverTimezone=Asia/Shanghai
2、配置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>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/><!--(下划线转为驼峰命名法映射)-->
<setting name="logImpl" value="STDOUT_LOGGING"/><!--控制台输入执行日志-->
<!--<setting name="cacheEnableE" value="true"/>-->
</settings>
</configuration>
3、配置Spring.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"
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"
default-lazy-init="true">
<!-- 允许使用注解 -->
<context:annotation-config/>
<!-- 自动扫描 -->
<context:component-scan base-package="com.www.service"/>
<!--spring加载属性文件-->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:db.properties</value>
</list>
</property>
</bean>
<!-- 数据源 -->
<bean id="MySql" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="username" value="${mysql_name}"/>
<property name="password" value="${mysql_pwd}"/>
<property name="url" value="${mysql_url}"/>
</bean>
<!-- 配置事物 -->
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="MySql"/>
</bean>
<!-- mybatis -->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 本地配置文件 -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!-- 数据传输模板 -->
<property name="typeAliasesPackage" value="com.wxd.entity"/>
<!-- sql管理文件 -->
<property name="mapperLocations" value="classpath:mappers/*Mapper.xml"/>
<!-- 数据源-->
<property name="dataSource" ref="MySql"/>
</bean>
<!--sql文件与dao接口的映射-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.www.dao"/>
</bean>
</beans>
4、配置springmvc.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:p="http://www.springframework.org/schema/p"
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"
default-lazy-init="true">
<!--扫描Controller-->
<context:component-scan base-package="com.www.controller"/>
<!--配置springMvc数据请求与响应的格式-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="com.www.utils.HttpConverter">
<property name="supportedMediaTypes">
<value>text/html;charset=utf-8</value>
</property>
</bean>
</list>
</property>
</bean>
<!--配置页面跳转的前缀与后缀-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/views" p:suffix=".jsp"/>
</beans>
5 、配置实现对数据库进行增删改查操作的.xml文件(实现dao层内方法):
<?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.www.dao.TStudentDao">
<select id="find" resultType="TStudent" parameterType="TStudent">
select * from t_student where 1=1
<if test="id!=null">and id = ${id}</if>
</select>
<insert id="insert" parameterType="TStudent">
insert into t_student
(
name,student_no,sex,age,birthday,height,weight,address
)
values
(
#{name},#{studentNo},#{sex},${age},#{birthday},${height},${weight},#{address}
)
</insert>
<update id="update" parameterType="TStudent">
update t_student set
name=#{name},
student_no=#{studentNo},
sex=#{sex},age=${age},
birthday=#{birthday},
height=${height},
weight=${weight},
address=#{address}
where id=#{id}
</update>
<delete id="remove" parameterType="java.lang.Integer">
delete from t_student where id = ${id}
</delete>
</mapper>
6、配置好web.xml配置文件:
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!--配置spring-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>
<!--配置文件监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--配置springMvc-->
<servlet>
<servlet-name>springMvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMvc.xml</param-value>
</init-param>
<!--加载顺序 先加载SpringMvc,再加载spring-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 忽略静态文件 -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<!---->
</web-app>
7、编写好静态页面index.xml(以下是写好的):
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>信息</title>
<style>
.tb{
margin: 20 auto;
width: 85%;
height: auto;
border: none;
border-collapse: collapse;
}
.tb td{
line-height: 25px;
border: 1px solid #333;
padding: 10px;
text-align: center;
}
/*-----------*/
.tb1{
margin: 20 auto;
width: 85%;
height: auto;
border: none;
border-collapse: collapse;
}
.tb1 td{
line-height: 25px;
border: 1px solid #333;
padding: 10px;
}
</style>
<script src="/js/jquery-1.8.3.js" type="text/javascript"></script>
</head>
<body>
<script>
//刷新页面自动值执行该方法
$(function () {
getStudentData();
})
//整体页面展示
function getStudentData() {
$.ajax({
type:'post',
url:'/tsc/find',
dataType:'json',
success:function (result) {
$('.tr').remove();
$.each(result,function (i,st) {
var str = '<tr class="tr">'+
'<td width="120px">'+st.studentNo+'</td>'+
'<td width="100px">'+st.name+'</td>'+
'<td width="50px">'+st.age+'</td>'+
'<td width="50px">'+st.sex+'</td>'+
'<td width="150px">'+undefinedNull(st.birthday)+'</td>'+
'<td width="80px">'+st.height+'</td>'+
'<td width="80px">'+st.weight+'</td>'+
'<td width="200px">'+undefinedNull(st.address)+'</td>'+
'<td width="50px">' +
'<a href="#" onclick="editData('+st.id+',\''+st.name+'\')">编辑</a>'+
' | '+
'<a href="#" onclick="deleteData('+st.id+',\''+st.name+'\')">删除</a>'+
'</td>'+
'</tr>';
$('#tb').append(str);
})
}
})
}
//添加
function addStudent() {
$('#dialog').show();
}
//编辑
function editData(id,name) {
alert("id="+id+",name="+name);
$.ajax({
type:'get',
url:'/tsc/edit/'+id,
dataType:'json',
success:function (result) {
if (result){
$('#dialog').show();
$('#id').val(result.id);
$('#studentNo').val(result.studentNo);
$('#name').val(result.name);
$('#age').val(result.age);
$('#birthday').val(result.birthday);
$('#height').val(result.height);
$('#weight').val(result.weight);
$('#address').val(result.address);
}else {
alert('数据获取失败,请稍后再试!')
}
}
})
}
//删除
function deleteData(id,name) {
confirm("确定删除"+name+",该条记录吗??");
$.ajax({
type:'get',
url:'/tsc/delete/'+id,
dataType:'json',
success:function (result) {
alert(result.msg);
if (result.is){//如果删除成功,刷新数据
getStudentData();
}
}
})
}
//后台传值为空时。在页面设置为 " "
function undefinedNull(value) {
if (value==undefined){
return "";
}
return value;
}
function closeDialog() {
$('#dialog').hide();
$('#dataForm input[type="text"]').val('');//清空表单,重置
$('#dataForm input[type="date"]').val('');//清空表单,重置
$('#dataForm textarea').html('');//清空表单,重置
}
function saveDate() {
//获取表单数据
var f = $('#dataForm')
var data = f.serialize();
$.ajax({
type: 'post',
url: '/tsc/saveOrEdit',
data:data,
dataType: 'json',
success:function (result) {
alert(result.msg);
if (result.is){
closeDialog();
getStudentData();
}
}
})
}
</script>
<div style="margin: 10px 200px;">
<input type="button" value="新增" onclick="addStudent()">
</div>
<table class="tb" id="tb">
<tr style="background-color: #999">
<td width="120px">学号</td>
<td width="100px">名称</td>
<td width="50px">年龄</td>
<td width="50px">性别</td>
<td width="150px">出生日期</td>
<td width="80px">身高</td>
<td width="80px">体重</td>
<td width="200px">家庭住址</td>
<td width="110px">操作</td>
</tr>
</table>
<div id="dialog" style="display: none;z-index: 998;position: relative;">
<div style="z-index: 999;background-color: #fff;position: relative;background-color: aqua;
border: 1px solid #000;width: 700px;height: 600px;margin: 0 auto">
<%---------------------------------------------------------------------------------------------------------%>
<form id="dataForm">
<input type="hidden" name="id" id="id">
<table class="tb1">
<tr>
<td width="150px" align="right">学号:</td>
<td>
<input type="text" name="studentNo" id="studentNo">
</td>
</tr>
<tr>
<td width="150px" align="right">姓名:</td>
<td>
<input type="text" name="name" id="name">
</td>
</tr>
<tr>
<td width="150px" align="right">年龄:</td>
<td>
<input type="text" name="age" id="age">
</td>
</tr>
<tr>
<td width="150px" align="right">性别:</td>
<td>
<input type="radio" name="sex" value="1" checked>男
<input type="radio" name="sex" value="2">女
</td>
</tr>
<tr>
<td width="150px" align="right">出生日期:</td>
<td>
<input type="date" name="birthday" id="birthday">
</td>
</tr>
<tr>
<td width="150px" align="right">身高:</td>
<td>
<input type="text" name="height" id="height">
</td>
</tr>
<tr>
<td width="150px" align="right">体重:</td>
<td>
<input type="text" name="weight" id="weight">
</td>
</tr>
<tr>
<td width="150px" align="right">家庭地址:</td>
<td>
<textarea name="address" rows="10" cols="30" id="address"></textarea>
</td>
</tr>
<tr>
<td colspan="2">
<input type="button" value="确定保存" onclick="saveDate()">
<input type="button" value="取消关闭" onclick="closeDialog()">
</td>
</tr>
</table>
</form>
</div>
</div>
</body>
</html>
8、controller层:
package com.www.controller;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import java.text.SimpleDateFormat;
import java.util.Date;
public class BaseController {
@InitBinder
public void initBinder(ServletRequestDataBinder binder){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
/**
* 重新注册客户端编辑器
* 寻找与实体中Date.class属性名称和参数名称相同的数据,在通过sdf的方式进行转换为Date
*/
binder.registerCustomEditor(Date.class,new CustomDateEditor(sdf,true));
}
}
package com.www.controller;
import com.www.entity.TStudent;
import com.www.service.TStudentServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/tsc")
public class TStudentController extends BaseController{
@Resource(name = "TStudentServiceImpl")
private TStudentServiceImpl tssi;
@RequestMapping("/index")
public String index(){
return "/student/index";
}
/**
*
*/
@RequestMapping("/find")
@ResponseBody
public List<TStudent> find(TStudent ts) {
List<TStudent> list = tssi.find(ts);
return list;
}
/**
*
*/
@RequestMapping("/saveOrEdit")
@ResponseBody
public Map<String,Object> saveOrEdit(TStudent ts){
return tssi.saveOrEdit(ts);
}
/**
*
*/
@RequestMapping("/edit/{id}")
@ResponseBody
public TStudent edit(@PathVariable(value = "id") int id){
TStudent ts = tssi.get(id);
return ts;
}
/**
*
*/
@RequestMapping("/delete/{id}")
@ResponseBody
public Map<String,Object> delete(@PathVariable(value = "id") int id){
return tssi.delete(id);
}
}
9、dao层:
package com.www.dao;
import com.www.entity.TStudent;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface TStudentDao {
List<TStudent> find(TStudent ts);
int insert(TStudent ts);
int update(TStudent ts);
//不是对象传值 , 需@Param
int remove(@Param(value = "id") int id);
}
10、实体类(entity):
package com.www.entity;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
@Data
public class TStudent implements Serializable {
private static final long serialVersionUID = -3252363464563436L;
private Integer id;
private String name;
private String password;
private String sex;
@JSONField(format = "yyyy-MM-dd")
private Date birthday;
private Date createDate;
private String studentNo;
private String address;
private String status;
private Integer age;
private Integer weight;
private Integer height;
private Integer classId;
public static long getSerialVersionUID() {
return serialVersionUID;
}
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 String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public String getStudentNo() {
return studentNo;
}
public void setStudentNo(String studentNo) {
this.studentNo = studentNo;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
public Integer getClassId() {
return classId;
}
public void setClassId(Integer classId) {
this.classId = classId;
}
@Override
public String toString() {
return "TStudent{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
", sex='" + sex + '\'' +
", birthday=" + birthday +
", createDate=" + createDate +
", studentNo='" + studentNo + '\'' +
", address='" + address + '\'' +
", status='" + status + '\'' +
", age=" + age +
", weight=" + weight +
", height=" + height +
", classId=" + classId +
'}';
}
}
11、service层:
package com.www.service;
import com.www.dao.TStudentDao;
import com.www.entity.TStudent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class TStudentServiceImpl {
@Autowired
private TStudentDao tsd;
public List<TStudent> find(TStudent ts){
List<TStudent> list = tsd.find(ts);
return list;
}
public Map<String, Object> saveOrEdit(TStudent ts) {
Map<String,Object> map = new HashMap<>();
int i = 0;
if (StringUtils.isEmpty(ts.getId())){
i = tsd.insert(ts);
map.put("is",i>0);
map.put("msg","保存"+(i>0?"成功":"失败"));
}else {
i = tsd.update(ts);
map.put("is",i>0);
map.put("msg","编辑"+(i>0?"成功":"失败"));
}
return map;
}
public TStudent get(int id) {
TStudent ts = new TStudent();
ts.setId(id);
List<TStudent> list = this.find(ts);
ts = list.size()>0? list.get(0):null;
return ts;
}
public Map<String, Object> delete(int id) {
Map<String, Object> map = new HashMap<>();
int i = tsd.remove(id);
map.put("msg","删除"+(i>0?"成功!":"失败!"));
map.put("is",i>0);
return map;
}
}
12、简单的执行流程:
13、。。。。。。(不足的、有疑问的欢迎提出、咨询)感谢观看!!!