运行结果展示:
查询:
添加:
修改:
删除:
代码整体布局:
代码如下:
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_0824_KTLX2</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>spring_0824_KTLX2 Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<servlet.version>4.0.1</servlet.version>
<jsp.version>2.2</jsp.version>
<jstl.version>1.2</jstl.version>
<spring.version>5.3.14</spring.version>
<commons-dbcp.version>1.4</commons-dbcp.version>
<mybatis.version>3.4.6</mybatis.version>
<mybatis-spring.version>1.3.3</mybatis-spring.version>
<mysql-connector-java.version>8.0.11</mysql-connector-java.version>
<fastjson.version>2.0.10</fastjson.version>
</properties>
<dependencies>
<!--添加spring依赖-->
<!-- 添加javaEE支持 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet.version}</version>
<!-- provided只在编译时支持,发布时不拷贝文件 -->
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp.version}</version>
<!-- provided只在编译时支持,发布时不拷贝文件 -->
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<!--引入spring框架-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!--引入spring数据库操作的支持模块-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- dbcp数据库连接池 -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>${commons-dbcp.version}</version>
</dependency>
<!-- mybatis spring整合 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring.version}</version>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!--mybatis插件PageHelper-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.0</version>
</dependency>
<!-- mysql驱动类 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
</dependency>
<!--mybatis通用mapper-->
<dependency>
<groupId>com.github.abel533</groupId>
<artifactId>mapper</artifactId>
<version>3.0.1</version>
</dependency>
<!--jackson-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.2.2</version>
</dependency>
<!--配置fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</dependency>
<!--引入junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<!--scope:表示该jar包的作用范围
<scope>test</scope>
-->
</dependency>
</dependencies>
</project>
Category:
package com.aaa.demo.entity;
import lombok.Data;
import javax.persistence.Id;
import javax.persistence.Table;
@Data
@Table(name = "category")
public class Category {
@Id
private Integer categoryId;
private String categoryName;
}
CommonResult :
package com.aaa.demo.entity;
public class CommonResult {
//编码:0成功,1失败
private Integer code;
//提示消息
private String msg;
//记录数
private Integer count;
//记录数据
private Object data;
public CommonResult() {
}
public CommonResult(Integer code, String msg, Integer count, Object data) {
this.code = code;
this.msg = msg;
this.count = count;
this.data = data;
}
//返回查询结果的成功信息:
public static CommonResult success(Integer count,Object data){
return new CommonResult(0,"success",count,data);
}
//返回增删改的成功信息
public static CommonResult success(){
return new CommonResult(0,"success",null,null);
}
//返回失败信息
public static CommonResult fail(){
return new CommonResult(1,"fail",null,null);
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
@Override
public String toString() {
return "CommonResult{" +
"code=" + code +
", msg='" + msg + ''' +
", count=" + count +
", data=" + data +
'}';
}
}
CategoryMapper:
package com.aaa.demo.mapper;
import com.aaa.demo.entity.Category;
import com.github.abel533.mapper.Mapper;
public interface CategoryMapper extends Mapper<Category> {
}
ICategoryService:
package com.aaa.demo.service;
import com.aaa.demo.entity.Category;
import java.util.List;
public interface ICategoryService {
List<Category> listAll();
int insert(Category category);
int update(Category category);
int delete(Integer categoryId);
}
CategoryServiceImpl:
package com.aaa.demo.service.impl;
import com.aaa.demo.entity.Category;
import com.aaa.demo.mapper.CategoryMapper;
import com.aaa.demo.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CategoryServiceImpl implements ICategoryService {
@Autowired
private CategoryMapper categoryMapper;
@Override
public List<Category> listAll() {
return categoryMapper.select(null);
}
@Override
public int insert(Category category) {
return categoryMapper.insert(category);
}
@Override
public int update(Category category) {
return categoryMapper.updateByPrimaryKey(category);
}
@Override
public int delete(Integer categoryId) {
return categoryMapper.deleteByPrimaryKey(categoryId);
}
}
CategoryController:
package com.aaa.demo.controller;
import com.aaa.demo.entity.Category;
import com.aaa.demo.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController //等价于 @Controller + @ResponseBody
@RequestMapping("/category")
public class CategoryController {
@Autowired
private ICategoryService iCategoryService;
@RequestMapping("/list")
public List<Category> list(){
return iCategoryService.listAll();
}
@RequestMapping("/add")
public int add(Category category){
System.out.println("======add=======");
System.out.println(category);
return iCategoryService.insert(category);
}
@RequestMapping("/update")
public int update(Category category){
System.out.println("======update=======");
System.out.println(category);
return iCategoryService.insert(category);
}
@RequestMapping("/delete")
public int delete(Integer categoryId){
System.out.println("======delete========");
System.out.println(categoryId);
return iCategoryService.delete(categoryId);
}
}
db.properties:
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/70813_db?useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=utf8&allowPublicKeyRetrieval=true
jdbc.username=root
jdbc.password=123456
mybatis-config.xml:
<?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="logImpl" value="STDOUT_LOGGING"/>
<!--配置将下划线字段转为小驼峰-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<plugins>
<!--拦截器-->
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<property name="offsetAsPageNum" value="true"/>
<!--配置数据库方言 4.0版本以后不用写-->
<!--<property name="helperDialect" value="mysql"/>-->
<!--是否做count查询-->
<property name="rowBoundsWithCount" value="true"/>
<!--合理化分页-->
<property name="reasonable" value="true"/>
</plugin>
<plugin interceptor="com.github.abel533.mapperhelper.MapperInterceptor">
<!--主键自增回写方法,默认值MYSQL -->
<!--<property name="IDENTITY" value="MYSQL" />-->
<!--通用Mapper默认接口,我们定义的Mapper需要实现该接口 -->
<property name="mappers" value="com.github.abel533.mapper.Mapper" />
</plugin>
</plugins>
</configuration>
spring-mybatis.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 https://www.springframework.org/schema/context/spring-context.xsd">
<!--配置spring扫描包-->
<context:component-scan base-package="com.aaa.demo.service"/>
<!--通过spring配置数据库的连接属性文件-->
<context:property-placeholder location="classpath:db.properties"/>
<!--通过spring来配置数据库连接池的数据源对象-->
<bean id="ds" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<!--配置连接池数据源需要使用四大金刚(数据库连接属性)-->
<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的会话工厂和其他相关配置
原来的时候,mybatis的会话工厂由程序员来创建,现在通过spring来创建管理
这个就体现了Spring的IoC特征(控制反转)
-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--配置SqlSession依赖的数据源对象-->
<property name="dataSource" ref="ds"/>
<!--配置mybatis要使用的类型别名定义-->
<property name="typeAliasesPackage" value="com.aaa.demo.entity"/>
<!--配置mybatis的主配置文件的路径,spring会自动加载mybatis的配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!--配置mybatis的Mapper文件的路径:spring中Mapper接口和Mapper文件路径可以由区别-->
<property name="mapperLocations" value="classpath:com/mapper/*.xml"/>
</bean>
<!--通过spring来配置Mybatis的Mapper接口
通过包扫描的方式进行配置
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--配置Mybatis的Mapper接口-->
<property name="basePackage" value="com.aaa.demo.mapper"/>
<!--配置可以创建Mapper接口对象的SqlSession使用的SqlSessionFactory对象的名字-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
</beans>
spring-mvc.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/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--扫描controller包,管理其中定义的controller类-->
<context:component-scan base-package="com.aaa.demo.controller"/>
<!--开启注解驱动
使用注解方式配置springMVC组件
处理器映射器,处理器适配器,
能够解析配置的注解完成请求:@RequestMapping
-->
<mvc:annotation-driven/>
<!--配置视图解析器(ViewResolver)-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--配置视图页面前缀-->
<property name="prefix" value="/WEB-INF/page/"/>
<!--配置视图页面后缀-->
<property name="suffix" value=".jsp"/>
</bean>
<!--配置DefaultServlet处理其他请求(静态资源)-->
<mvc:default-servlet-handler/>
</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容器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--定义spring的配置文件,用于在spring监听器监听网站启动的时候,创建spring容器-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mybatis.xml</param-value>
</context-param>
<!--配置spring的编码过滤器-->
<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>
<!--配置springMVC前端控制器-->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!--
springMVC需要配置组件。。。
-->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<!--
凡是以.do结尾的请求都让springMVC来处理
<url-pattern>*.do</url-pattern>
-->
<!-- <url-pattern>*.do</url-pattern>-->
<!--
斜杠配置(/)∶表示所有的默认请求都交给DisaptherServlet来处理
导致的问题就是请求静态资源的时候无法处理
<url-pattern>/</url-pattern>
-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
category.jsp:
<%--
Created by IntelliJ IDEA.
User: 33154
Date: 2022/8/25
Time: 14:34
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<div>分类数据</div>
<div id="category">
</div>
<%--添加表单--%>
<form id="btnAddFrm">
分类名称:
<input type="text" id="categoryName" name="categoryName"/>
<input type="button" value="添加" id="btnAdd"/>
</form>
<%--修改表单--%>
<form id="btnUpdateFrm">
分类编号:
<input type="text" id="categoryId" name="categoryId"/>
分类名称:
<input type="text" name="categoryName"/>
<input type="button" value="修改" id="btnUpdate"/>
</form>
<%--删除表单--%>
<form id="btnDeleteFrm">
分类编号:
<input type="text" name="categoryId"/>
<input type="button" value="删除" id="btnDelete"/>
</form>
<!--引入jqery-->
<script type="text/javascript" src="${pageContext.request.contextPath}/assets/jq/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$.ajax({
url:"${pageContext.request.contextPath}/category/list",
type:"get",
success:function (res){
console.log(res);
for(var i=0;i<res.length;i++){
$("#category").append("<p>"+res[i].categoryId+" "+res[i].categoryName+"</p>")
}
}
})
//绑定添加按钮单击
$("#btnAdd").click(function (){
//通过表单序列,返回表单的字符串拼接数据 :categoryId=xxx&cateName=xxx
alert($("#btnAddFrm").serialize())
$.ajax({
url: "${pageContext.request.contextPath}/category/add",
data:$("#btnAddFrm").serialize(),
type: "post",
success:function (res){
alert(res);
}
})
})
//绑定修改按钮单击
$("#btnUpdate").click(function (){
//通过表单序列,返回表单的字符串拼接数据 :categoryId=xxx&cateName=xxx
alert($("#btnUpdateFrm").serialize())
$.ajax({
url:"${pageContext.request.contextPath}/category/update",
data: $("#btnUpdateFrm").serialize(),
type:"post",
success:function (res){
alert(res);
}
})
})
//绑定删除按钮单击
$("#btnDelete").click(function (){
//通过表单序列,返回表单的字符串拼接数据 :categoryId=xxx&cateName=xxx
alert($("#btnDeleteFrm").serialize())
$.ajax({
url:"${pageContext.request.contextPath}/category/delete",
data: $("#btnDeleteFrm").serialize(),
type:"post",
success:function (res){
alert(res);
}
})
})
</script>
</body>
</html>
关键点参考:
注意:
ajax中的数据传输:
ajax中的get/post:
引入通用mapper:(可以理解为引入“接口实现类里的各种方法”)
绑定表/id实现“通过主键更新/删除的方法”:
接口插件:
原文地址:https://blog.csdn.net/Liu_wen_wen/article/details/126526855
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_48140.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。