三层架构就是将整个业务应用划分为:界面层、业务逻辑层、数据访问层。
高内聚低耦合
package come.entity;
/**
* User类是对MySQL中数据的封装,包含name及password
*/
public class User {
public String username;
public String password;
public User() {
super();
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
package come.entity;
import com.sun.corba.se.impl.resolver.SplitLocalResolverImpl;
import java.util.List;
/**
* Page是对以后进行分页处理时,需要的分页数据进行的封装
* 此部分包含五个数据:
* a. 当前页 currentPage
* b. 页面大小 pageSize
* c. 当前页的数据集合 list
* d. 总数据量 totalCount
* e. 总页数 totalPage
*/
public class Page {
private int currentPage;
private int pageSize;
private List<User> list;
private int totalCount;
private int totalPage;
public Page() {
}
public Page(int currentPage, int pageSize, List<User> list, int totalCount, int totalPage) {
this.currentPage = currentPage;
this.pageSize = pageSize;
this.list = list;
this.totalCount = totalCount;
this.totalPage = totalPage;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
//在这里需要注意:
// 计算总页数totalPage的操作在这里~
this.totalPage = this.totalCount%this.pageSize==0?this.totalCount/this.pageSize:this.totalCount/this.pageSize+1;
}
public List<User> getList() {
return list;
}
public void setList(List<User> list) {
this.list = list;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage=totalPage;
}
}
(2)接下来进行dao层的增删改查操作(这里再附带util,即对jdbc的封装)
package come.dao;
import come.entity.User;
import java.util.List;
/**
* 这是dao层的接口啦
*/
public interface DataDao {
/**
* 获取数据总数
* @return
*/
public int getTotalCount();
/**
* 查询某一页
* @param currentPage 当前页码
* @param pageSize 每页多少数据
* @return
*/
public List<User> queryDataByPage(int currentPage, int pageSize);
/**
* 判断用户是否存在(这是service层的逻辑)
* @return
*/
public boolean isExist(User user);
/**
* 根据用户名查找信息
* @param user 传递整个用户信息,但实际上只需要用户名
* @return
*/
public User queryDataByName(User user);
/**
* 增加用户
* @param user 获取用户的name及password信息
* @return
*/
public boolean addData(User user);
/**
* 删除用户信息
* @param user 传递整个用户信息,判断name及password是否一致
* @return
*/
public boolean deleteData(User user);
/**
* 修改用户信息
* @param user 传递整个用户信息,但这里只修改password
*/
public boolean updateData(User user);
}
package come.dao.Impl;
import come.entity.User;
import come.dao.DataDao;
import come.util.util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.*;
public class DataDaoImpl implements DataDao {
/**
* 查询用户总人数
* @return
*/
public int getTotalCount(){
return util.getTotalCount();
}
/**
* 查询某一页
* @param currentPage 当前页
* @param pageSize 每页需多少条数据
* @return
*/
@Override
public List<User> queryDataByPage(int currentPage, int pageSize) {
List<User> list=new ArrayList<>();
User user;
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
conn=util.getConnection();
ps=util.getPreparedStatement(conn,"select * from data limit "+(currentPage-1)*pageSize+","+pageSize);
rs=ps.executeQuery();
while (rs.next()) {
user=new User(rs.getString("name"),rs.getString("password"));
list.add(user);
}
}catch (Exception e) {
e.printStackTrace();
} finally {
util.closeRs(rs);
util.closePs(ps);
util.closeConn(conn);
return list;
}
}
/**
* 查询用户是否存在
* @param user
* @return
*/
@Override
public boolean isExist(User user) {
return queryDataByName(user)==null?false:true;
}
/**
* 根据名字查询用户是否存在
* @param user
* @return
*/
@Override
public User queryDataByName(User user) {
User u=null;
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
conn= util.getConnection();
ps=util.getPreparedStatement(conn,"select * from data where name='"+user.getUsername()+"'");
rs=ps.executeQuery();
if (rs.next()) {
u=new User(rs.getString("name"),rs.getString("password"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
util.closeRs(rs);
util.closePs(ps);
util.closeConn(conn);
return u;
}
}
/**
* 增加用户
* @param user
* @return
*/
@Override
public boolean addData(User user) {
Connection conn=null;
PreparedStatement ps=null;
int count=-1;
try {
conn=util.getConnection();
ps=util.getPreparedStatement(conn,"insert into data (name,password) value (?,?)");
ps.setString(1,user.getUsername());
ps.setString(2,user.getPassword());
count=ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
util.closePs(ps);
util.closeConn(conn);
if (count>0) {
return true;
} else {
return false;
}
}
}
/**
* 删除用户
* @param user
* @return
*/
@Override
public boolean deleteData(User user) {
Connection conn=null;
PreparedStatement ps=null;
int count=-1;
try {
conn=util.getConnection();
ps=util.getPreparedStatement(conn,"delete from data where name=? and password=?");
ps.setString(1,user.getUsername());
ps.setString(2,user.getPassword());
count=ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
util.closePs(ps);
util.closeConn(conn);
if (count>0) {
return true;
} else {
return false;
}
}
}
/**
* 更新用户信息
* @param user
* @return
*/
@Override
public boolean updateData(User user) {
Connection conn=null;
PreparedStatement ps=null;
int count=-1;
try {
conn=util.getConnection();
ps=util.getPreparedStatement(conn,"update data set password=? where name=?");
ps.setString(1,user.getPassword());
ps.setString(2,user.getUsername());
count=ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
util.closePs(ps);
util.closeConn(conn);
if (count>0) {
return true;
} else {
return false;
}
}
}
}
package come.util;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class util {
private static String driver;
private static String url;
private static String username;
private static String password;
static {
Properties p=new Properties();
InputStream is=util.class.getResourceAsStream("/jdbc.properties");
try {
p.load(is);
driver=p.getProperty("driver");
url=p.getProperty("url");
username=p.getProperty("username");
password=p.getProperty("password");
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection conn=null;
try {
conn= DriverManager.getConnection(url,username,password);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public static PreparedStatement getPreparedStatement(Connection conn,String sql){
PreparedStatement ps=null;
try {
ps=conn.prepareStatement(sql);
} catch (Exception e) {
e.printStackTrace();
}
return ps;
}
public static Statement getStatement(Connection conn) {
Statement stmt=null;
try {
stmt=conn.createStatement();
} catch (Exception e) {
e.printStackTrace();
}
return stmt;
}
public static void closeRs(ResultSet rs) {
try {
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void closePs(PreparedStatement ps) {
try {
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void closeStmt(Statement stmt) {
try {
stmt.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void closeConn(Connection conn) {
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//通用查询数据总数
public static int getTotalCount() {
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
//MySQL是从0开始计数
int count=-1;
try {
conn=util.getConnection();
ps=util.getPreparedStatement(conn,"select count(*) from data");
rs=ps.executeQuery();
if (rs.next()) {
count=rs.getInt(1);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
util.closeRs(rs);
util.closePs(ps);
util.closeConn(conn);
return count;
}
}
}
(3)是逻辑性的service包啦
package come.service;
import come.entity.User;
import java.util.List;
//依旧是接口
public interface DataService {
/**
* 查询数据总数
* @return
*/
public int getTotalCount();
/**
* 定位页数
* @param currentPage
* @param pageSize
* @return
*/
public List<User> queryDataByPage(int currentPage,int pageSize);
/**
* 根据用户名查找用户
* @param user
* @return
*/
public User queryDataByName(User user);
/**
* 判断用户是否存在,如不存在,增加;否则,不增加
* @param user
* @return
*/
public boolean addData(User user);
/**
* 判断用户是否存在,如果存在,删除;否则,返回警告
* @param user
* @return
*/
public boolean deleteData(User user);
/**
* 判断用户是否存在,如果存在,更新数据;否则,返回警告
* @param user
* @return
*/
public boolean updateData(User user);
}
package come.service.Impl;
import come.dao.DataDao;
import come.dao.Impl.DataDaoImpl;
import come.entity.User;
import come.service.DataService;
import java.util.List;
/**
* 有逻辑的组装,进行逻辑判断并调用dao层的方法
*/
public class DataServiceImpl implements DataService {
DataDao dao=new DataDaoImpl();
/**
* 查询数据总数
* @return
*/
public int getTotalCount() {
return dao.getTotalCount();
}
/**
* 定位页数
* @param currentPage
* @param pageSize
* @return
*/
public List<User> queryDataByPage(int currentPage, int pageSize) {
return dao.queryDataByPage(currentPage,pageSize);
}
/**
* 根据用户名查找用户
* @param user
* @return
*/
public User queryDataByName(User user) {
return dao.queryDataByName(user);
}
/**
* 判断用户是否存在,如不存在,增加;否则,不增加
* @param user
* @return
*/
public boolean addData(User user) {
if (!dao.isExist(user)) {
return dao.addData(user);
} else {
System.out.println("此人已存在");
return false;
}
}
/**
* 判断用户是否存在,如果存在,删除;否则,返回警告
* @param user
* @return
*/
public boolean deleteData(User user) {
if (dao.isExist(user)) {
return dao.deleteData(user);
} else {
System.out.println("此人不存在");
return false;
}
}
/**
* 判断用户是否存在,如果存在,更新数据;否则,返回警告
* @param user
* @return
*/
public boolean updateData(User user) {
if (dao.isExist(user)) {
return dao.updateData(user);
} else {
System.out.println("此人不存在");
return false;
}
}
}
(4)创建servlet包
package come.servlet;
import come.dao.DataDao;
import come.dao.Impl.DataDaoImpl;
import come.entity.Page;
import come.entity.User;
import come.service.DataService;
import come.service.Impl.DataServiceImpl;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
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 javax.swing.table.TableStringConverter;
import java.io.IOException;
import java.util.List;
/**
* 此部分是进行分页操作+查询所有用户数据
*/
@WebServlet("/QueryDataByPageServlet")
public class QueryDataByPageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
DataService service=new DataServiceImpl();
//将页面所需的5个字段,组装到page对象之中
Page page=new Page();
//如果第一次调用身为首页的QueryDataByPageServlet,是获取不到currentPage的,因此先判断currentPage的值,如果为空,定位到第一页
String cPage=req.getParameter("currentPage");
//获得当前页数
if (cPage==null) {
cPage="1";
}
int currentPage=Integer.parseInt(cPage);
page.setCurrentPage(currentPage);
//获取总数据条数
int totalCount=service.getTotalCount();
page.setTotalCount(totalCount);
//获得当前页应显示的条数
String cPageSize=req.getParameter("pageSize");
//定义初始PageSize是3
if (cPageSize==null) {
cPageSize="3";
}
int pageSize=Integer.parseInt(cPageSize);
page.setPageSize(pageSize);
List<User> list=service.queryDataByPage(currentPage,pageSize);
page.setList(list);
req.setAttribute("page",page);
req.getRequestDispatcher("index.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
package come.servlet;
import come.entity.User;
import come.service.DataService;
import come.service.Impl.DataServiceImpl;
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;
/**
* 此部分是增加用户数据
*/
@WebServlet("/AddDataServlet")
public class AddDataServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
String username=req.getParameter("username");
String password=req.getParameter("password");
User user=new User(username,password);
DataService service=new DataServiceImpl();
boolean result=service.addData(user);
if (result) {
req.setAttribute("error","noaddError");
req.getRequestDispatcher("QueryDataByPageServlet").forward(req,resp);
} else {
req.setAttribute("error","addError");
req.getRequestDispatcher("QueryDataByPageServlet").forward(req,resp);
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
}
package come.servlet;
import come.entity.User;
import come.service.DataService;
import come.service.Impl.DataServiceImpl;
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;
/**
* 此部分是删除用户数据
*/
@WebServlet("/DeleteDataServlet")
public class DeleteDataServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
PrintWriter out=resp.getWriter();
String name=req.getParameter("username");
String password=req.getParameter("password");
User user=new User(name,password);
DataService service=new DataServiceImpl();
boolean result=service.deleteData(user);
if (result) {
resp.sendRedirect("QueryDataByPageServlet");
} else {
out.println("删除失败");
}
}
}
package come.servlet;
import come.entity.User;
import come.service.DataService;
import come.service.Impl.DataServiceImpl;
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;
/**
* 此部分是修改用户的password
*/
@WebServlet("/UpdateDataServlet")
public class UpdateDataServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
PrintWriter out=resp.getWriter();
String oldname=req.getParameter("username");
String password=req.getParameter("password");
User user=new User(oldname,password);
DataService service=new DataServiceImpl();
boolean result=service.updateData(user);
if (result) {
resp.sendRedirect("QueryDataByPageServlet");
} else {
out.println("更新失败");
}
}
}
package come.servlet;
import come.entity.User;
import come.service.DataService;
import come.service.Impl.DataServiceImpl;
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;
/**
* 此部分是删除用户的password
*/
@WebServlet("/QueryDataByNameServlet")
public class QueryDataByNameServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
PrintWriter out=resp.getWriter();
String name=req.getParameter("username");
String password=req.getParameter("password");
User user=new User(name,password);
DataService service=new DataServiceImpl();
User u=service.queryDataByName(user);
if (u!=null) {
req.setAttribute("user",user);
req.getRequestDispatcher("info.jsp").forward(req,resp);
} else {
System.out.println("查无此人");
}
}
}
(5)最后进行表示层的操作
<%@ page import="java.util.List" %>
<%@ page import="come.entity.User" %>
<%@ page import="come.entity.Page" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<html>
<head>
<title>用户信息列表</title>
</head>
<body>
<%
//此处判断增加用户是否成功,并打印在主页的第一行
String error=(String)request.getAttribute("error");
if (error!=null) {
if (error.equals("addError")) {
out.print("增加失败");
} else if (error.equals("noaddError")) {
out.print("增加成功");
}
}
%>
<br>
<table border="1px" width="500px">
<tr>
<th>姓名</th>
<th>操作</th>
</tr>
<%
Page page1=(Page)request.getAttribute("page");
for (User user:page1.getList()) {
%>
<tr>
<td><a href="QueryDataByNameServlet?username=<%=user.getUsername()%>&password=<%=user.getPassword()%>"><%=user.getUsername()%></a></td>
<td><a href="DeleteDataServlet?username=<%=user.getUsername()%>&password=<%=user.getPassword()%>">删除</a></td>
</tr>
<%
}
%>
</table>
<a href="add.jsp">新增学生</a><br>
<%-- 此处是在进行判断:即,当定位在数据第一页时,不需要显示首页和上一页;而当定位在最后一页时,也不需要显示尾页和下一页--%>
<%-- 此处需要注意在跳转到QueryDataByPageServlet时,传递的两个值:currentPage和pageSize--%>
<%-- currentPage是为了准确定位页数,而pageSize是需要传递过去计算每页的数据及页数之类的信息(敲重点,pageSize是重点!!!)--%>
<%-- 因为之前缺少pageSize,所以每一次在点击上一页及下一页时,都不会准确定位数据条数--%>
<%
if (page1.getCurrentPage()==page1.getTotalPage()) {
%>
<a href="QueryDataByPageServlet?currentPage=1&pageSize=<%=page1.getPageSize()%>">首页</a>
<a href="QueryDataByPageServlet?currentPage=<%=page1.getCurrentPage()-1%>&pageSize=<%=page1.getPageSize()%>">上一页</a>
<%
} else if (page1.getCurrentPage()==1) {
%>
<a href="QueryDataByPageServlet?currentPage=<%=page1.getCurrentPage()+1%>&pageSize=<%=page1.getPageSize()%>">下一页</a>
<a href="QueryDataByPageServlet?currentPage=<%=page1.getTotalPage()%>&pageSize=<%=page1.getPageSize()%>">尾页</a>
<%
} else {
%>
<a href="QueryDataByPageServlet?currentPage=1&pageSize=<%=page1.getPageSize()%>">首页</a>
<a href="QueryDataByPageServlet?currentPage=<%=page1.getCurrentPage()-1%>&pageSize=<%=page1.getPageSize()%>">上一页</a>
<a href="QueryDataByPageServlet?currentPage=<%=page1.getCurrentPage()+1%>&pageSize=<%=page1.getPageSize()%>">下一页</a>
<a href="QueryDataByPageServlet?currentPage=<%=page1.getTotalPage()%>&pageSize=<%=page1.getPageSize()%>">尾页</a>
<%
}
%>
<br>
<%-- 此处是传递pageSize的值--%>
<form action="QueryDataByPageServlet" method="get" name="pageSize">
每页显示
<select name="pageSize">
<option value="3" selected>3</option>
<option value="5">5</option>
<option value="10">10</option>
</select>条
<input type="submit" value="刷新">
</form>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<script language="JavaScript">
function check() {
if (forma.username.value=="" || forma.password.value=="") {
window.alert("用户名或密码为空");
return false;
}
}
</script>
<title>增加页面</title>
</head>
<body>
<form action="AddDataServlet" method="post" name="forma">
用户名:<input type="text" name="username"><br>
密码:<input type="text" name="password"><br>
<input type="submit" value="新增学生" onclick="return check()">
</form>
</body>
</html>
<%@ page import="come.entity.User" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>查询及修改页面</title>
</head>
<body>
<%
User user=(User)request.getAttribute("user");
%>
<h1>查询及更新页面</h1>
<form action="UpdateDataServlet" method="get">
姓名:<input type="text" name="username" value="<%=user.getUsername()%>" readonly="readonly"><br>
密码:<input type="text" name="password" value="<%=user.getPassword()%>"><br>
<input type="submit" name="修改"><a href="QueryDataByPageServlet">返回查询页面</a>
</form>
</body>
</html>
(6)最后的最后,注意一下web.xml的配置叭
<welcome-file-list>
<!-- 注意此处的初始页面并不是index.jsp,而是要通过QueryDataByPageServlet来获取信息再跳转到index.jsp-->
<welcome-file>QueryDataByPageServlet</welcome-file>
</welcome-file-list>