봄에 대하여
maven에서 spring + springmvc + mybatis 통합의 자세한 구성
SpringBoot + Mybatis + Redis 기본 구성
지난 이틀 동안 작성한 보충 숙제 또는 적어 둡니다. 그렇지 않으면 한 달이 지난 후에도 코드를 입력하지 않으면 잊어 버리고 말도 안되는 말을하게되면 프로젝트 소스 코드를 직접 얻어야합니다.
링크 : https://pan.baidu.com/s/1RQ1rD9fARI37bhCHwLLVOg
추출 코드 : gio8
첫 번째 효과 사진 게시, GIF 사진은 소프트웨어를 얻기에 너무 게으르지 않습니다. 직접 시도해보십시오.
우선 vue와 springboot의 기초가 있어야합니다. springboot는 제 블로그를 먼저 봐주세요. 상세하지 않을 수 있지만 문제를 언급했습니다.
https://blog.csdn.net/qq_41520636/article/details/87192263
오래된 규칙,이 일이 먼저 겪은 문제에 대해 이야기합시다.
질문 1 :
vue 및 axios를 사용할 때 백그라운드 포스트 요청이 연결되고 백그라운드는 항상 null 값을받습니다. Baidu는 거의 그렇게 할 수 없었기 때문에 치료를 포기하기로 결정했습니다. GET 요청 방법을 변경하면 해결할 수있는 큰 녀석이 있으니 비공개 메시지 나 댓글로 알려주세요. 감사합니다!
-------------- 20200417 업데이트 ----------------------------
이 문제가 해결되었습니다!
솔루션 링크 : https://blog.csdn.net/qq_41520636/article/details/104726763
질문 2 :
사실 vue 사용법을 잊은 것뿐입니다. 체크 박스의 값을 선택하고 데이터에 작성한 v-model의 해당 값은 다음과 같습니다.
checkData:''
이것은 잘못된 쓰기 방법입니다. 그렇지 않으면 확인란을 클릭하고 다른 모든 확인란이 선택됩니다.
올바른 접근 방식은
checkData:[]
질문 3 :
자동 코드 생성기 지원을 사용하기 때문에 Baidu는 많은 것을 가지고 있는데 Shenma 플러그인을 설치하는 것이 그렇게 번거 롭습니까? pom.xml의 구성도 있습니다.
이것은 문제가 아닙니다. 단지 내가 잘못 인도 된 것입니다.
Java를 직접 간단하고 편리하게 작성하는 것이 얼마나 좋은지.
질문 4 :
데이터베이스를 설계 할 때 관심있는 일대 다 관계를 기반으로했는데, 이전 코드를 잊었 기 때문에 머리에 갇혀서 할 수 없었습니다.
컨트롤러에서 원하는 학생 테이블에서 List <Hobbys>를 통해 직접
@ResponseBody
@RequestMapping(value ="/addStudent")
public ResponseCode addStudent(@Valid Student student){
System.out.println(student.toString());
int insert = studentService.insert(student);
return new ResponseCode(insert);
}
public class Student implements Serializable {
private List<Hobbys> hobby;
이 목록은 직접 전달됩니다.
hobby.id가 데이터에 직접 추가되었지만 실패했습니다. 얻은 값은 항상 null 값이었으며 취미 매개 변수 만 추가하여 가져올 수 있습니다.
질문 5 :
교차 도메인 요청과 관련하여 문제를 해결하도록 구성했습니다.
위는 내가 만난 거의 문제이고 아래는 코드 포스트입니다.
자동으로 생성 된 우편 번호
package org.lanqiao.test;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* @ClassName TestGenerator
* @Description TODO
* @Author lisonglin
* @Date 2018/12/5 17:00
* @Version 1.0
*/
public class TestGenerator {
/***
* 功能描述:
* 调用generatorConfig.xml
* @param: []
* @return: void
* @auther: 李松林
* @date: 2018/12/8 19:50
*/
public void generator(){
List<String> warnings=new ArrayList<String>();
//更新数据库时,请修改项目的xml配置绝对路径
File file=new File("E:\\MyJAVA\\SpringMakeup\\src\\main\\conf\\generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = null;
try {
config = cp.parseConfiguration(file);
DefaultShellCallback shellCallback = new DefaultShellCallback(true);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, shellCallback, warnings);
myBatisGenerator.generate(null);
System.out.println(warnings);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
try {
TestGenerator generatorSqlmap = new TestGenerator();
generatorSqlmap.generator();
} catch (Exception e) {
e.printStackTrace();
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<!-- 配置生成器 -->
<generatorConfiguration>
<context id="testTables" targetRuntime="MyBatis3" defaultModelType="flat">
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<property name="javaFileEncoding" value="UTF-8"/>
<!-- 生成注释配置 -->
<commentGenerator>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
<property name="javaFileEncoding" value="UTF8"/>
<!--生成的注释包含时间戳(避免重复提交SVN,设为true)-->
<property name="suppressDate" value="true"/>
</commentGenerator>
<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<!--
<jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver"
connectionURL="jdbc:oracle:thin:@150.16.17.22:1521/wsbs" userId="hr"
password="hr123">
</jdbcConnection>-->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/sys?useUnicode=true&characterEncoding=utf8&useSSL=false"
userId="root"
password="123">
</jdbcConnection>
<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- targetProject:生成PO类的位置 -->
<javaModelGenerator targetPackage="org.lanqiao.model"
targetProject="E:/MyJAVA/SpringMakeup/src/main/java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false"/>
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- targetProject:mapper.xml映射文件生成的位置 -->
<sqlMapGenerator targetPackage="org.lanqiao.mapper"
targetProject="E:/MyJAVA/SpringMakeup/src/main/conf">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- targetPackage:mapper.java接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="org.lanqiao.mapper"
targetProject="E:/MyJAVA/SpringMakeup/src/main/java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<!-- 指定数据库表 -->
<!-- enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" selectByExampleQueryId="false"-->
<!--不生成example-->
<!--<table tableName="items"></table> -->
<table tableName="hobbys" mapperName="HobbysMapper" domainObjectName="Hobbys"
enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" selectByExampleQueryId="false">
<!--下划线转驼峰命名-->
<property name="useActualColumnNames" value="false"/>
<!--指定自动生成主键的属性-->
<generatedKey column="id" sqlStatement="MySql" identity="true"></generatedKey>
<!--元素从将某些属性默认计算的值更改为指定的值。-->
<!--<columnOverride column="message_content" javaType="List<Teacher>"></columnOverride >-->
<!--忽略字段-->
<!--<ignoreColumn column="file_id"></ignoreColumn>-->
<!--<ignoreColumn column="lyric_id"></ignoreColumn>-->
</table>
</context>
</generatorConfiguration>
프로젝트 패키지 다이어그램
#热部署
#开启
spring.devtools.restart.enabled=true
#监听目录
spring.devtools.restart.additional-paths=src/main/java
#mybatis
#mybatis-config.xml配置文件的路径
#mybatis.configLocation=classpath:mybatis-config.xml
#SQL语句映射文件
#mybatis.mapper-locaitons= classpath*:com/example/mapper/*.xml
mybatis.mapper-locations=classpath*:org/lanqiao/mapper/*.xml
# 类的别名的包
mybatis.type-aliases-package=org.lanqiao.model
#驼峰命名法
mybatis.configuration.mapUnderscoreToCamelCase=true
#允许返回多个结果集
mybatis.configuration.multipleResultSetsEnabled=true
#使用jdbc的getGeneratedKeys获取数据库自增主键值
mybatis.configuration.useGeneratedKeys=true
#日志
#mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#延迟加载总开关( 查询时,关闭关联对象即时加载以提高性能)
mybatis.configuration.lazyLoadingEnabled=false
#侵入懒加载,设置为false则按需加载,否则会全部加载
mybatis.configuration.aggressiveLazyLoading=false
spring.datasource.url=jdbc:mysql://localhost:3306/sys?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>org.lanqiao</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--热部署-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<!-- tomcat的支持.-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!--自动生成bean-->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.6</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<!-- 对象转换成json引入如下依赖 -->
<!-- 文档:https://www.yiibai.com/jackson/jackson_first_application.html#article-start -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package org.lanqiao.controller;
import org.lanqiao.model.Hobbys;
import org.lanqiao.model.ResponseCode;
import org.lanqiao.model.Student;
import org.lanqiao.service.HobbysService;
import org.lanqiao.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
/**
* @ClassName MainController
* @Description TODO
* @Author lisonglin
* @Date 2019/3/28 0:03
* @Version 1.0
*/
@Controller
public class MainController {
@Autowired
StudentService studentService;
@Autowired
HobbysService hobbysService;
@ResponseBody
@RequestMapping("/getAll")
public List<Student> getStudent(){
List<Student> students = studentService.getAll();
System.out.println(students);
return students;
}
@ResponseBody
@RequestMapping(value ="/addStudent")
public ResponseCode addStudent(@Valid Student student, String hobbys){
System.out.println(student.toString());
System.out.println("兴趣是:"+hobbys);
int insert = studentService.insert(student,hobbys);
return new ResponseCode(insert);
}
@ResponseBody
@RequestMapping(value ="/updateStudent")
public ResponseCode updateStudent(@Valid Student student,String hobbys){
System.out.println(student+"兴趣:"+hobbys);
int i = studentService.updateByPrimaryKey(student, hobbys);
return new ResponseCode(i);
}
@ResponseBody
@RequestMapping(value ="/deleteStudent")
public ResponseCode deleteStudent(Integer studentId){
int i = studentService.deleteByPrimaryKey(studentId);
return new ResponseCode(i);
}
@ResponseBody
@RequestMapping("/getHobbys")
public List<Hobbys> getHobbys(){
return hobbysService.getHobbys();
}
@RequestMapping("/hello")
public String hello(){
return "hello";
}
}
package org.lanqiao.dao;
import org.lanqiao.mapper.StudentHobbysMapper;
import org.lanqiao.mapper.StudentMapper;
import org.lanqiao.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @ClassName StudentDao
* @Description TODO
* @Author lisonglin
* @Date 2019/3/27 23:51
* @Version 1.0
*/
@Repository
public class StudentDao {
@Autowired
StudentMapper studentMapper;
@Autowired
StudentHobbysMapper studentHobbysMapper;
public int deleteByPrimaryKey(Integer id){
studentMapper.deleteByPrimaryKey(id);
studentHobbysMapper.deleteHobbyIdToStudent(id);
return 1;
};
public int insertStudent(Student student, String hobbys){
studentMapper.insert(student);
String regex = ",";
String[] arr = hobbys.split(regex);
for(int i=0;i<arr.length;i++){
studentHobbysMapper.insertStudentHobby(student.getId(),arr[i]);
}
return 1;
};
public int insertSelective(Student record){
return studentMapper.insertSelective(record);
};
public Student selectByPrimaryKey(Integer id){
return studentMapper.selectByPrimaryKey(id);
};
public int updateByPrimaryKeySelective(Student record){
return studentMapper.updateByPrimaryKeySelective(record);
};
public int updateByPrimaryKey(Student student, String hobbys){
studentMapper.updateByPrimaryKey(student);
studentHobbysMapper.deleteHobbyIdToStudent(student.getId());
String regex = ",";
String[] arr = hobbys.split(regex);
for(int i=0;i<arr.length;i++){
studentHobbysMapper.insertStudentHobby(student.getId(),arr[i]);
}
return 1;
};
public List<Student> getAll() {
return studentMapper.getAll();
}
}
package org.lanqiao.dao;
import org.lanqiao.mapper.HobbysMapper;
import org.lanqiao.model.Hobbys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @ClassName HobbysDao
* @Description TODO
* @Author lisonglin
* @Date 2019/3/30 15:54
* @Version 1.0
*/
@Repository
public class HobbysDao {
@Autowired
HobbysMapper hobbysMapper;
public List<Hobbys> getHobbys() {
return hobbysMapper.getHobbys();
}
}
<?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="org.lanqiao.mapper.HobbysMapper">
<select id="getHobbys" resultType="Hobbys">
select * from hobbys
</select>
</mapper>
<?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="org.lanqiao.mapper.StudentHobbysMapper">
<insert id="insertStudentHobby">
insert into stu_hobby (id,hobby) values (#{studentId},#{hobbyId})
</insert>
<delete id="deleteHobbyIdToStudent">
delete from stu_hobby where id=#{studentId}
</delete>
</mapper>
<?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="org.lanqiao.mapper.StudentMapper">
<resultMap id="BaseResultMap" type="org.lanqiao.model.Student">
<id column="id" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="sex" jdbcType="VARCHAR" property="sex" />
<result column="age" property="age" />
<result column="score" jdbcType="DOUBLE" property="score" />
</resultMap>
<sql id="Base_Column_List">
id, name, sex, age, score
</sql>
<sql id="Base_All">
select s.id sid,s.`name`,s.sex,s.age,s.score,h.id,h.hobby
from student s
join stu_hobby sh
on s.id=sh.id
join hobbys h
on sh.hobby=h.id
</sql>
<select id="getAll" resultMap="getStudentAll">
<include refid="Base_All"></include>
</select>
<resultMap id="getStudentAll" type="Student">
<id column="sid" property="id"></id>
<result column="name" property="name"></result>
<result column="sex" property="sex"></result>
<result column="age" property="age"></result>
<result column="score" property="score"></result>
<collection property="hobby" ofType="Hobbys">
<id column="id" property="id"></id>
<result column="hobby" property="hobby"></result>
</collection>
</resultMap>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from student
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from student
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="org.lanqiao.model.Student">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>
insert into student (name, sex, age,
score)
values (#{name,jdbcType=VARCHAR}, #{sex,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER},
#{score,jdbcType=DOUBLE})
</insert>
<insert id="insertSelective" parameterType="org.lanqiao.model.Student">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>
insert into student
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="name != null">
name,
</if>
<if test="sex != null">
sex,
</if>
<if test="age != null">
age,
</if>
<if test="score != null">
score,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="sex != null">
#{sex,jdbcType=VARCHAR},
</if>
<if test="age != null">
#{age,jdbcType=INTEGER},
</if>
<if test="score != null">
#{score,jdbcType=DOUBLE},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="org.lanqiao.model.Student">
update student
<set>
<if test="name != null">
name = #{name,jdbcType=VARCHAR},
</if>
<if test="sex != null">
sex = #{sex,jdbcType=VARCHAR},
</if>
<if test="age != null">
age = #{age,jdbcType=INTEGER},
</if>
<if test="score != null">
score = #{score,jdbcType=DOUBLE},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="org.lanqiao.model.Student">
update student
set name = #{name,jdbcType=VARCHAR},
sex = #{sex,jdbcType=VARCHAR},
age = #{age,jdbcType=INTEGER},
score = #{score,jdbcType=DOUBLE}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>
package org.lanqiao.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
* 解决跨域请求配置
* @ClassName AccessConfig
* @Description TODO
* @Author lisonglin
* @Date 2019/3/30 22:27
* @Version 1.0
*/
@Configuration
public class AccessConfig extends WebMvcConfigurationSupport {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT")
.maxAge(3600);
}
}
package org.lanqiao.config;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @ClassName MapperScannerConfig
* @Description TODO
* @Author lisonglin
* @Date 2019/3/27 22:43
* @Version 1.0
*/
@Configuration
public class MapperScannerConfig {
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
//指定xml配置文件的路径
mapperScannerConfigurer.setBasePackage("org.lanqiao.mapper");
return mapperScannerConfigurer;
}
}
<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>vue增删改查</title>
</head>
<body>
<div id="app1">
<table border="1" cellpadding="0" cellspacing="0">
<tr>
<td colspan="2" align="center">学生基本信息</td>
</tr>
<tr>
<td>姓名</td>
<td>
<input v-model="name" style="width:150px" />
</td>
</tr>
<tr>
<td>性别</td>
<td>
<input type="radio" id="boy" value="男" v-model="sex">
<label for="boy">男</label>
<input type="radio" id="girl" value="女" v-model="sex">
<label for="girl">女</label>
</td>
</tr>
<tr>
<td>年龄</td>
<td>
<select v-model="age">
<option v-for="option in options" v-bind:value="option.value"
:disabled="option.value==0?true:false" :class="{statusbtn:option.value==0}">
{
{ option.text }}
</option>
</select>
</td>
</tr>
<tr>
<td>成绩</td>
<td>
<input v-model.number="score" placeholder="请输入成绩" style="width:150px"/>
</td>
</tr>
<tr>
<td>兴趣</td>
<td>
<span v-for="(studentHobby,index) in studentHobbys" >
<input type="checkbox" name="interests" v-bind:value="index+1" v-model="checkData">
<label>{
{ studentHobby.hobby }}</label>
</span>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" :value="form" @click="submission" v-if="isAdd"/>
<input type="submit" :value="form" @click="update" v-else="!isAdd"/>
<input type="submit" id="reset" value="重置" v-on:click="resets"/>
</td>
</tr>
</table>
<br /><br /><br /><br />
<table border="1" cellspacing="0" cellpadding="0" id="listTable">
<tr>
<td>选中</td>
<td>姓名</td>
<td>性别</td>
<td>年龄</td>
<td>成绩</td>
<td>兴趣</td>
<td>操作</td>
</tr>
<tr>
<td>
<label>全选</label>
<input type="checkbox" name="item" v-model='checked' v-on:click='checkedAll'/>
</td>
<td colspan="6" align="center">
<input type="button" value="选中删除" @click="delRow"/>
</td>
</tr>
<tr v-for="(items,index) in student">
<td><input type="checkbox" name="item" v-model="checkList" :value="items.id"/>{
{1 + index}}</td>
<td>{
{items.name}}</td>
<td>{
{items.sex}}</td>
<td>{
{items.age}}</td>
<td>{
{ items.score }}</td>
<td><span v-for="item in items.hobby">{
{item.hobby}} </span></td>
<td>
<input type="button" value="删除" @click="del(items.id)"/>
<input type="button" name="update" value="修改" @click="modify(items)" />
</td>
</tr>
</table>
</div>
<style>
.statusbtn {
color: #d6caca;
cursor: not-allowed; /*这个在button上面才管用,是一个禁用的小标识*/
}
</style>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js"></script>
<script src="https://cdn.bootcss.com/qs/6.6.0/qs.min.js"></script>
<script>
var app1=new Vue({
el:'#app1',
data:{
options: [
{ text: '请选择', value: '0' },
{ text: '16', value: '16' },
{ text: '17', value: '17' },
{ text: '18', value: '18' },
{ text: '19', value: '19' },
{ text: '20', value: '20' },
{ text: '21', value: '21' },
{ text: '22', value: '22' },
{ text: '23', value: '23' },
],
id:'',
name:'',
age:'0',
sex:'男',
score:'',
studentHobbys:[],
student:[],
form:'提交',
isAdd: true,
checkData: [],//后台请求的数据
checked:false,//全选框
checkList: []
},
watch: { // 监视双向绑定的数据数组
'checkList': {
handler(val, oldVal){ // 数据数组有变化将触发此函数
if (val.length === this.student.length) {
this.checked = true;
} else {
this.checked = false;
}
},
deep: true // 深度监视
}
},
created: function (){
this.getStudent();
this.getHobbysAll();
},
methods: {
getHobbysAll: function(){
axios.get('http://localhost:8080/getHobbys')
.then(function (response) {
var arr = response.data;
app1.studentHobbys = arr;
})
.catch(function (error) {
})
},
getStudent:function () {
axios.post('http://localhost:8080/getAll').
then(function (response){
var arr=response.data;
app1.student=arr;
}) .catch(function (error) {
})
},
submission:function () {
// console.log("选中:"+this.checkData);
//获取兴趣
var selectedValue=this.checkData;
axios.get('http://localhost:8080/addStudent?name='+this.name+'&sex='+this.sex+'&age='+
this.age+'&score='+this.score+'&hobbys='+selectedValue)
.then(function (response) {
//更新
app1.getStudent();
//重置
app1.resets();
}).catch(function (error) {
})
},
del:function (e) {
// console.log(e);
axios.get('http://localhost:8080/deleteStudent?studentId='+e)
.then(function (response) {
app1.getStudent();
}).catch(function (error) {
})
},
//选中删除
delRow:function(){
for(var i=0;i<this.checkList.length;i++){
axios.get('http://localhost:8080/deleteStudent?studentId='+this.checkList[i])
.then(function (response) {
app1.getStudent();
}).catch(function (error) {
})
}
},
//修改回显
modify:function (items) {
//重置
app1.resets();
//更新按钮
app1.form='更新';
//回显
this.id=items.id;
this.name=items.name;
this.sex=items.sex;
this.age=items.age;
this.score=items.score;
var arr=[];
for(var i=0;i<items.hobby.length;i++){
arr.push(items.hobby[i].id);
}
this.checkData=arr;
this.isAdd=false;
},
update:function(items){
axios.get('http://localhost:8080/updateStudent?id='+this.id+'&name='+this.name+'&sex='+this.sex+'&age='+
this.age+'&score='+this.score+'&hobbys='+this.checkData)
.then(function (response) {
app1.getStudent();
app1.resets();
}).catch(function (error) {
})
},
resets:function () {
this.name='',
this.sex='男',
this.age='0',
this.score=''
this.checkData=[],
this.form='提交',
this.isAdd=true
},
checkedAll: function(){
//全选和反选
var _this = this;
// .log(_this.checked+"---"+_this.checkList+"----"+_this.student)
this.$nextTick(function() {
if(!_this.checked){
_this.checkList = _this.student.map(function(json,index){
// console.log(json.id+","+index)
return json.id;
})
}else {
_this.checkList = []
}
});
},
}
});
</script>
</body>
</html>
위의 기본 코드와 중요한 코드가 게시되어 있으므로 자세한 소스 코드를 참조하십시오.