引言

这个实例是上一个实例JavaWeb学习 三层架构实例(一)的加强版,实现的是在前端对数据库中student表的 操作。关于三层组成云云,这里就不再叙述。

实例

效果图

先来看一下主页,将student表中的数据列出来,这里隐藏了地址信息(saddress)。



这是添加学生信息的页面



这是修改学生信息的页面(学号不可修改)



由于删除学生信息不需要跳转,所以没有删除学生信息的页面。这几个功能的操作结果都会在主页的左上角显示。

项目结构



如图,自上到下,

StudentDao.java 是直接对数据库进行增删改查操作的,属于原子性的操作,没有逻辑性,只是简单的增删改查.比如,它并不会在删除某条信息之前先判断这条信息是否存在.

Student.java 是"学生"类,此类拥有诸如学号、姓名、年龄、地址等信息以及对应的getter和setter方法。

StudentService.java 这个类,名子含义有点模糊,属于service层,同样是对数据库进行增删改查操作,与上面的Dao类不同的是,service层的操作具有逻辑性,就拿添加学生信息来说,service会先调用Dao类的查询方法,先判断这个学生是否存在,根据结果进行信息插入操作。

Servlet包 易发现,这个包中存放的都是Servlet类,属于视图层的后端,每一个类每一个类对应一个视图层前端的功能(增删改查);

代码

Student.java


package com.ajy.entity;
public class Student {
private int stuNo;
private String stuName;
private int stuAge;
private String stuAddress;
public Student(int stuNo,String stuName,int stuAge,String stuAddress){
this.stuNo = stuNo;
this.stuName = stuName;
this.stuAge = stuAge;
this.stuAddress = stuAddress;
}
public Student(String stuName,int stuAge,String stuAddress){
this.stuNo = stuNo;
this.stuName = stuName;
this.stuAge = stuAge;
this.stuAddress = stuAddress;
} public int getStuNo() {
return stuNo;
} public void setStuNo(int stuNo) {
this.stuNo = stuNo;
} public String getStuName() {
return stuName;
} public void setStuName(String stuName) {
this.stuName = stuName;
} public int getStuAge() {
return stuAge;
} public void setStuAge(int stuAge) {
this.stuAge = stuAge;
} public String getStuAddress() {
return stuAddress;
} public void setStuAddress(String stuAddress) {
this.stuAddress = stuAddress;
} @Override
public String toString() {
return getStuNo()+"--"+getStuName()+"--"+getStuAge()+"--"+getStuAddress();
}
}

StudentDao.java


