好久没写过博客了,今天一个前端同事让帮忙写一个用户登录进去并且能对房间信息进行增删改查的项目,也不打算使用框架,因为懒得配置哈哈,所以就用servlet撸,顺手写篇博客记录一下吧。
页面他已经写完了,所以我只需要提供接口,如果你们需要用到页面,可以百度找一些简单的html页面。
我使用的开发工具是:idea+Navicat
测试工具是:Postman
下面是数据库
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for room_detail
-- ----------------------------
DROP TABLE IF EXISTS `room_detail`;
CREATE TABLE `room_detail` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`room_num` int(11) NULL DEFAULT NULL COMMENT '房间号',
`room_type` varchar(32) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT '房间类型',
`room_price` decimal(10, 2) NULL DEFAULT NULL COMMENT '价钱',
`live_time` varchar(32) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT '入住日期',
`create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建日期',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for room_user
-- ----------------------------
DROP TABLE IF EXISTS `room_user`;
CREATE TABLE `room_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_name` varchar(32) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
`pass_word` varchar(32) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
`create_time` datetime(0) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of room_user
-- ----------------------------
INSERT INTO `room_user` VALUES (1, 'admin', '123456', '2020-04-17 16:44:16');
SET FOREIGN_KEY_CHECKS = 1;
下面是我创建的Javaweb项目,因为不是maven项目,所以需要下载jar包,我把jar包放到网盘里,大家自行下载,最后我会把完整项目都提供给大家,不过我建议大家能够按照顺序阅读博客。
链接:https://pan.baidu.com/s/12T2NFRi7AjMz-QqrdcuGlA
提取码:tzoo如果你是新手小白不太熟练创建Javaweb项目,可以参考这篇博客https://www.cnblogs.com/cangqinglang/p/10027199.html
下面开始编写代码,首先是实体类,这里不多做介绍,普通的get/set方法。
接下来是创建接口,功能很简单,登录、房间信息增删改
package com.lebron.dao;
import com.lebron.entity.RoomUser;
public interface RoomUserDao {
/**
* @param userName、passWord
* @return BookUser
* @Author Lebron
* @Date 2020/4/20 10:40
* @Description 登录 TODO
*/
RoomUser login(String userName, String passWord);
}
房间信息接口
package com.lebron.dao;
import com.lebron.entity.RoomDetail;
import java.util.List;
public interface RoomDetailDao {
/**
* @param keyword 关键字
* @param pageSize 开始页
* @param pageSize 每页显示的条数
* @return RoomDetail
* @Author Lebron
* @Date 2020/4/20 10:40
* @Description 查询房间信息 TODO
*/
List getAll(String keyword, Integer page, Integer pageSize);
/**
* @param id
* @return RoomDetail
* @Author Lebron
* @Date 2020/4/20 10:40
* @Description 根据id查询房间信息 TODO
*/
RoomDetail getById(Integer id);
/**
* @param roomDetail
* @return int
* @Author Lebron
* @Date 2020/4/20 10:40
* @Description 添加房间信息 TODO
*/
int insertRoom(RoomDetail roomDetail);
/**
* @param id
* @return int
* @Author Lebron
* @Date 2020/4/20 10:40
* @Description 删除房间信息 TODO
*/
int delById(Integer id);
/**
* @param roomDetail
* @return int
* @Author Lebron
* @Date 2020/4/20 10:40
* @Description 编修/修改房间信息 TODO
*/
int updRoom(RoomDetail roomDetail);
/**
* @param keyword
* @return int
* @Author Lebron
* @Date 2020/4/20 10:40
* @Description 根据关键字查询总条数 TODO
*/
int getTotalCount(String keyword);
}
下面是接口实现类 (登录功能)
package com.lebron.dao;
import com.lebron.entity.RoomUser;
import com.lebron.util.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* @author Lebron
* @ClassName RoomUserDaoImpl
* @Description TODO
* @Date 2020/4/17 17:28
* @Version 1.0
*/
public class RoomUserDaoImpl implements RoomUserDao {
@Override
public RoomUser login(String userName, String passWord) {
RoomUser roomUser = new RoomUser();
Connection conn = null;
try {
conn = DBUtil.getConnection();
String sql = "select * from room_user where user_name = ? and pass_word = ?";
PreparedStatement pr = conn.prepareCall(sql);
pr.setString(1, userName);
pr.setString(2, passWord);
ResultSet rs = pr.executeQuery();
if (rs.next()) {
roomUser.setId(rs.getInt("id"));
roomUser.setUserName(userName);
roomUser.setPassWord(passWord);
roomUser.setCreateTime(rs.getDate("create_time"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
DBUtil.closeCon(conn);
System.out.println("数据库连接已关闭");
} catch (Exception e) {
e.printStackTrace();
}
}
}
return roomUser;
}
}
然后是房间信息接口实现,代码很简单所以没加注释。
package com.lebron.dao;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lebron.entity.RoomDetail;
import com.lebron.util.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* @author Lebron
* @ClassName RoomDetailDaoImpl
* @Description TODO
* @Date 2020/4/17 17:29
* @Version 1.0
*/
public class RoomDetailDaoImpl implements RoomDetailDao {
Connection conn = null;
@Override
public List getAll(String keyword, Integer page, Integer pageSize) {
List roomDetails = new ArrayList<>();
conn = DBUtil.getConnection();
try {
String sql = "";
PreparedStatement ps = null;
page = (page - 1) * pageSize;
if (keyword == null || keyword.equals("")) {
sql = "select * from room_detail order by id desc limit ?,?";
ps = conn.prepareCall(sql);
ps.setInt(1, page);
ps.setInt(2, pageSize);
} else {
sql = "select * from room_detail " +
"where room_num like ? or room_type like ? order by id desc limit ?,?";
ps = conn.prepareCall(sql);
ps.setString(1, '%' + keyword + '%');
ps.setString(2, '%' + keyword + '%');
ps.setInt(3, page);
ps.setInt(4, pageSize);
}
ResultSet rs = ps.executeQuery();
while (rs.next()) {
RoomDetail roomDetail = new RoomDetail();
roomDetail.setId(rs.getInt("id"));
roomDetail.setRoomNum(rs.getInt("room_num"));
roomDetail.setRoomType(rs.getString("room_type"));
roomDetail.setRoomPrice(rs.getBigDecimal("room_price"));
roomDetail.setLiveTime(rs.getString("live_time"));
roomDetails.add(roomDetail);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
DBUtil.closeCon(conn);
} catch (Exception e) {
e.printStackTrace();
}
}
}
String roomJson = JSON.toJSONString(roomDetails);
List roomList = JSONObject.parseArray(roomJson);
return roomList;
}
@Override
public RoomDetail getById(Integer id) {
RoomDetail roomDetail = new RoomDetail();
try {
conn = DBUtil.getConnection();
String sql = "select * from room_detail where id = ?";
PreparedStatement ps = conn.prepareCall(sql);
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
roomDetail.setId(id);
roomDetail.setRoomNum(rs.getInt("room_num"));
roomDetail.setRoomType(rs.getString("room_type"));
roomDetail.setRoomPrice(rs.getBigDecimal("room_price"));
roomDetail.setLiveTime(rs.getString("live_time"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
DBUtil.closeCon(conn);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return roomDetail;
}
@Override
public int insertRoom(RoomDetail roomDetail) {
int count = 0;
try {
conn = DBUtil.getConnection();
String sql = "INSERT INTO room_detail(room_num,room_type,room_price,live_time,create_time) VALUES(?,?,?,?,?)";
PreparedStatement ps = conn.prepareCall(sql);
ps.setInt(1, roomDetail.getRoomNum());
ps.setString(2, roomDetail.getRoomType());
ps.setBigDecimal(3, roomDetail.getRoomPrice());
ps.setString(4, roomDetail.getLiveTime());
ps.setDate(5, roomDetail.getCreateTime());
count = ps.executeUpdate();
if (count > 0) {
System.out.println("添加成功");
} else {
System.out.println("添加失败");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
DBUtil.closeCon(conn);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return count;
}
@Override
public int delById(Integer id) {
int count = 0;
try {
conn = DBUtil.getConnection();
String sql = "delete from room_detail where id = ?";
PreparedStatement ps = conn.prepareCall(sql);
ps.setInt(1, id);
count = ps.executeUpdate();
if (count > 0) {
System.out.println("删除成功");
} else {
System.out.println("删除失败");
}
} catch (SQLException e) {
e.printStackTrace();
}
return count;
}
@Override
public int updRoom(RoomDetail roomDetail) {
int count = 0;
try {
conn = DBUtil.getConnection();
String sql = "update room_detail set room_num = ?,room_type = ?,room_price = ?,live_time = ? where id = ?";
PreparedStatement ps = conn.prepareCall(sql);
ps.setInt(1, roomDetail.getRoomNum());
ps.setString(2, roomDetail.getRoomType());
ps.setBigDecimal(3, roomDetail.getRoomPrice());
ps.setString(4, roomDetail.getLiveTime());
ps.setInt(5, roomDetail.getId());
count = ps.executeUpdate();
if (count > 0) {
System.out.println("修改成功");
} else {
System.out.println("修改失败");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
DBUtil.closeCon(conn);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return count;
}
@Override
public int getTotalCount(String keyword) {
int count = 0;
try {
String sql = "";
conn = DBUtil.getConnection();
PreparedStatement ps = null;
if (keyword == null) {
sql = "select * from room_detail";
ps = conn.prepareCall(sql);
} else {
sql = "select * from room_detail " +
"where room_num like ? or room_type like ?";
ps = conn.prepareCall(sql);
ps.setString(1, '%' + keyword + '%');
ps.setString(2, '%' + keyword + '%');
}
ResultSet rs = ps.executeQuery();
while (rs.next()) {
count++;
}
} catch (SQLException e) {
e.printStackTrace();
}
return count;
}
}
最后我们开始编写servlet,首先是登录
package com.lebron.servlet;
import com.alibaba.fastjson.JSON;
import com.lebron.dao.RoomUserDao;
import com.lebron.dao.RoomUserDaoImpl;
import com.lebron.entity.RoomUser;
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 java.io.IOException;
import java.io.PrintWriter;
/**
* @author Lebron
* @ClassName LoginServlet
* @Description TODO
* @Date 2020/4/17 17:36
* @Version 1.0
*/
@WebServlet(name = "loginServlet", urlPatterns = "/loginServlet")
public class LoginServlet extends HttpServlet {
private RoomUserDao roomUserDao = new RoomUserDaoImpl();
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json;GBK");
response.setCharacterEncoding("GBK");
request.setCharacterEncoding("UTF-8");
String userName = request.getParameter("userName");
String passWord = request.getParameter("passWord");
PrintWriter out = response.getWriter();
if (userName == null || passWord == null) {
String resJSON = "{" + "\"code\":-1," + "\"success\":false," + "\"msg\":账号或密码为空" + "}";
out.print(resJSON);
} else {
RoomUser roomUser = roomUserDao.login(userName, passWord);
if (roomUser == null) {
String resJSON = "{" + "\"code\":-1," + "\"success\":false," + "\"msg\":用户不存在" + "}";
out.print(resJSON);
} else {
HttpSession session = request.getSession();
session.setAttribute("user", roomUser);
String json = JSON.toJSONString(roomUser);
String resJSON = "{" + "\"code\":0," + "\"success\":true," + "\"date\":" + json + "}";
out.print(resJSON);
}
}
}
}
因为同事让我给她json格式的返回值,所以拼了一下,你们自己写的话根据需求返回即可。
房间信息添加servlet
package com.lebron.servlet;
import com.lebron.dao.RoomDetailDao;
import com.lebron.dao.RoomDetailDaoImpl;
import com.lebron.entity.RoomDetail;
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 java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Date;
/**
* @author Lebron
* @ClassName InsertRoomServlet
* @Description TODO
* @Date 2020/4/18 9:27
* @Version 1.0
*/
@WebServlet(name = "insertRoomServlet", urlPatterns = "/insertRoomServlet")
public class InsertRoomServlet extends HttpServlet {
private RoomDetailDao roomDetailDao = new RoomDetailDaoImpl();
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json;GBK");
response.setCharacterEncoding("GBK");
request.setCharacterEncoding("UTF-8");
String roomNum = request.getParameter("roomNum");
String roomType = request.getParameter("roomType");
String roomPrice = request.getParameter("roomPrice");
String liveTime = request.getParameter("liveTime");
BigDecimal roomPriceTmp = new BigDecimal(roomPrice);
PrintWriter out = response.getWriter();
RoomDetail roomDetail = new RoomDetail();
roomDetail.setRoomNum(Integer.valueOf(roomNum));
roomDetail.setRoomPrice(roomPriceTmp);
roomDetail.setRoomType(roomType);
roomDetail.setLiveTime(liveTime);
roomDetail.setCreateTime(new java.sql.Date(System.currentTimeMillis()));
int count = roomDetailDao.insertRoom(roomDetail);
if (count > 0) {
out.print("{" + "\"code\":0," + "\"success\":true," + "\"msg\":" + "添加成功" + "}");
} else {
out.print("{" + "\"code\":-1," + "\"success\":false," + "\"msg\":" + "添加失败" + "}");
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
查询全部房间信息,这里为了方便前端分页,把分页数据一并返回给了前端。还有模糊查询,keyword是用户输入的关键字。
package com.lebron.servlet;
import com.alibaba.fastjson.JSON;
import com.lebron.dao.RoomDetailDao;
import com.lebron.dao.RoomDetailDaoImpl;
import com.lebron.entity.RoomDetail;
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 java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
/**
* @author Lebron
* @ClassName getAllRoomServlet
* @Description TODO
* @Date 2020/4/17 18:10
* @Version 1.0
*/
@WebServlet(name = "allRoomServlet", urlPatterns = "/allRoomServlet")
public class GetAllRoomServlet extends HttpServlet {
private RoomDetailDao roomDetailDao = new RoomDetailDaoImpl();
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json;GBK");
response.setCharacterEncoding("GBK");
request.setCharacterEncoding("UTF-8");
String keyword = request.getParameter("keyword");
String page = request.getParameter("page");
String pageSize = request.getParameter("pageSize");
if (page == null || Integer.valueOf(page).equals(0)) {
//默认从第一页显示
page = "1";
}
if (pageSize == null || Integer.valueOf(pageSize).equals(0)) {
//默认每页显示10条
pageSize = "10";
}
PrintWriter out = response.getWriter();
int totalCount = roomDetailDao.getTotalCount(keyword);
List roomDetails = roomDetailDao.getAll(keyword, Integer.valueOf(page), Integer.valueOf(pageSize));
String json = JSON.toJSONString(roomDetails);
String resJSON = "{" + "\"code\":0," + "\"success\":true," + "\"page\":" + page + ","
+ "\"pageSize\":" + pageSize + "," + "\"totalCount\":" + totalCount + "," + "\"date\":" + json + "}";
out.print(resJSON);
}
}
根据id查询单条房间信息,查到的信息供修改使用。
package com.lebron.servlet;
import com.alibaba.fastjson.JSON;
import com.lebron.dao.RoomDetailDao;
import com.lebron.dao.RoomDetailDaoImpl;
import com.lebron.entity.RoomDetail;
import com.sun.xml.internal.bind.v2.model.core.ID;
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 java.io.IOException;
import java.io.PrintWriter;
/**
* @author Lebron
* @ClassName GetRoomByID
* @Description TODO
* @Date 2020/4/20 15:45
* @Version 1.0
*/
@WebServlet(name = "getRoomByIdServlet", urlPatterns = "/getRoomByIdServlet")
public class GetRoomByID extends HttpServlet {
private RoomDetailDao roomDetailDao = new RoomDetailDaoImpl();
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json;GBK");
response.setCharacterEncoding("GBK");
request.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
String roomId = request.getParameter("id");
if (roomId == null || Integer.valueOf(roomId).equals(0)) {
String resJSON = "{" + "\"code\":-1," + "\"success\":false," + "\"msg\":" + "参数为空" + "}";
out.print(resJSON);
}
RoomDetail roomDetail = roomDetailDao.getById(Integer.valueOf(roomId));
String roomJson = JSON.toJSONString(roomDetail);
String resJSON = "{" + "\"code\":0," + "\"success\":true," + "\"date\":" + roomJson + "}";
out.print(resJSON);
}
}
编辑房间信息。
package com.lebron.servlet;
import com.lebron.dao.RoomDetailDao;
import com.lebron.dao.RoomDetailDaoImpl;
import com.lebron.entity.RoomDetail;
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 java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
/**
* @author Lebron
* @ClassName UpdRoomServlet
* @Description TODO
* @Date 2020/4/20 15:55
* @Version 1.0
*/
@WebServlet(name = "updRoomServlet", urlPatterns = "/updRoomServlet")
public class UpdRoomServlet extends HttpServlet {
private RoomDetailDao roomDetailDao = new RoomDetailDaoImpl();
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json;GBK");
response.setCharacterEncoding("GBK");
request.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
String roomId = request.getParameter("id");
String roomNum = request.getParameter("roomNum");
String roomType = request.getParameter("roomType");
String roomPrice = request.getParameter("roomPrice");
String liveTime = request.getParameter("liveTime");
RoomDetail roomDetail = roomDetailDao.getById(Integer.valueOf(roomId));
if (roomDetail == null) {
String resJSON = "{" + "\"code\":-1," + "\"success\":false," + "\"msg\":" + "查不到此条数据" + "}";
out.print(resJSON);
}
roomDetail.setRoomNum(Integer.valueOf(roomNum));
roomDetail.setRoomType(roomType);
roomDetail.setRoomPrice(new BigDecimal(roomPrice));
roomDetail.setLiveTime(liveTime);
int count = roomDetailDao.updRoom(roomDetail);
if (count > 0) {
out.print("{" + "\"code\":0," + "\"success\":true," + "\"msg\":" + "修改成功" + "}");
} else {
out.print("{" + "\"code\":-1," + "\"success\":false," + "\"msg\":" + "修改失败" + "}");
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
最后是删除。
package com.lebron.servlet;
import com.lebron.dao.RoomDetailDao;
import com.lebron.dao.RoomDetailDaoImpl;
import com.sun.xml.internal.bind.v2.model.core.ID;
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 java.io.IOException;
import java.io.PrintWriter;
/**
* @author Lebron
* @ClassName DelRoomServlet
* @Description TODO
* @Date 2020/4/20 15:49
* @Version 1.0
*/
@WebServlet(name = "delRoomServlet", urlPatterns = "/delRoomServlet")
public class DelRoomServlet extends HttpServlet {
private RoomDetailDao roomDetailDao = new RoomDetailDaoImpl();
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json;GBK");
response.setCharacterEncoding("GBK");
request.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
String roomId = request.getParameter("id");
if (roomId == null || Integer.valueOf(roomId).equals(0)) {
String resJSON = "{" + "\"code\":-1," + "\"success\":false," + "\"msg\":" + "参数为空" + "}";
out.print(resJSON);
}
int count = roomDetailDao.delById(Integer.valueOf(roomId));
if (count > 0) {
out.print("{" + "\"code\":0," + "\"success\":true," + "\"msg\":" + "删除成功" + "}");
} else {
out.print("{" + "\"code\":-1," + "\"success\":false," + "\"msg\":" + "删除失败" + "}");
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
OK,至此同事需要的功能已经全部实现,但是缺少过滤器,用户不需要登录就可以进入到其他页面,这里我们需要在添加一个过滤器。创建filter目录。
package com.lebron.filter;
import com.lebron.entity.RoomDetail;
import com.lebron.entity.RoomUser;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @author Lebron
* @ClassName LoginFilter
* @Description TODO
* @Date 2020/4/20 16:19
* @Version 1.0
*/
public class LoginFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String servletPath = request.getServletPath();
HttpSession session = request.getSession();
RoomUser roomUser = (RoomUser) session.getAttribute("user");
PrintWriter out = response.getWriter();
if (servletPath != null && servletPath.equals("/loginServlet")) {
filterChain.doFilter(servletRequest, servletResponse);
} else {
if (roomUser != null) {
String userName = roomUser.getUserName();
if (userName != null || !userName.equals("")) {
filterChain.doFilter(servletRequest, servletResponse);
} else {
out.print("{" + "\"code\":-2," + "\"success\":false" + "\"msg\":" + "用户未登录" + "}");
}
} else {
out.print("{" + "\"code\":-2," + "\"success\":false" + "\"msg\":" + "用户未登录" + "}");
}
}
}
@Override
public void destroy() {
}
}
过滤器需要在web.xml文件中配置,配置文件如下
LoginFilter
com.lebron.filter.LoginFilter
LoginFilter
/*
接下来就可以进行测试啦,我用的测试工具是postman,一款很方便的接口测试工具。
登录测试
房间信息添加测试 大家测试的时候记得要把过滤器的配置文件先注释掉,不然会不通过的!或者就先测试登录再测别的接口!
wtf?乱码了?还是乖乖配个注册字符编码过滤器吧。
过滤器是有先后执行顺序的,我们要把这个配置放在登录过滤器上边。
package com.lebron.filter;
import javax.servlet.*;
import java.io.IOException;
/**
* @author Lebron
* @ClassName LoginFilter
* @Description TODO
* @Date 2020/4/20 16:19
* @Version 1.0
*/
public class CharacterEncodingFilter implements Filter {
private FilterConfig config;
@Override
public void init(FilterConfig config) throws ServletException {
this.config = config;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
String encoding = config.getInitParameter("encoding");
if (encoding != null) {
request.setCharacterEncoding(encoding);
response.setCharacterEncoding(encoding);
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
配置如下
characterEncodingFilter
com.lebron.filter.CharacterEncodingFilter
encoding
UTF-8
characterEncodingFilter
/*
此时我们再测试一次
OK,乱码问题已经解决,我们接着进行测试。
我介绍一下参数与返回值,keyword是用户输入的查询条件,不传的时候是查询全部,page是第几页,pageSize是每页显示几条数据,返回的totalCount是一共多少条数据,总条数/每条显示的条数就是总页数。
根据id查询单条数据信息。也ok
修改,也没问题。
最后就是删除啦!
OK!至此就全部完成啦,虽然很简单的代码,但是希望能给大家带来帮助,有问题可以留言,看到后我会回复,最后是项目,欢迎大家下载学习!
项目源码!!
链接:https://pan.baidu.com/s/10ZmzlDWRAeKL7pqic79XmQ
提取码:rxjo