通过eclipse + Jsp+Servlet+MySql+bootstrap设计实现,功能比较简单。
博客分为游客跟管理员,游客只能查看文章不能修改。管理员能对本人的文章还有用户的增删查改。
管理员可以通过登录注册方式进入管理界面可以管理文章信息,用户信息,等信息。实现了分页查询,添加信息、修改信息、删除信息、选中删除等功能,下面是运行的界面:
文章来源:https://www.toymoban.com/news/detail-504461.html
文章来源地址https://www.toymoban.com/news/detail-504461.html
package controller;
import java.io.IOException;
import java.sql.Date;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import dao.ArticleDao;
import dao.UserDao;
import dao.impl.ArticleDaoImpl;
import dao.impl.UserDaoImpl;
import domain.Article;
import domain.User;
import utils.JsonModel;
import utils.JsonUtil;
@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
private ArticleDao articleDao = new ArticleDaoImpl();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
System.out.println("action=" + action);
if ("getAllBlog".equals(action)) { // 查询所有博客信息
try {
allBlogInfo(request, response);
} catch (SQLException e) {
e.printStackTrace();
}
} else if ("deleteBlog".equals(action)) { // 删除博客
try {
deleteBlog(request, response);
} catch (SQLException e) {
e.printStackTrace();
}
} else if ("updateBlog".equals(action)) { // 修改博客信息
try {
updateBlog(request, response);
} catch (SQLException | ParseException e) {
e.printStackTrace();
}
} else if ("addBlog".equals(action)) { //添加博客
try {
addBlog(request, response);
} catch (SQLException | ParseException e) {
e.printStackTrace();
}
}
}
// 添加用戶
private void addBlog(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException, ServletException, ParseException {
String title = request.getParameter("title");
String content = request.getParameter("content");
String time = request.getParameter("time");
String author = request.getParameter("author");
HttpSession session = request.getSession();
String username = (String) session.getAttribute("username"); // 登录的适合已经设置过了
//String转化为java.sql.Date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
java.sql.Date sDate = null;
java.util.Date date3 = sdf.parse(time);
sDate = new java.sql.Date(date3.getTime());
UserDao userDao = new UserDaoImpl();
int userid = userDao.selectUser(username); // 获取用户id 好给文章分主人
Article article = new Article(userid, sDate,title, author, content);
int flag = articleDao.createBlog(article); // 更新操作,成功返回1,失败为0
// System.out.println(flag);
// 更新是否成功
if(flag > 0) {
response.sendRedirect(request.getContextPath()+"/edit_blog.jsp");
} else {
request.setAttribute("msg", "添加博客失败!");
request.getRequestDispatcher("/error.jsp").forward(request, response);
}
}
/**
* 更新用户信息
*/
private void updateBlog(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException, ServletException, ParseException {
int id = Integer.parseInt(request.getParameter("id").trim()); // 获取文章编号
String title = request.getParameter("title");
String content = request.getParameter("content");
String author = request.getParameter("author");
String time = request.getParameter("time");
//String转化为java.sql.Date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
java.sql.Date sDate = null;
java.util.Date date3 = sdf.parse(time);
sDate = new java.sql.Date(date3.getTime());
Article article = new Article(id, title, content, author, sDate);
int flag = articleDao.updateBlog(article); // 更新操作,成功返回1,失败为0
// 更新是否成功
if(flag > 0) {
response.sendRedirect(request.getContextPath()+"/edit_blog.jsp");
} else {
request.setAttribute("msg", "修改失败!");
request.getRequestDispatcher("/error.jsp").forward(request, response);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
// 查询所有文章信息
public void allBlogInfo(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
List<Article> list = articleDao.selectAllBlogs();
JsonModel<List<Article>> jsonModel = new JsonModel<>();
if(list==null) {
jsonModel.setCode(0);
jsonModel.setMsg("error...");
}else {
jsonModel.setCode(1);
jsonModel.setMsg("success...");
jsonModel.setRows(list);
jsonModel.setTotal(list.size());
}
response.getWriter().println(JsonUtil.toJSONString(jsonModel.getRows()));
}
// 删除文章
public void deleteBlog(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
Integer blog_id = Integer.parseInt(request.getParameter("blogID"));
JsonModel<List<Article>> jsonModel = new JsonModel<>();
int flag = articleDao.delectBlog(blog_id); // 通过文章编号删除,不是用户id
// 删除是否成功
if(flag > 0) {
jsonModel.setCode(1);
jsonModel.setMsg("delete success");
} else {
jsonModel.setCode(0);
jsonModel.setMsg("delete error");
}
response.getWriter().println(jsonModel);
}
}
package controller;
import javax.servlet.*;
import javax.servlet.http.*;
import dao.UserDao;
import dao.impl.UserDaoImpl;
import domain.User;
import utils.JsonModel;
import utils.JsonUtil;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
@WebServlet("/user")
public class UserServlet extends HttpServlet {
private UserDao userDao = new UserDaoImpl();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
System.out.println("action=" + action);
if ("getAllUser".equals(action)) { // 查询所有用户信息
try {
allUserInfo(request, response);
} catch (SQLException e) {
e.printStackTrace();
}
} else if ("deleteUser".equals(action)) { // 删除用户
try {
deleteUser(request, response);
} catch (SQLException e) {
e.printStackTrace();
}
} else if ("updateUser".equals(action)) { // 修改用户信息
try {
updateUser(request, response); // 更新用户信息
} catch (SQLException e) {
e.printStackTrace();
}
} else if ("loginUser".equals(action)) { // 登录操作
try {
login(request, response);
} catch (SQLException e) {
e.printStackTrace();
}
}else if ("addUser".equals(action)) { // 登录操作
try {
addUser(request, response);
} catch (SQLException e) {
e.printStackTrace();
}
}else if ("regUser".equals(action)) { // 登录操作
try {
regUser(request, response);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// 添加用戶
private void addUser(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException, ServletException {
String userName = request.getParameter("username");
String password = request.getParameter("password");
String sex = request.getParameter("sex");
String email = request.getParameter("email");
String info = request.getParameter("info");
User user = new User(userName, password, sex, email, info);
int flag = userDao.AddUser(user); // 更新操作,成功返回1,失败为0
// 更新是否成功
if(flag > 0) {
response.sendRedirect(request.getContextPath()+"/edit_user.jsp");
} else {
request.setAttribute("msg", "添加用戶失败!");
request.getRequestDispatcher("/error.jsp").forward(request, response);
}
}
// 注册
private void regUser(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException, ServletException {
String userName = request.getParameter("username");
String password = request.getParameter("password");
String sex = request.getParameter("sex");
String email = request.getParameter("email");
String info = request.getParameter("info");
User user = new User(userName, password, sex, email, info);
int flag = userDao.AddUser(user); // 更新操作,成功返回1,失败为0
// 更新是否成功
if(flag > 0) {
response.sendRedirect(request.getContextPath()+"/login.jsp");
} else {
request.setAttribute("msg", "添加用戶失败!");
request.getRequestDispatcher("/error.jsp").forward(request, response);
}
}
/**
* 更新用户信息
*/
private void updateUser(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException, ServletException {
int id = Integer.parseInt(request.getParameter("id").trim());
String userName = request.getParameter("username");
String password = request.getParameter("password");
String sex = request.getParameter("sex");
String email = request.getParameter("email");
String info = request.getParameter("info");
User user = new User(id, userName, password, sex, email, info);
int flag = userDao.updateUser(user); // 更新操作,成功返回1,失败为0
// 更新是否成功
if(flag > 0) {
response.sendRedirect(request.getContextPath()+"/edit_user.jsp");
} else {
request.setAttribute("msg", "修改失败!");
request.getRequestDispatcher("/error.jsp").forward(request, response);
}
}
/**
* 登录
*/
private void login(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException, ServletException {
String userName = request.getParameter("username");
String password = request.getParameter("password");
System.out.println(userName + " " + password + " ");
String pwd = userDao.loginUser(userName); // 返回值是一个String密码
HttpSession session = request.getSession();
// 判断数据库返回的密码是否跟用户输入的一致
if (pwd.equals(password)) {
System.out.println("登录成功!");
session.setAttribute("username", userName);
// 说明找到了用户名对应的密码,现在判断,跳转相应权限页面
response.sendRedirect(request.getContextPath()+"/index.jsp");
} else { // 两个密码不相同 登录失败
System.out.println("登录失败!");
response.setCharacterEncoding("utf-8");
session.setAttribute("isLogin", "0"); // 1为已登录, 0为还未登录
request.setAttribute("msg", "登录失败!请检查账号密码是否正确!");
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
// 查询所有用户信息
public void allUserInfo(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
List<User> list = userDao.selectAllUsers();
JsonModel<List<User>> jsonModel = new JsonModel<>();
if(list==null) {
jsonModel.setCode(0);
jsonModel.setMsg("error...");
}else {
jsonModel.setCode(1);
jsonModel.setMsg("success...");
jsonModel.setRows(list);
jsonModel.setTotal(list.size());
}
response.getWriter().println(JsonUtil.toJSONString(jsonModel.getRows()));
}
// 删除用户
public void deleteUser(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
Integer userId = Integer.parseInt(request.getParameter("userID"));
JsonModel<List<User>> jsonModel = new JsonModel<>();
int flag = userDao.deleteUser(userId);
// 删除是否成功
if(flag > 0) {
userDao.deleteUser(userId);
jsonModel.setCode(1);
jsonModel.setMsg("delete success");
} else {
jsonModel.setCode(0);
jsonModel.setMsg("delete error");
}
response.getWriter().println(jsonModel);
}
}
package dao.impl;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import dao.UserDao;
import domain.Article;
import domain.User;
import utils.BaseDao;
import utils.JDBCUtil;
public class UserDaoImpl extends BaseDao implements UserDao{
@Override
public List<User> selectAllUsers() throws SQLException {
String sql = "select * from user";
User user=null;
List<User> list = new ArrayList<>();
ResultSet resultSet = this.executeQuery(sql);
while(resultSet.next()) {
user = new User();
// 从结果集中,每次遍历给user对象赋值
user.setId(Integer.parseInt(resultSet.getString("id")));
user.setUsername(resultSet.getString("username"));
user.setPassword(resultSet.getString("password"));
user.setInfo(resultSet.getString("info"));
user.setEmail(resultSet.getString("email"));
user.setSex(resultSet.getString("sex"));
list.add(user); // 一个一个实体传入列表里
}
return list; // 返回User类型的列表数据
}
@Override
public String loginUser(String username) throws SQLException {
String sql = "select password from user where username=?";
String pwd=null;
ResultSet resultSet = this.executeQuery(sql, username);
while (resultSet.next()) {
pwd = resultSet.getString("password"); // 获取查询到的密码
}
return pwd;
}
public int selectUser(String username) throws SQLException {
String sql = "select id from user where username=?";
int id = 0;
ResultSet resultSet = this.executeQuery(sql, username);
while (resultSet.next()) {
id = resultSet.getInt("id"); // 获取查询到的密码
}
return id;
}
@Override
public int AddUser(User user) throws SQLException {
String sql = "insert into user(username, password, info, sex, email) values(?,?,?,?,?)";
int flag = this.executeUpdate(sql, user.getUsername(), user.getPassword(), user.getInfo(), user.getSex(), user.getEmail());
return flag;
}
@Override
public int deleteUser(Integer userID) throws SQLException {
String sql = "delete from user where id=?";
int flag = this.executeUpdate(sql, userID);
return flag;
}
@Override
public User selectByName(String username) throws SQLException {
String sql = "select * from user where username=?";
User user = null;
ResultSet resultSet = this.executeQuery(sql, username);
while(resultSet.next()) {
user = new User();
user.setId(Integer.parseInt(resultSet.getString("id")));
user.setUsername(resultSet.getString("username"));
user.setPassword(resultSet.getString("password"));
user.setInfo(resultSet.getString("info"));
user.setEmail(resultSet.getString("email"));
user.setSex(resultSet.getString("sex"));
}
return user; // 返回User类型的列表数据
}
@Override
public int updateUser(User user) throws SQLException {
String sql = "update user set username=?, password=?, email=?, info=?, sex=? where id=?;";
int flag = this.executeUpdate(sql, user.getUsername(), user.getPassword(), user.getEmail(), user.getInfo(), user.getSex(), user.getId());
return flag;
}
}
package utils;
public class JsonModel<T>{
private int code;
private String msg;
private long total;
private T rows;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
public T getRows() {
return rows;
}
public void setRows(T rows) {
this.rows = rows;
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>内容页</title>
<link rel="stylesheet" type="text/css" href="./css/bootstrap.min.css"></link>
<link rel="stylesheet"
href="https://unpkg.com/bootstrap-table@1.15.3/dist/bootstrap-table.min.css">
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="./js/bootstrap.min.js"></script>
<script
src="https://unpkg.com/bootstrap-table@1.15.3/dist/bootstrap-table.min.js"></script>
<script
src="https://unpkg.com/bootstrap-table@1.15.3/dist/locale/bootstrap-table-zh-CN.min.js"></script>
</head>
<body>
<div class="container">
<!-- 博客管理 -->
<div class="container-fluid">
<div class="alert alert-info" id="examplebtTableEventsResult"
role="alert">
<h3 class="text-center">博客管理....</h3>
</div>
<a href="addBlog.jsp" class="btn btn-primary">添加博客</a>
<a href="index.jsp" class="btn btn-info">返回主页</a>
<table id="exampleTableEvents" data-height="" style="height: 100px;"
data-show-refresh="true" data-mobile-responsive="true"
data-page-size="" data-pagination="true" data-toggle="table">
</table>
</div>
<!-- 模态框 data-toggle="modal" data-target="#myModal" -->
<div class="modal fade" data-backdrop="static" id="myModal"
tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">编辑博客信息</h4>
</div>
<div class="modal-body">
<!-- 表单 -->
<form class="form-horizontal" action="blog?action=updateBlog"
method="post">
<div class="form-group">
<label for="username" class="col-sm-2 control-label">编号:</label>
<div class="col-sm-10">
<input type="text" id="id" name="id" class="form-control">
</div>
</div>
<div class="form-group">
<label for="title" class="col-sm-2 control-label">文章标题</label>
<div class="col-sm-10">
<input type="text" id="title" name="title" class="form-control">
</div>
</div>
<div class="form-group">
<label for="author" class="col-sm-2 control-label">作者</label>
<div class="col-sm-10">
<input type="text" id="author" name="author"
class="form-control">
</div>
</div>
<div class="form-group">
<label for="time" class="col-sm-2 control-label">发布时间</label>
<div class="col-sm-10">
<input type="text" name="time" class="form-control" id="time">
</div>
</div>
<div class="form-group">
<label for="content" class="col-sm-2 control-label">文章内容</label>
<div class="col-sm-10">
<textarea class="form-control" id="content" rows="3"
name="content"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="submit" id="sumit_btn" class="btn btn-primary">提交</button>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
// getData方法获取全部页面数据后,将data转为json对象,使用index当前行号作为下标获取对应数据
function EditViewById(index){
var data = JSON.stringify($("#exampleTableEvents").bootstrapTable('getData')); //获取全部数据
// console.log("data:" + data)
var data_json = JSON.parse(data); //data_json和data_json2一样都是json对象
// console.log("data_json:" + data_json);
//由于data2已经是对象了,alert不能显示对象只能显示为[object Object],需要控制台打印
//根据index找到对应行数据,填充数据到修改模态框
// $("#username").val(row);
$("#id").val(data_json[index].id);
$("#title").val(data_json[index].title);
$("#author").val(data_json[index].author);
$("#content").val(data_json[index].content);
$("#time").val(data_json[index].time);
$("#email").val(data_json[index].email);
//弹出修改模态框,非新增模态框
$('#myModal').modal('show');
}
// 展示数据
function listDatas() {
$('#exampleTableEvents').bootstrapTable({
url: 'http://localhost:8081/Blog/blog?action=getAllBlog',
dataType: "json",//数据类型
method: 'GET',
columns: [
{
checkbox: true,
visible: false //是否显示复选框
}, {
field: 'id',
title: '编号'
},{
field: 'title',
title: '文章标题名'
},{
field: 'author',
title: '作者'
},{
field: 'content',
title: '文章内容'
},{
field: 'time',
title: '发布时间'
},{
title: '操作',
formatter: formaterProcess
}],
toolbarAlign: "right", //工具栏对齐方式
sidePagination: "client", //分页方式:client客户端分页,server服务端分页(*)
pagination: true, //是否显示分页(*)
search: true, //是否显示表格搜索,此搜索是客户端搜索,不会进服务端
// showToggle:true, //是否显示详细视图和列表视图的切换按钮
striped: true, //是否显示行间隔色
// clickToSelect: true, //是否启用点击选中行
paginationPreText: "上一页",
paginationNextText: "下一页",
pageSize : 4,//单页记录数
// pageList : [ 5, 10],//可选择单页记录数
// showRefresh: true, //是否显示刷新按钮
uniqueId: "id", //每一行的唯一标识,一般为主键列
onLoadSuccess: function (data) { //加载成功时执行
console.log("加载成功");
console.log(data);
},
onLoadError: function (res) { //加载失败时执行
console.log("加载失败");
},
});
}
listDatas();
function formaterProcess(value, rows, index) {
return '<button class="btn btn-info" onclick="EditViewById('+ index +')">编辑</button>' + ' <button class="btn btn-danger" onclick="deleteBlog('+ rows.id +')">删除</button>';
}
// "<a href='javascript:;' οnclick='deleteMessage("+row.message_number+","+row.approval_status+")'>删除</a>";
// <button class="btn btn-info" οnclick='EditViewById("+row.message_number+","+row.approval_status+")'>编辑</button>
// 删除用户
function deleteBlog(blogID){
if (confirm("确定要删除【" + blogID + "】的用户吗?")) {
$.ajax({
url: 'http://localhost:8081/Blog/blog?action=deleteBlog',
type: 'get',
data: {blogID: blogID},
dataType: 'json',
success: function (res){
// console.log(res)
if(res.code>0) {
$('#exampleTableEvents').bootstrapTable('refresh');
console.log(res.msg);
} else{
bootbox.alert(res.msg);
}
},
})
}
console.log(userID);
}
</script>
</body>
</html>
到了这里,关于Javaweb课程设计(简单的个人博客)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!