package com.ajy.dao; import com.ajy.entity.Student; import java.sql.*;
import java.util.ArrayList;
import java.util.List; public class StudentDao {
private final String URL="jdbc:mysql://localhost:3306/anjiyubase?&serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true";
private final String DRIVER="com.mysql.cj.jdbc.Driver";
private final String NAME="root";
private final String PWD="121181"; //增加学生信息
public boolean addStudent(Student stu){
Connection con = null;
PreparedStatement pstmt = null;
int count = 0;
try {
Class.forName(DRIVER);
con = DriverManager.getConnection(URL,NAME,PWD);
String sql = "insert into student values(?,?,?,?)";
pstmt = con.prepareStatement(sql);
pstmt.setInt(1,stu.getStuNo());
pstmt.setString(2,stu.getStuName());
pstmt.setInt(3,stu.getStuAge());
pstmt.setString(4,stu.getStuAddress());
count = pstmt.executeUpdate();
} catch (ClassNotFoundException e) {
e.printStackTrace();
return false;
} catch (SQLException e) {
e.printStackTrace();
return false;
}finally {
try {
if (pstmt!=null)pstmt.close();
if (con!=null)con.close();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
if(count==0){
return false;
}else{
return true;
}
} //查询学生是否存在
public boolean isExits(int stuNo){
return queryStudent(stuNo)==null?false:true;
} //查询学生
public Student queryStudent(int stuNo){
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
Student stu = null;
int count = 0;
try {
Class.forName(DRIVER);
con = DriverManager.getConnection(URL,NAME,PWD);
String sql = "select * from student where sno=?";
pstmt = con.prepareStatement(sql);
pstmt.setInt(1,stuNo);
rs = pstmt.executeQuery();
if (rs.next()){
stu = new Student(rs.getInt("sno"),
rs.getString("sname"),
rs.getInt("sage"),
rs.getString("saddress"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
} catch (SQLException e) {
e.printStackTrace();
return null;
}finally {
try {
if (rs!=null)rs.close();
if (pstmt!=null)pstmt.close();
if (con!=null)con.close();
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
return stu;
} //查询全部学生
public List<Student> queryAll(){
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
List<Student> list = new ArrayList<>();
try {
Class.forName(DRIVER);
con = DriverManager.getConnection(URL,NAME,PWD);
String sql = "select *from student";
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next()){
int sno = rs.getInt("sno");
String sname = rs.getString("sname");
int sage = rs.getInt("sage");
String saddress = rs.getString("saddress");
list.add(new Student(sno,sname,sage,saddress));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
} catch (SQLException e) {
e.printStackTrace();
return null;
}finally {
try {
if (rs!=null)rs.close();
if (stmt!=null)stmt.close();
if (con!=null)con.close();
return list;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
} //根据学号删除学生
public boolean deleteStudentBySno(int Sno){
Connection con = null;
PreparedStatement pstmt = null;
int count = 0;
try {
Class.forName(DRIVER);
con = DriverManager.getConnection(URL,NAME,PWD);
String sql = "delete from student where sno=?";
pstmt = con.prepareStatement(sql);
pstmt.setInt(1,Sno);
count = pstmt.executeUpdate();
} catch (ClassNotFoundException e) {
e.printStackTrace();
return false;
} catch (SQLException e) {
e.printStackTrace();
return false;
}finally {
try {
if (pstmt!=null)pstmt.close();
if (con!=null)con.close();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
if(count==0){
return false;
}else{
return true;
}
} //根据学号修改学号对应的学生信息
public boolean updateStudentBySno(int sno,Student stu){
Connection con = null;
PreparedStatement pstmt = null;
int count = 0;
try {
Class.forName(DRIVER);
con = DriverManager.getConnection(URL,NAME,PWD);
String sql = "update student set sname=?,sage=?,saddress=? where sno=?";
pstmt = con.prepareStatement(sql);
//要修改的人
pstmt.setInt(4,sno);
//修改该后的内容
pstmt.setString(1,stu.getStuName());
pstmt.setInt(2,stu.getStuAge());
pstmt.setString(3,stu.getStuAddress());
count = pstmt.executeUpdate();
} catch (ClassNotFoundException e) {
e.printStackTrace();
return false;
} catch (SQLException e) {
e.printStackTrace();
return false;
}finally {
try {
if (pstmt!=null)pstmt.close();
if (con!=null)con.close();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
if(count==0){
return false;
}else{
return true;
}
}
}

StudentService


package com.ajy.service; import com.ajy.dao.StudentDao;
import com.ajy.entity.Student; import java.util.List; public class StudentService {
StudentDao studentDao = new StudentDao(); //增加学生
public boolean addStudent(Student stu){
if (!studentDao.isExits(stu.getStuNo())){
return studentDao.addStudent(stu);
}else{
return false;
}
} //根据学号删除学生
public boolean deleteStudentBySno(int sno){
//先判断学生是否存在
if(!studentDao.isExits(sno)){
return false;
}else{
return studentDao.deleteStudentBySno(sno);
}
} //根据学号查询学生
public Student queryStudentBySno(int sno){
return studentDao.queryStudent(sno);
} //根据学号,更新对应的学生
public boolean updateStudentBySno(int sno,Student stu){
//先判断此学号对应的学生是否存在
if(!studentDao.isExits(sno)){
return false;
}else{
return studentDao.updateStudentBySno(sno,stu);
}
} //查询全部学生
public List<Student> queryStudentAll(){
return studentDao.queryAll();
}
}

QueryAllStudents.java


package com.ajy.servlet; import com.ajy.entity.Student;
import com.ajy.service.StudentService; 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; @WebServlet(name = "QueryAllStudents",value = "/QueryAllStudents")
public class QueryAllStudents extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
StudentService studentService = new StudentService();
List<Student> studentList = studentService.queryStudentAll(); request.setAttribute("students",studentList); request.getRequestDispatcher("studentlist.jsp").forward(request,response);
}
}

AddStudentServlet.java


package com.ajy.servlet; import com.ajy.entity.Student;
import com.ajy.service.StudentService; 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; @WebServlet(name = "AddStudentServlet",value = "/AddStudentServlet")
public class AddStudentServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8");
int stuNo = Integer.parseInt(request.getParameter("stuNo"));
String stuName = request.getParameter("stuName");
int stuAge = Integer.parseInt(request.getParameter("stuAge"));
String stuAddress = request.getParameter("stuAddress"); Student stu = new Student(stuNo,stuName,stuAge,stuAddress);
StudentService addStudentService = new StudentService();
boolean res = addStudentService.addStudent(stu); if (res){
request.setAttribute("res","添加成功");
}else{
request.setAttribute("res","添加失败");
}
request.getRequestDispatcher("QueryAllStudents").forward(request,response);
}
}

DeleteStudentServlet.java


package com.ajy.servlet;
import com.ajy.service.StudentService;
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(name = "DeleteStudentServlet",value = "/DeleteStudentServlet")
public class DeleteStudentServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
//根据学号删除学生
int sno = Integer.parseInt(request.getParameter("sno"));
StudentService studentService = new StudentService();
boolean res = studentService.deleteStudentBySno(sno); response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter();
if (res){
request.setAttribute("res","删除成功");
}else{
request.setAttribute("res","删除失败");
}
request.getRequestDispatcher("QueryAllStudents").forward(request,response);
}
}

UpdateStudentBySnoServlet.java


package com.ajy.servlet; import com.ajy.entity.Student;
import com.ajy.service.StudentService;
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; @WebServlet(name = "UpdateStudentBySnoServlet",value = "/UpdateStudentBySnoServlet")
public class UpdateStudentBySnoServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
StudentService studentService = new StudentService(); int sno = Integer.parseInt(request.getParameter("sno"));
String sname = request.getParameter("sname");
int sage = Integer.parseInt(request.getParameter("sage"));
String saddress = request.getParameter("saddress");
Student student = new Student(sname,sage,saddress); boolean res = studentService.updateStudentBySno(sno,student);
if (res){
request.setAttribute("res","修改成功");
}else{
request.setAttribute("res","修改失败");
}
request.getRequestDispatcher("QueryAllStudents").forward(request,response);
}
}

QueryStudentBySno.java


package com.ajy.servlet; import com.ajy.entity.Student;
import com.ajy.service.StudentService;
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; @WebServlet(name = "QueryStudentBySno",value = "/QueryStudentBySno")
public class QueryStudentBySno extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
StudentService studentService = new StudentService();
int sno = Integer.parseInt(request.getParameter("sno"));
Student stu = studentService.queryStudentBySno(sno); request.setAttribute("student",stu);
request.getRequestDispatcher("updateinfo.jsp").forward(request,response);
}
}

addstudent.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>添加学生</title>
</head>
<body>
<form action="AddStudentServlet" method="post">
学号:<input type="number" name="stuNo"><br>
姓名:<input type="text" name="stuName"><br>
年龄:<input type="number" name="stuAge"><br>
地址:<input type="text" name="stuAddress"><br>
<input type="submit" value="提交"><br>
</form>
<a href="QueryAllStudents">返回首页</a>
</body>
</html>

studentlist.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>学生信息列表</title>
</head>
<body>
<%
String operateResult = (String) request.getAttribute("res");
if (operateResult!=null){
out.print(operateResult);
}else{
out.print("<br>");
}
%>
<table border="1px">
<tr>
<th>学号</th>
<th>姓名</th>
<th>年龄</th>
<th>操作</th>
</tr>
<%
List<Student> studentList = (List<Student>) request.getAttribute("students");
for (Student student:studentList){
%>
<tr>
<td><%=student.getStuNo()%></td>
<td><%=student.getStuName()%></td>
<td><%=student.getStuAge()%></td>
<td><a href="QueryStudentBySno?sno=<%=student.getStuNo()%>">修改</a></td>
<td><a href="DeleteStudentServlet?sno=<%=student.getStuNo()%>">删除</a></td>
</tr>
<%
}
%>
</table>
<a href="addstudent.jsp">增加</a>
</body>
</html>

updateinfo.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>学生个人信息</title>
</head>
<body>
<%
Student stu = (Student) request.getAttribute("student");
%>
<form action="UpdateStudentBySnoServlet" method="post">
学号:<input type="number" name="sno" value="<%=stu.getStuNo()%>"><br>
姓名:<input type="text" name="sname" value="<%=stu.getStuName()%>"><br>
年龄:<input type="number" name="sage" value="<%=stu.getStuAge()%>"><br>
地址:<input type="text" name="saddress" value="<%=stu.getStuAddress()%>"><br>
<input type="submit" value="提交"><br>
</form>
<a href="QueryAllStudents">返回首页</a>
</body>
</html>

JavaWeb学习之三层架构实例(二)的更多相关文章

  1. JavaWeb学习之三层架构实例(三)

    引言 通过上一篇博客JavaWeb学习之三层架构实例(二)我们基本上已经实现了对学生信息列表的增删改查操作(UI除外),但是不难看出,代码冗余度太高了,尤其是StudentDao这个类,其中的增删改查 ...

  2. java:Session(概述,三层架构实例(实现接口封装JDBC),Session实现简单购物车实例)

    1.Session概述: Session:在计算机中,尤其是在网络应用中,称为“会话控制”.Session 对象存储特定用户会话所需的属性及配置信息.这样,当用户在应用程序的 Web 页之间跳转时,存 ...

  3. javaweb学习总结(六)——Servlet开发(二)

    一.ServletConfig讲解 1.1.配置Servlet初始化参数 在Servlet的配置文件web.xml中,可以使用一个或多个<init-param>标签为servlet配置一些 ...

  4. javaweb学习总结(六)——Servlet开发(二)(转)

    转载自 http://www.cnblogs.com/xdp-gacl/p/3763559.html 一.ServletConfig讲解 1.1.配置Servlet初始化参数 在Servlet的配置文 ...

  5. C# 学习笔记 三层架构系列(控件一)

    下面是我两周的学习总结:这是我写给自己的,如果哪位朋友有幸看到这篇文章就是缘分.如果所说的内容不对,就请纠正.勿喷!!! 想要将两周的学习知识通过文字.通过代码.通过图片储备起来,以防自己那天思维短路 ...

  6. C# 使用三层架构实例演示-winForm 窗体登录功能

    ---------------------------------------------------------------------------------------------------华 ...

  7. Java学习笔记——三层架构

    Layer: UI层: user interface 用户接口层 Biz层:   service business login layer 业务逻辑层 DAO层:   Date Access Obje ...

  8. JAVAWEB学习总结 HTTPSERVLETRESPONSE对象(二)

    一.HttpServletResponse常见应用--生成验证码 1.1.生成随机图片用作验证码 生成图片主要用到了一个BufferedImage类 步骤: 1. 在内存中创建一张图片 2.得到图片 ...

  9. JAVAWEB学习总结 SERVLET开发(二)

    一.ServletConfig对象 1.1.配置servlet初始化参数 在servlet的配置文件中web.xml中,可以使用一个或多个<init-param>标签为servlet配置一 ...

随机推荐

  1. mysql根据分组和条件查询以后如何统计记录的条数

    1.子查询,查询出的数据随便起一个别名,然后根据分组和条件查询出的数据,作为一个具有一列的一个表,然后外面的查询查询这个数据表的这一列的总数,即可. SELECT COUNT( * ) FROM ( ...

  2. Go Socket实现简单的HttpServer

    在上篇博客中写到如何用Python实现一个类似tomcat的简单服务器,接下来用go语言去实现 1. Go本身自己封装实现了非常简单的httpServer package main import ( ...

  3. HBase总结 LSM理解

    转载的文章,觉得写的比较好 讲LSM树之前,需要提下三种基本的存储引擎,这样才能清楚LSM树的由来: 哈希存储引擎  是哈希表的持久化实现,支持增.删.改以及随机读取操作,但不支持顺序扫描,对应的存储 ...

  4. MySQL通过Navicat实现远程连接的过程

      直接使用Navicat通过IP连接会报各种错误,例如:Error 1130: Host '192.168.1.80' is not allowed to connect to this MySQL ...

  5. 将cookie 转换成字典格式

    b = 'bid=Qzw9cKnyESM; ll="108288"; __yadk_uid=4YChvgeANLBEh4iV00n1tc0HQ8zpmSl1; __utmc=301 ...

  6. vue-cli 构建的项目中 如何使用less

    vue-cli 构建的项目默认是不支持 less 的,需要自己添加. 首选,安装 less 和 less-loader ,在项目目录下运行如下命令 npm install less less-load ...

  7. linux(ubuntu) 安装composer(PHP用来管理依赖关系的工具 ) 和安装中国全量镜像

    https://www.phpcomposer.com/  composer中文网 1:进入安装目录   cd /usr/local/bin 2:下载并安装     sudo curl -s http ...

  8. asp.net MVC jsonp跨域获取数据

    public class JsonpResult : JsonResult { object _data = null; public JsonpResult() { } public JsonpRe ...

  9. __x__(10)0906第三天__字符实体(转义字符)

    实体:也叫转义字符,在网页中,一些类似“大于号”和“小于号”这样的字符,无法直接使用,需要用特殊的字符串来表示. 实体语法: “&实体名字;” 或者 “&实体编号;” 注意: 最好使用 ...

  10. __x__(35)0908第五天__ 层级 z-index

    如果三个 div 全部设置 position: absolute; 绝对定位,且未设置 z-index,  则从代码结构上    下面的元素 会盖住 上面的元素. z-index 层级: 通过 z-i ...