上一篇搭建起了大體架構,這一篇寫個增刪改查demo,
第三篇是完善第二篇的bug:第三篇
7、測試顯示table 信息 √
(建table,在sql 裏面添加幾條數據,顯示到頁面)
8、增加熱部署功能 √(自動刷新後臺java,xml代碼變動情況,無需手動重啓,
不過idea對它支持不大友好,建議idea寫完框架後用 sts(eclipse對spring包的集成)繼續修改
spring.thymeleaf.cache 設爲false
或者使用springboot的devtools
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<version>1.3.0.RELEASE</version>
</dependency>
)9、增加 redis設置 √(這個著名的高性能sql不用多說了吧?自行安裝配置)
10、加入前端框架:layUI ,bootstrap,jquery √
(前端頁面爲bootstrap-table)
11、寫增刪查改! crud √
(前臺,寫個隱藏域,獲取id,如果id爲空,執行添加;如果id有值,執行修改;實現兩個功能用一個方法)
12、設置報錯頁面 √
13、美化頁面,規範代碼 √
————————————————————
效果:
目錄結構:
工慾善其事必先利其器,配置幾個不錯的功能再寫demo吧:
主頁:Application.java ,這裏有個跳轉首頁的註解方法,index主頁大家自己寫比較好
@Controller
@SpringBootApplication
@ServletComponentScan
@EnableScheduling
@EnableCaching
@MapperScan(basePackages = {"com.example.demo.other.MyMapper"})
//啓註解事務管理
@EnableTransactionManagement
public class Application {
private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
"classpath:/META-INF/resources/", "classpath:/resources/",
"classpath:/static/", "classpath:/public/"
};
@RequestMapping(value="/index",method = RequestMethod.GET)
public String showIndex(){
return "index";
}
}
一、配置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>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath/>
</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-thymeleaf</artifactId>
</dependency>
<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>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-autoconfigure</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
<!-- 分頁插件 -->
<!-- <dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.1</version>
</dependency>-->
<!--通用Mapper插件-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
<version>1.2.7.RELEASE</version>
</dependency>
<!-- redis 設置 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- aop異常處理 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>-->
<!-- tomcat , jsp 的支持 ;做jsp頁面的測試 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.7</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
二、application.properties 設置:
當前mysql密碼爲空,redies還沒完全配置好
#設置Tomcat端口,默認8081
server.port=8081
#設置項目ContextPath
server.servlet.context-path =/test
server.jsp-servlet.init-parameters.*= # Init parameters used to configure the JSP servlet
#設置Tomcat編碼
server.tomcat.uri-encoding=UTF-8
#設置視圖解析器路徑
spring.mvc.view.prefix=/static/jsp/
#設置視圖解析器後綴
spring.mvc.view.suffix=.jsp
#修改jsp後立即加載
server.jsp-servlet.init-parameters.development=true
#server.html-servlet.init-parameters.development=true
#數據庫配置
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=gbk
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.thymeleaf.prefix=classpath:/templates/
#配置.xml文件路徑
mybatis.mapper-locations=classpath*:mapper/**/*.xml
#配置模型路徑
mybatis.type-aliases-package=com.example.demo.model
mapper.mappers=com.example.demo.other.MyMapper
mapper.not-empty=false
mapper.identity=MYSQL
#jpa create table
spring.jpa.database = MYSQL
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.DefaultNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
#關閉緩存,及時刷新
spring.freemarker.cache=false
#熱部署生效
spring.devtools.restart.enabled=true
spring.devtools.restart.exclude=META-INF/maven/**,META-INF/resources/**,resources/**,static/**,public/**,templates/**,**/*Test.class,**/*Tests.class,git.properties # Patterns that should be excluded from triggering a full restart.
#設置重啓的目錄,添加那個目錄的文件需要restart(監聽目錄)
spring.devtools.restart.additional-paths=src/main/java
# 熱部署引起的亂碼
spring.http.encoding.force=true
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
# Redis數據庫索引(默認爲0)
spring.redis.database=0
# Redis服務器地址
spring.redis.host=172.31.19.222
# Redis服務器連接端口
spring.redis.port=6379
# Redis服務器連接密碼(默認爲空)
spring.redis.password=
# 連接池最大連接數(使用負值表示沒有限制)
spring.redis.pool.max-active=8
# 連接池最大阻塞等待時間(使用負值表示沒有限制)
spring.redis.pool.max-wait=-1
# 連接池中的最大空閒連接
spring.redis.pool.max-idle=8
# 連接池中的最小空閒連接
spring.redis.pool.min-idle=0
# 連接超時時間(毫秒)
spring.redis.timeout=0
## LOG4J配置
log4j.rootCategory=DEBUG,stdout
## 控制檯輸出
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n
二、項目設置:
1、Setting-compiler-make project automatically 勾上,自動啓動刷新;
2、ctrl + shift + alt + /,選擇Registry,勾上 Compiler autoMake allow when app running
(每個人的idea版本不同,快捷鍵不一定,我的是 Ctrl+Shift+A )
3、重啓idea,完成熱部署
(其他參考:https://www.jianshu.com/p/7b659c75c0ee)
注意:idea對熱部署的支持不友好,sts才能完成適應熱部署!
三、other的其他類設置:
我需要配置myBatis,myMapper,redis三個類,
application已經配置了掃描路徑,這裏直接給方法:
1、MybatisProperties
package com.example.demo.other;
/**
* Created by Administrator on 2018/6/15 0015.
*/
import org.apache.ibatis.session.ExecutorType;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.io.Resource;
/**
* Configuration properties for Mybatis.
*
* @author Eddú Meléndez
*/
@ConfigurationProperties(prefix = MybatisProperties.MYBATIS_PREFIX)
public class MybatisProperties {
public static final String MYBATIS_PREFIX = "mybatis";
/**
* Config file path.
*/
private String config;
/**
* Location of mybatis mapper files.
*/
private Resource[] mapperLocations;
/**
* Package to scan domain objects.
*/
private String typeAliasesPackage;
/**
* Package to scan handlers.
*/
private String typeHandlersPackage;
/**
* Check the config file exists.
*/
private boolean checkConfigLocation = false;
/**
* Execution mode.
*/
private ExecutorType executorType = ExecutorType.SIMPLE;
public String getConfig() {
return this.config;
}
public void setConfig(String config) {
this.config = config;
}
public Resource[] getMapperLocations() {
return this.mapperLocations;
}
public void setMapperLocations(Resource[] mapperLocations) {
this.mapperLocations = mapperLocations;
}
public String getTypeHandlersPackage() {
return this.typeHandlersPackage;
}
public void setTypeHandlersPackage(String typeHandlersPackage) {
this.typeHandlersPackage = typeHandlersPackage;
}
public String getTypeAliasesPackage() {
return this.typeAliasesPackage;
}
public void setTypeAliasesPackage(String typeAliasesPackage) {
this.typeAliasesPackage = typeAliasesPackage;
}
public boolean isCheckConfigLocation() {
return this.checkConfigLocation;
}
public void setCheckConfigLocation(boolean checkConfigLocation) {
this.checkConfigLocation = checkConfigLocation;
}
public ExecutorType getExecutorType() {
return this.executorType;
}
public void setExecutorType(ExecutorType executorType) {
this.executorType = executorType;
}
}
2、MyMapper.java (數據庫持久層dao,我需要調用它封裝的sql方法)
package com.example.demo.other;
/**
* Created by Administrator on 2018/6/15 0015.
*/
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
/**
* 被繼承的Mapper,一般業務Mapper繼承它
*
*/
public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> {
//TODO
//FIXME 特別注意,該接口不能被掃描到,否則會出錯
}
3、RedisConfigpackage com.example.demo.other;
/**
* Created by Administrator on 2018/6/16 0016.
*/
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.util.HashMap;
import java.util.Map;
/**
* Redis緩存配置類
* @author szekinwin
*
*/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{
@Bean(name="redisTemplate")
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, String> template = new RedisTemplate<>();
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setConnectionFactory(factory);
//key序列化方式
template.setKeySerializer(redisSerializer);
//value序列化
template.setValueSerializer(jackson2JsonRedisSerializer);
//value hashmap序列化
template.setHashValueSerializer(jackson2JsonRedisSerializer);
return template;
}
/* @Bean
public CacheManager cacheManager(@SuppressWarnings("rawtypes")RedisTemplate redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
cacheManager.setDefaultExpiration(3000);
return cacheManager;
}*/
}
四、寫個增刪改查demo
1、mysql建表:
CREATE TABLE `student` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`age` int(11) NOT NULL,
`name` varchar(255) DEFAULT NULL,
`to_day` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
2、model :實體類 Student.java
(注意,springboot裏面,不大支持Integer id,
這裏id 我用Long類型,使用的時候記得轉換類型)
package com.example.demo.model;
import javax.persistence.*;
import java.io.Serializable;
/**
* Created by Administrator on 2018/6/15 0015.
*/
@Entity
@Table(name="student")
public class Student implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Integer age;
private String toDay;
public Student(){
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getToDay() {
return toDay;
}
public void setToDay(String toDay) {
this.toDay = toDay;
}
}
3、service層,接口跟方法
StudentService接口:
package com.example.demo.service;
import com.example.demo.model.Student;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* Created by Administrator on 2018/6/15 0015.
*/
@Component
public interface StudentService {
//顯示table信息
public List<Student> showTable();
//添加信息
/* public Integer addStudent(Student st);*/
//刪除
public Integer deleteStudent(String id);
//修改
/* public Integer editStudent(Student st);*/
//查詢(模糊查詢:age,name)
public List<Student> findStudent(String testInput);
//添加,修改共用一個方法
public Integer updateStudent(Student st);
}
StudentServiceImpl.java 實現接口方法
(這裏用了MyMapper帶有的sql方法,它不是一個jar包,需要自己手動加上去,
但是用起來非常方便!不過查詢是在 StudentMapper.java 接口的方法 ,
sql語句在 resources-mapper-StudentMapper.xml
)package com.example.demo.service.impl;
import com.example.demo.mapper.StudentMapper;
import com.example.demo.model.Student;
import com.example.demo.service.StudentService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* Created by Administrator on 2018/6/15 0015.
*/
@Service
public class StudentServiceImpl implements StudentService {
@Resource
StudentMapper sm;
@Override
public List<Student> showTable() {
System.out.println("----------顯示table全部信息------");
return sm.selectAll();
}
//添加
/* @Override
public Integer addStudent(Student st) {
System.out.println("---------添加信息---------"+st);
return sm.insert(st);
}*/
//刪除: 因爲javabean裏,ID是Long型的,所以需要轉換
@Override
public Integer deleteStudent(String id) {
System.out.println("----------刪除信息------"+id);
return sm.deleteByPrimaryKey(Long.valueOf(id));
}
//修改
/* @Override
public Integer editStudent(Student st) {
System.out.println("------修改信息-------"+st);
return sm.updateByPrimaryKey(st);
}*/
//嘗試添加,修改寫同一個方法
@Override
public Integer updateStudent(Student st) {
//獲取id
if(st.getId() !=null){
System.out.println("----id不爲空,執行修改---"+st.getId());
return sm.updateByPrimaryKey(st);
}else{
System.out.println("----id空,執行新增---"+st.getId());
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
st.setToDay(sdf.format(new Date()));
return sm.insert(st);
}
}
//模糊查詢:age,name
@Override
public List<Student> findStudent(String testInput){
System.out.println("------查詢輸入信息----"+testInput);
return sm.selectStudentUrl("%" + testInput+ "%" , "%"+ testInput +"%");
}
}
4、mapper,數據庫持久層:
StudentMapper.java
package com.example.demo.mapper;
import com.example.demo.model.Student;
import com.example.demo.other.MyMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* Created by Administrator on 2018/6/15 0015.
*/
@Mapper
public interface StudentMapper extends MyMapper<Student> {
List<Student> selectStudentUrl(@Param("age") String age, @Param("name") String name);
}
5、controller層:(以上都配置好有,再寫控制層,給前端頁面調用)
StudentController.java
package com.example.demo.controller;
import com.example.demo.model.Student;
import com.example.demo.service.impl.StudentServiceImpl;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import org.slf4j.Logger;
/**
* Created by Administrator on 2018/6/15 0015.
*/
@Controller
public class StudentController {
private Logger logger = LoggerFactory.getLogger(getClass());
@Resource
private StudentServiceImpl ssi;
@RequestMapping ("/hello")
public String showTest(){
return "testStudent";
}
@RequestMapping("/showTable")
@ResponseBody
public List<Student> showStudent(){
List<Student> ls=ssi.showTable();
return ls;
}
/**
* 添加學生
*/
/* @RequestMapping("/addStudent")
@ResponseBody
public Integer addStudent(Student st){
return ssi.addStudent(st);
}*/
/**
* 刪除學生
*/
@RequestMapping("/deleteStudent")
@ResponseBody
public Integer deleteStudent(String id){
return ssi.deleteStudent(id);
}
/**
* 修改學生
*/
/* @RequestMapping("/editStudent")
@ResponseBody
public Integer editStudent(Student st){
return ssi.editStudent(st);
}*/
/**
* 添加/修改學生
*/
@RequestMapping("/updateStudent")
@ResponseBody
public Integer updateStudent(Student st){
return ssi.updateStudent(st);
}
/**
* 查詢學生,需要studentRepository的方法
*/
@RequestMapping("/selectStudent")
@ResponseBody
public List<Student> selectTestPeople(HttpServletRequest request) {
String testInput=request.getParameter("testInput");
logger.info("selectTestPeopleUrl===="+testInput);
return ssi.findStudent(testInput);
}
}
6、resource-mapper下的xml文件:StudentMapper.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.example.demo.mapper.StudentMapper">
<resultMap id="BaseResultMap" type="com.example.demo.model.Student">
<id column="id" jdbcType="BIGINT" property="id" />
<result column="age" jdbcType="VARCHAR" property="age" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="to_day" jdbcType="VARCHAR" property="toDay" />
</resultMap>
<select id="selectStudentUrl" resultMap="BaseResultMap" >
select * from student
<where>
<if test="age!=null"> or age like #{age} </if>
<if test="name!=null"> or name like #{name}</if>
</where>
</select>
</mapper>
(
用於我mybatis用的少,有時會犯錯,
提醒一下各位,
1、規範 : xml文件與mapper層的類同名
xxxMapper.xml 與 xxxMapper.java
2、規則:mapper,serviceImpl層的方法名需要和xml 的id一致:
return sm.selectStudentUrl.....
List<Student> selectStudentUrl(....
<select id="selectStudentUrl" resultMap="BaseResultMap" >)
————————————————————————
五、頁面佈局:後臺方法已經寫好了,那麼頁面直接調用即可,頁面默認第一級目錄:templates
1、testStudent.html
溫馨提示:springboot識別js,css 不能用絕對路徑,
在頁頭加上:<html xmlns:th="http://www.thymeleaf.org">
css用這個方式:<link rel="stylesheet" type="text/css" th:href="@{/index.css}">
js用這個:<script th:src="@{/xxx.js}"></script>
這裏使用了:bootstrap,bootstrap-table的css跟js,可以用cdn外鏈:https://cdn.baomitu.com/
layUi 的css跟js ,沒有外鏈,直接下載丟進項目:http://www.layui.com/
多看看console是否有未識別的js,cs,是否有錯誤的代碼;
<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>testStudent</title>
<style type="text/css">
#list_Sysdic .test1{
width: 200px;
}
#list_Sysdic tr td{
font-size:12px;
padding: 5px !important;
}#list_Sysdic th{
font-size:100%;
padding: 0px !important;
}.col-sm-3{
width: 19%;
}.col-sm-8{
width: 80%;
padding-left: 0px;
}
.radio input[type="radio"]{
margin-top: 3px;
}
/* 去掉 number 的箭頭 */
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
}
input[type="number"]{
-moz-appearance: textfield;
}
</style>
<!-- 引用外部css 寫法
<link rel="stylesheet" type="text/css" th:href="@{/index.css}">-->
<link rel="stylesheet" type="text/css" th:href="@{/css/bootstrap.min.css}"/>
<link rel="stylesheet" type="text/css" th:href="@{/css/bootstrap-table.min.css}"/>
<link rel="stylesheet" type="text/css" th:href="@{/css/layui.css}">
<link rel="stylesheet" type="text/css" th:href="@{/css/modules/code.css}">
</head>
<body style="text-align: center;margin: 50px;">
<div class="panel-body" style="padding:5px;margin-top: -20px;">
<div id="toolbar_not">
<div class="pull-left search" style="margin-left: 10px">
<input class="form-control" id="input_title" style="display:inline;width: 180px" placeholder="請輸入年齡或姓名" type="text"/>
</div>
<button id="button_selectStudent" style="margin-top: 10px;" class="btn btn-primary">查詢</button>
<button id="button_addStudent" style="margin-top: 10px;" class="btn btn-primary" data-toggle="modal" data-target="#addStudent">添加</button>
</div>
<table
id="list_showStudent"
data-toggle="table"
data-toolbar="#toolbar_not"
data-height=""
data-striped="true"
data-url="showTable"
data-pagination="true"
data-page-list="[5, 10, 20, 50]"
data-sort-name="id"
data-sort-order="desc"
style="text-align: center;">
<thead>
<tr>
<th data-field="id" data-width="15%">id</th>
<th data-field="age" data-width="15%">年齡</th>
<th data-field="name" data-width="15%">姓名</th>
<th data-field="toDay" data-width="15%">日期</th>
<th class="test1" data-formatter="operateFormatter" data-width="15%">操作</th>
</tr>
</thead>
</table>
</div>
<!-- 任務添加信息表 -->
<div class="modal inmodal" id="addStudent" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog" style="width: 420px">
<div class="modal-content animated fadeIn">
<div class="modal-header" style="padding: 8px">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<p class="modal-title" style="font-size: 16px;">添加信息</p>
</div>
<div class="modal-body">
<form class="form-horizontal m-t" id="form_addStudent">
<div class="form-group">
<label class="col-sm-3 control-label" style="width:24%">年齡:</label>
<div class="col-sm-8" style="width:68%">
<input id="age" name="age" placeholder="年齡請輸入數字" class="form-control" type="number"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label" style="width:24%">姓名:</label>
<div class="col-sm-8" style="width:68%">
<input id="name" name="name" class="form-control" type="text"/>
</div>
</div>
</form>
</div>
<div class="modal-footer" style="padding: 8px">
<button type="button" class="btn btn-primary btn_saveStudent">保存</button>
<button type="button" class="btn btn-white" data-dismiss="modal">關閉</button>
</div>
</div>
</div>
</div>
<!-- 任務編輯,修改 -->
<div class="modal inmodal" id="editStudentDiv" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog" style="width: 420px">
<div class="modal-content animated fadeIn">
<div class="modal-header" style="padding: 8px">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<p class="modal-title" style="font-size: 16px;">任務編輯</p>
</div>
<div class="modal-body">
<form class="form-horizontal m-t" id="form_editStudent">
<div class="form-group">
<label class="col-sm-3 control-label" style="width:24%">年齡:</label>
<div class="col-sm-8" style="width:68%">
<input id="OldAge" name="age" placeholder="請輸入數字" class="form-control" type="number"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label" style="width:24%">姓名:</label>
<div class="col-sm-8" style="width:68%">
<input id="OldName" name="name" class="form-control" />
</div>
</div>
<div style="display: none;" class="form-group">
<label class="col-sm-3 control-label" style="width:24%">日期:</label>
<div class="col-sm-8" style="width:68%">
<input id="OldToDay" name="toDay" class="form-control" />
</div>
</div>
<input name="id" id="ids" type="hidden">
</form>
</div>
<div class="modal-footer" style="padding: 8px">
<button type="button" class="btn btn-white btn_editStudent" data-dismiss="modal">確定</button>
<button type="button" class="btn btn-white" data-dismiss="modal">關閉</button>
</div>
</div>
</div>
</div>
<!-- 任務編輯 結束-->
<!--<br>
<hr><hr>-->
<script th:src="@{/js/jquery.min.js}"></script>
<script th:src="@{/js/bootstrap.min.js}"></script>
<script th:src="@{/js/bootstrap-table.min.js}"></script>
<script th:src="@{/layui.all.js}"></script>
<script th:src="@{/otherJs/testStudent.js}"></script>
</body>
</html>
2、testStudent.js:用bootstrap-table.js 跟 layui.js
/**
*操作格式化
*/
function operateFormatter(value, row, index) {
return [
'<a class="" href="javascript:void(0)" onclick="editStudentBtn('+index+')" data-toggle="modal" data-target="#editStudentDiv" title="Remove"><button class="label label-info">修改</button></a> ',
'<a class="" href="javascript:void(0)" id="'+row.id+'" age="'+row.age+'" name="'+row.name+'" onclick="deleteStudentBtn(this)" title="Remove"><button class="label label-info">刪除</button></a>'
].join('');
}
/**
任務列表刪除
*/
function deleteStudentBtn(th){
var id=$(th).attr("id");
layer.confirm('你確定刪除信息嗎?', {
btn: ['確定','取消'] //按鈕
}, function(){
$.ajax({
type : "post",
url:"deleteStudent",
data:{id:id},
async:false,
success: function (data) {
layer.msg("操作成功",{icon:1});
$("#list_showStudent").bootstrapTable('remove',{
field:'id'
});
}
});
$("#list_showStudent").bootstrapTable('refresh');
$("#list_showStudent").bootstrapTable('refresh');
}, function () {
});
}
/**
添加學生:保存後獲取form全部信息,以pos請求使用添加方法,隱藏彈框,刷新table
*/
$(function () {
$(".btn_saveStudent").click(function () {
var ser=$("#form_addStudent").serialize();
$.post("updateStudent",ser, function (data) {
/* $.post("addStudent",ser, function (data) { */
if(data==1){
layer.msg("操作成功",{icon:1});
$("#addStudent").modal('hide');
$("#list_showStudent").bootstrapTable('refresh');
}
});
});
});
/**
* 修改學生信息:獲取table的全部信息,獲取每一行的字段內容,預備顯示到彈框
*/
function editStudentBtn(index){
var data=$("#list_showStudent").bootstrapTable('getData');
$("#ids").val(data[index].id);
$("#OldAge").val(data[index].age);
$("#OldName").val(data[index].name);
$("#OldToDay").val(data[index].toDay);
}
$(".btn_editStudent").click(function () {
var ser=$("#form_editStudent").serialize();
$.post("updateStudent",ser,function(data){
/* $.post("editStudent",ser,function(data){ */
if (data==1){
layer.msg("操作成功",{icon:1});
$("#list_showStudent").bootstrapTable("refresh");
$("#editStudentDiv").modal('hide');
}
});
});
/**
查詢信息
*/
$("#button_selectStudent").click(function(){
var testInput=$("#input_title").val();
$("#list_showStudent").bootstrapTable('refresh',{url:"selectStudent",query:{testInput:testInput}});
});
好了,demo的代碼都給了,有錯誤請自行解決,
其他:自定義錯誤頁面
1、在templates加一個錯誤頁面,我的是:error/error.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>404</title> </head> <body style="text-align: center;"> <h2>啊,頁面出錯了!404!</h2> <span style="color:red;">——來自異世界的客戶端!</span> </body> </html>
2、自定義一個控制類,實現ErrorController接口,
設置頁面跳轉ok
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Created by Administrator on 2018/6/18 0018.
*/
@Controller
public class ErrorIndexController implements ErrorController{
@Override
@RequestMapping(value = "/error")
public String getErrorPath() {
return "error/error";
}
/* @RequestMapping
public String error() {
return getErrorPath();
}*/
}
框架搭建完成,自行規範優化代碼,美化頁面,
有致命報錯或者意見,請到羣裏去找我,博客左邊有鏈接,
歡迎各位的指點,後期會出第三篇,繼續完善這個框架