留言板可以增删改查,以及拥有审核状态
数据库
package com.xj.model.message;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.sql.Timestamp;
//##############一定要写 很重要!!!
@Entity
//##############这个是数据库的名字
@Table(name = "mes")
public class Message {
private String id;
private String liuyan;
private String ip;
private String date;
private String title;
private String state;
//##########审核的状态
public static String 审核成功= "on";
public static String 审核中 = "off";
//##############设置主键
@Id
//##############Column用来标识实体类中属性与数据表中字段的对应关系
@Column(name = "id", unique = true, nullable = false, length = 36)
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Column(name = "title",length = 36)
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Column(name="liuyan",length = 36)
public String getLiuyan() {
return liuyan;
}
public void setLiuyan(String liuyan) {
this.liuyan = liuyan;
}
@Column(name = "ip",length = 36)
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
@Column(name="date")
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
@Column(name="state")
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
1.获取列表/查
JSP文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<script type="text/javascript">
$(function () {
<!--初始化message-table 和最后一行对应名字-->
$('#message-table').datagrid({
url: "${pageContext.request.contextPath}/a/getMessageList.action",
singleSelect: true,
pagination: true,
fitColumns: true,
pageSize: 20,
pageList: [20, 50, 100],
nowrap: true,
border: false,
idField: 'id',
toolbar: [{
<!--一个添加按钮-->
text: '添加',
iconCls: 'icon-search',
handler: function () {
addMessage();
}
}],
columns: [[{
<!--和model(数据库)相同,必须!-->
field: 'id',
title: 'id'
}, {
field:'liuyan',
title:'留言'
},{
field:'title',
title:'主题'
},{
field: 'date',
title: '时间'
}, {
field: 'ip',
title: 'IP地址'
},{
field:'state',
title:'状态',
formatter: function (value, rowData) {
if ('on' == value) {
if (rowData.endTime && (new Date().getTime() > new Date(rowData.endTime).getTime())) {
return '<span style="color:red;">审核成功</span>';
} else {
return '<span style="color:#1abc9c;">审核成功</span>';
}
} else if ('off' == value) {
return '<span style="color:grey;">审核中</span>';
} else {
return '<span style="color:red;">未知</span>';
}
}
},{
title: '操作',
formatter: function (value, rowData) {
var src = '';
src = "<button type='button' onclick='updateMessage(\"" + rowData.id + "\")' class='btn btn-primary btn-sm btnstype btnstyle1'>修改</button> ";
src += "<button type='button' onclick='delMessage(\"" + rowData.id + "\",\"" + rowData.areaCode + "\")' class='btn btn-primary btn-sm btnstype btnstyle1'>删除</button> ";
if ('on' == rowData.state) {
src += "<button type='button' onclick='shenhe(\"" + rowData.id + "\",\"" + rowData.liuyan + "\",\"" + rowData.state + "\")' class='btn btn-primary btn-sm btnstype btnstyle5' style='color: red;'>审核成功</button> ";
} else {
src += "<button type='button' onclick='shenhe(\"" + rowData.id + "\",\"" + rowData.liuyan + "\",\"" + rowData.state + "\")' class='btn btn-primary btn-sm btnstype btnstyle5' style='color: green;'>审核中</button> ";
}return src;
}
}]]
});
});
</script>
<!--和前面初始化-->
<table id="message-table"></table>
java
//用于调用 获取列表
@RequestMapping("/getMessageList")
public void getMessageList() {
Message message=new Message();
Map<String, Object> returnMap = new HashMap<>();
//行数和页数
String p = req.getParameter("page");
String r = req.getParameter("rows");
try {
int page = Integer.parseInt(p);
int rows = Integer.parseInt(r);
Map<String, Object> params = new HashMap<>();
Map<String, String> conditions = new HashMap<>();
//查询列表 分页
List<Message> messageList = messageBaseService.getObjcetPagination(Message.class, params, conditions, page, rows, "order by id");
long num = messageBaseService.getObjectNum(Message.class, params, conditions);
returnMap.put("total", num);
returnMap.put("rows", messageList);
} catch (Exception e) {
logger.error("在获取材质列表时出现错误", e);
returnMap.put("msg", "系统繁忙,请稍后再试");
}
super.writeToJson(returnMap);
}
@RequestMapping("/getMessageById")
public void getMessageById(Message message) {
Json json = new Json();
//查询用的
String mesType = req.getParameter("mesType");
try {
Map<String, Object> returnMap = new HashMap<>();
Message mes=null;
//获取信息
List<Map<String, String>> mapList = new ArrayList<>();
if (StringUtils.isObjectNotEmpty(mes) && StringUtils.isObjectNotEmpty(mes.getId())) {
Map<String, String> map = new HashMap<>();
map.put("id", mes.getId());
map.put("liuyan", mes.getLiuyan());
map.put("title", mes.getTitle());
map.put("date", mes.getDate());
map.put("ip", mes.getIp());
map.put("state",mes.getState());
map.put("chooseStatus", "true");
mapList.add(map);
}
Map<String, Object> params = new HashMap<>();
String hql = "FROM mes WHERE id IS NULL";
hql += " order by id";
List<Message> messageList = messageBaseService.find(hql, params);
returnMap.put("mcList", mapList);
json.setObj(returnMap);
json.setSuccess(true);
} catch (Exception e) {
logger.error("获取分类时出现错误", e);
json.setMsg("系统繁忙,请稍后再试");
}
super.writeToJson(json);
}
2.增加
jsp
function addMessage() {
$('<div id="add-message"/>').dialog({
//是JSP取得绝对路径的方法
href: '${pageContext.request.contextPath}/message_info.jsp',
width: 450,
height: 200,
modal: true,
title: '新增留言',
buttons: [{
text: '添加',
iconCls: 'icon-add',
handler: function () {
//获得id
var d = $("#" + this.id);
$.ajax({
type: "POST",
url: "${pageContext.request.contextPath}/a/addMessage.action",
dataType: "json",
//点击前
beforeSend: function () {
//进行表单字段验证,当全dao部字段都有效版时返回 true,否则权返回false,可用于阻止提交动作
var isValid = $("#message-info-form").form('validate');
if (isValid) {
//进度条
$.messager.progress({
text: "添加数据,请等待..."
});
}
return isValid;
},
//方法通过序列化表单值
data: $("#message-info-form").serialize(),
error: function (info) {
$.messager.progress('close');
var pattern = /<script[^>]*>((.|[\n\r])*)<\/script>/im;
//exec一次只会匹配符合条件的一项,每次调用则会在字符串中继续寻找
var matches = pattern.exec(info.responseText);
eval(matches[1]);
},
success: function (result) {
$.messager.show({
msg: result.msg,
title: '提示'
});
$.messager.progress('close');
if (result.success) {
//表单更新
$('#message-table').datagrid('reload');
d.dialog('destroy');
}
}
});
}
}],
onClose: function () {
$(this).dialog('destroy');
}
});
}
java文件
@RequestMapping("/addMessage")
//传Message 值,如果是Message mes=new Message();则mes为空
public void addMessage(Message pmes){
Json json = new Json();
try {
//.trim()去除字符串两端的空白字符。
if (StringUtils.isObjectEmpty(pmes.getLiuyan()) || StringUtils.isObjectEmpty(pmes.getLiuyan().trim())) {
json.setMsg("请输入留言:");
super.writeToJson(json);
return;
}
if (StringUtils.isObjectEmpty(pmes.getTitle()) || StringUtils.isObjectEmpty(pmes.getTitle().trim())) {
json.setMsg("请输入标题:");
super.writeToJson(json);
return;
}
Message message=new Message();
BeanUtils.copyProperties(pmes,message);//将pmes的值拷贝到message
//随机32位id
message.setId(UUID.randomUUID().toString());
//日期
Date d=new Date();
SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
message.setDate(formatter.format(d));
//状态
message.setState("审核中");
//地址
message.setIp(Inet4Address.getLocalHost().getHostAddress());
messageBaseService.add(message);
json.setMsg("添加成功");
json.setSuccess(true);
} catch (Exception e) {
logger.error("在添加留言时出现错误", e);
json.setMsg("系统繁忙,请稍后再试");
}
super.writeToJson(json);
}
3.删除
jsp
function delMessage(id,liuyan) {
$.messager.confirm('提示', "确定要删除“" + id + "”吗", function (r) {
if (r) {
$.ajax({
type: "POST",
url: "${pageContext.request.contextPath}/a/deteleMessage.action",
dataType: "json",
beforeSend: function () {
$.messager.progress({
text: "删除数据,请等待..."
});
},
data: "id=" + id,
success: function (result) {
if (result.success) {
$("#message-table").datagrid('reload');
}
$.messager.show({
msg: result.msg,
title: '提示'
});
$.messager.progress('close');
}
});
}
});
}
java
@RequestMapping("/deteleMessage")
public void deteleMessage(Message pmessage) {
Json json = new Json();
try {
if (StringUtils.isObjectsNotEmpty(pmessage.getId())) {
Message message = messageBaseService.get(Message.class, pmessage.getId());
if (StringUtils.isObjectNotEmpty(message)) {
messageBaseService.delete(message);
json.setSuccess(true);
json.setMsg("删除成功");
} else {
json.setMsg("没有该l留言信息");
}
} else {
json.setMsg("缺少信息,请刷新重试");
}
} catch (Exception e) {
logger.error("留言信息出现错误 ", e);
json.setMsg("系统繁忙,请稍后再试");
}
super.writeToJson(json);
}
4.改
jsp
function updateMessage(id) {
$('<div id="update-message-code"/>').dialog({
href: '${pageContext.request.contextPath}/message_info.jsp',
width: 450,
height: 200,
modal: true,
title: '修改留言',
buttons: [{
text: '修改',
iconCls: 'icon-save',
handler: function () {
var d = $("#" + this.id);
$.ajax({
type: "POST",
url: "${pageContext.request.contextPath}/a/updateMessage.action",
dataType: "json",
beforeSend: function () {
var isValid = $("#message-info-form").form('validate');
if (isValid) {
$.messager.progress({
text: "修改数据,请等待..."
});
}
return isValid;
},
data: $("#message-info-form").serialize() + "&id=" + id,
error: function (info) {
$.messager.progress('close');
var pattern = /<script[^>]*>((.|[\n\r])*)<\/script>/im;
var matches = pattern.exec(info.responseText);
},
success: function (result) {
$.messager.show({
msg: result.msg,
title: '提示'
});
$.messager.progress('close');
if (result.success) {
$('#message-table').datagrid('reload');
d.dialog('destroy');
}
}
});
}
}],
//页面跳转马上
onLoad: function () {
$.ajax({
type: "post",
dataType: "json",
url: "${pageContext.request.contextPath}/a/updateMessage.action",
data: "id=" + id,
//在用ajax请求时,没有返回前会出现前出现一个转动的loading小图标或者“内容加载中…”,用来告知用户正在请求数据。
beforeSend: function () {
$.messager.progress({
text: "加载数据,请等待..."
});
},
//成功以后
success: function (result) {
$.messager.show({
msg: result.msg,
title: '提示'
});
$.messager.progress('close');
if (result.success) {
$('#message-table').datagrid('reload');
d.dialog('destroy');
}
}
});
},
onClose: function () {
$(this).dialog('destroy');
}
});
}
java
@RequestMapping("/updateMessage")
public void updateMessage(Message pmessage) {
Json json = new Json();
try {
if (StringUtils.isObjectsNotEmpty(pmessage.getId())) {
Message message = messageBaseService.get(Message.class, pmessage.getId());
if (StringUtils.isObjectEmpty(message)) {
json.setMsg("没有留言信息");
super.writeToJson(json);
return;
}
//id的值不变
BeanUtils.copyProperties(pmessage, message, "id");
//id
message.setId(pmessage.getId());
//date
SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
Date date = new Date();
message.setDate(formatter.format(date));
//ip
message.setIp(Inet4Address.getLocalHost().getHostAddress());
message.setState("审核成功");
messageBaseService.update(message);
json.setMsg("修改成功");
json.setSuccess(true);
} else {
json.setMsg("缺少信息,请刷新重试");
}
} catch (Exception e) {
logger.error("在修改时出现错误", e);
json.setMsg("系统繁忙,请稍后再试");
}
super.writeToJson(json);
}