制作留言板
1.用session存取数据
(1)MessageController
package com.example.message.controller;
import com.example.message.entity.Message;
import com.example.message.util.Result;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/message")
public class MessageController {
@PostMapping("/insert")
public Result insert(Message message, HttpServletRequest request){
List<Message> messageList = (List<Message>)request.getSession().getAttribute("list");
if(messageList == null){
messageList = new ArrayList<>();
}
messageList.add(message);
request.getSession().setAttribute("list",messageList);
System.out.println(message);
return Result.success();
}
@GetMapping("/getAll")
public Result getAll(HttpServletRequest request){
List<Message> messageList = (List<Message>)request.getSession().getAttribute("list");
return Result.success(messageList);
}
}
(2)Message实体
package com.example.message.entity;
import lombok.Data;
@Data
public class Message {
private String author;
private String content;
private String date;
}
(3)工具类Result
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Result<T> {
private Integer code;
private String message;
private Object data;
public Result() {
this.code = 200;
this.message = "操作成功";
}
/**
* 用于@valid错误处理
*
* @param code 错误码
* @param message 错误提示信息
*/
public Result(Integer code, String message) {
this.code = code;
this.message = message;
}
/**
* 用于封装返回数据
*
* @param code 返回码
* @param message 提示信息
*/
public Result(Integer code, String message, Object data) {
this.code = code;
this.message = message;
this.data = data;
}
//系统错误
public static Result<String> error(String message) {
return new Result<>(400, message);
}
//操作成功,返回数据
public static Result<Object> success(Object data) {
return new Result<>(200, "success", data);
}
//操作成功,无返回数据
public static Result<Object> success() {
return new Result<>(200, "success");
}
//操作失败,返回数据
public static Result<Object> fail(Object data) {
return new Result<>(200, "fail", data);
}
//操作失败,无返回数据
public static Result<Object> fail() {
return new Result<>(200, "fail");
}
}
(4)静态页
<!DOCTYPE html>
<html lang="en">
<head>
<title>留言板</title>
<meta charset="UTF-8">
<style>
div {
margin: 0;
padding: 0;
font-size: 12px;
margin: 0 auto;
}
h3 {
text-align: center
}
#container {
width: 500px;
}
.article {
border: 1px solid #a6cbe7;
margin-top: 5px;
}
.author {
background-color: #0099FF;
width: 100%;
height: 24px;
line-height: 24px;
}
.content {
height: 40px;
padding: 10px;
}
.author span {
float: right;
padding-right: 10px;
}
.time {
border-top: solid 1px #a6cbe7;
}
.page {
text-align: right;
height: 30px;
line-height: 30px;
padding-right: 10px;
}
</style>
<script src="js/jquery-3.5.1.js"></script>
<script src="js/vue.js"></script>
<script>
function todate(num) {
if(num<10) return '0'+ num;
else return num;
}
$(function (){
//1、获得数据
$.getJSON("/message/getAll",function (result){
vm.msgs = result.data;
});
//2、展示数据
let vm = new Vue({
el:"#container",
data:{
msgs : [],
}
});
$("#publish").click(function(){
var dateobject = new Date();
var year = dateobject.getFullYear();
var month = todate(dateobject.getMonth()+1);
var date = todate(dateobject.getDate());
var hour = todate(dateobject.getHours());
var minute = todate(dateobject.getMinutes());
var second =todate(dateobject.getSeconds());
var dateTime = year + "年" + month + "月" + date + "日" +hour + ":" + minute + ":" + second;
// console.log(dateTime);
$.ajax({
//请求地址
url : "/message/insert",
//请求方式
type : "post",
//提交数据 json字符串
data : {author: $("input:text").val(),content:$("textarea").val(),date:dateTime},
//
//返回值类型
dataType : "json",
//请求成功
success : function(result) {
console.log(result);
console.log(result.message);
}
})
window.location.reload();
});
});
</script>
</head>
<body>
<div id="container">
<div><h3>留言板</h3></div>
<div>
<div class="article" v-for="msg in msgs" >
<div class="author">用户:{{msg.author}}<span id="addFloor">1#</span></div>
<div class="content">{{msg.content}}</div>
<div class="time page">发表于:{{msg.date}}</div>
</div>
</div>
<div class="page">
<input class="btn1" type="button" value="上一页" onClick="">
<input class="btn2" type="button" value="下一页" onClick="">
</div><br>
<div>
<form>
<div>
用户: <input type="text" name="author" value=""/>
</div><br>
<div>
留言: <textarea name="message" rows="5" cols="72"></textarea>
</div>
<div align="center"><input type="reset" value="清除"/> <input type="button" value="发表" id="publish"/></div>
</form>
</br>
</br>
</br>
</div>
</div>
</body>
</html>
(5)效果图
(6)存在的问题 每次都会创建一个session,无法使楼层自增,所以用数据库来存取数据
2.用mysql数据库
(1)连接数据库并配置application.properties文件,修改后缀为yml
#连接池配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 990731
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
#日期格式
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
#mybatis配置
mybatis:
configuration:
map-underscore-to-camel-case: true
#showSql
logging:
level:
org.lanqiao.book21.dao: debug
(2)添加依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
(3)MessageDao
package com.example.message.dao;
import com.example.message.entity.Message;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface MessageDao {
@Insert("insert into message(author,content,date) values(#{author},#{content},#{date})")
//将数据库中的id回调
@Options(useGeneratedKeys = true,keyColumn="id")
public void insert(Message message);
@Select("select * from message")
public List<Message> getAll();
}
(4)MessageService
package com.example.message.service;
import com.example.message.entity.Message;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface MessageService {
public void insert(Message message);
public List<Message> getAll();
}
(5)MessageServiceImpl
package com.example.message.service.impl;
import com.example.message.dao.MessageDao;
import com.example.message.entity.Message;
import com.example.message.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
@Service
public class MessageServiceImpl implements MessageService {
@Autowired
MessageDao messageDao;
@Override
public void insert(Message message) {
message.setDate(new Date());
messageDao.insert(message);
}
@Override
public List<Message> getAll() {
return messageDao.getAll();
}
}
(6)MessageController
package com.example.message.controller;
import com.example.message.entity.Message;
import com.example.message.service.MessageService;
import com.example.message.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/message")
public class MessageController {
@Autowired
MessageService messageService;
@PostMapping("/insert")
public Result insert(Message message){
messageService.insert(message);
return Result.success(message);
}
@GetMapping("/getAll")
public Result getAll(){
return Result.success(messageService.getAll());
}
}
3.增加翻页功能
(1)增加依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<scope>1.2.13</scope>
</dependency>
(2)修改MessageController.java里的getAll方法
@GetMapping("/getAll")
public Result getAll(int pageNum,int pageSize){
PageHelper.startPage(pageNum,pageSize);
List<Message> messageList = messageService.getAll();
PageInfo<Message> pageInfo = new PageInfo<>(messageList);
return Result.success(pageInfo);
(3)修改html
$(function (){
const pageSize =5;
let nextPage;
let prePage;
//获得数据
function getPage(num,size){
$.getJSON("/message/getAll",{pageNum:num,pageSize:size},function (result){
vm.msgs = result.data.list;
nextPage = result.data.nextPage;
prePage = result.data.prePage;
});
}
//第一页
getPage(1,pageSize);
//展示数据
let vm = new Vue({
el:"#container",
data:{
msgs : [],
}
});
$("#publish").click(function(){
$.ajax({
//请求地址
url : "/message/insert",
//请求方式
type : "post",
//提交数据 json字符串
data : {author: $("input:text").val(),content:$("textarea").val()},
//
//返回值类型
dataType : "json",
//请求成功
success : function(result) {
vm.msgs.push(result.data);
$("input:text").val("");
$("textarea").val();
}
})
});
$(".btn1").click(function(){
if(prePage!=0) getPage(prePage,pageSize);
else alert("已经是第一页");
});
$(".btn2").click(function(){
if(nextPage!=0) getPage(nextPage,pageSize);
else alert("已经是最后一页");
});
});
4动态查找
(1)修改MessageDao
@Select("<script>select * from message"+
"<where>"+
"<if test=\"author!=null and author!=''\">"+
"author=#{author}"+
"</if>"+
"<if test=\"content!=null and content!=''\">"+
"and content like '%' #{content} '%'"+
"</if>"+
"</where>"+
"</script>")
public List<Message> getBySearch(Message message);
(2)修改MessageService
public List<Message> getBySearch(Message message);
(3)修改MessageServiceImp
@Override
public List<Message> getBySearch(Message message) {
return messageDao.getBySearch(message);
}
(4)修改MessageController
@PostMapping("/getBySearch")
public Result getBySearch(Message message,int pageNum,int pageSize){
PageHelper.startPage(pageNum,pageSize);
List<Message> messageList = messageService.getBySearch(message);
PageInfo<Message> pageInfo = new PageInfo<>(messageList);
return Result.success(pageInfo);
}
(5)html
<script>
$(function (){
let size =2;
let num =1;
let nextPage;
let prePage;
let url = "/message/getAll";
let obj = {pageNum:num,pageSize:size}
//获得数据
function getPage(url,obj){
$.post(url,obj,function (result){
vm.msgs = result.data.list;
nextPage = result.data.nextPage;
prePage = result.data.prePage;
},"json");
}
//第一页
getPage(url,obj);
//展示数据
let vm = new Vue({
el:"#container",
data:{
msgs : [],
}
});
$("#publish").click(function(){
$.ajax({
//请求地址
url : "/message/insert",
//请求方式
type : "post",
//提交数据 json字符串
data : {author: $(".author").val(),content:$("textarea").val()},
//
//返回值类型
dataType : "json",
//请求成功
success : function(result) {
vm.msgs.push(result.data);
$("input:text").val("");
$("textarea").val();
}
})
});
$("#search").click(function(){
url = "/message/getBySearch";
obj = {author:$("input[name=author]").val(),content:$("input[name=content]").val(),pageNum:num,pageSize:size};
getPage(url,obj);
});
$(".btn1").click(function(){
if(prePage!=0) {
obj.pageNum = prePage;
getPage(url, obj);
}
else {
{
alert("已经是第一页");
}
}
});
$(".btn2").click(function(){
if(nextPage!=0) {
obj.pageNum = nextPage;
getPage(url, obj);
}
else {
{
alert("已经是最后一页");
}
}
});
});
</script>
</head>
<body>
<div id="container">
<div><h3>留言板</h3></div>
<div>
用户:<input type="text" name="author"> 留言:<input type="text" name="content">
<input id="search" type="button" value="搜索">
<div class="article" v-for="msg in msgs" >
<div class="author">用户:{{msg.author}}<span id="addFloor">{{msg.id}}</span></div>
<div class="content">{{msg.content}}</div>
<div class="time page">"发表于:"{{msg.date}}</div>
</div>
</div>
<div class="page">
<input class="btn1" type="button" value="上一页" onClick="">
<input class="btn2" type="button" value="下一页" onClick="">
</div><br>
<div>
<form>
<div>
用户: <input type="text" name="author" value=""/>
</div><br>
<div>
留言: <textarea name="message" rows="5" cols="72"></textarea>
</div>
<div align="center"><input type="reset" value="清除"/> <input type="button" value="发表" id="publish"/></div>
</form>
</br>
</br>
</br>
</div>
</div>
</body>
ljm要加油