java web +三层架构 + oracle 实现学生管理系统
程序员文章站
2022-03-15 11:11:52
...
最近在看网易云课颜群的java web课程 做一些总结
首先看一下结构:
java 部分
jsp部分
DBUtil.java 这一部分主要是放置了连接数据库的一些通用方法。
package oge.student.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.swing.text.html.HTMLDocument.HTMLReader.PreAction;
import org.student.entity.Student;
import com.sun.corba.se.spi.orbutil.fsm.State;
//数据库帮助类
public class DBUtil{
private static final String URL="jdbc:oracle:thin:@localhost:1521:orcl";
private static final String USERNAME="sys as sysdba";
private static final String PASSWORD="123456";
public static Connection connection= null;
public static PreparedStatement pstmt=null;
static ResultSet rs;
public static int getTotalCount(String sql) {
int count=-1;
try {
pstmt= createPreparedStatement(sql, null);
rs = pstmt.executeQuery();
if(rs.next()) {
count = rs.getInt(1);
}
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
closeAll(rs, pstmt, connection);
}
return count;
}
public static Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("oracle.jdbc.OracleDriver");
return DriverManager.getConnection(URL,USERNAME,PASSWORD);
}
public static PreparedStatement createPreparedStatement(String sql,Object[] params) throws ClassNotFoundException, SQLException {
pstmt= getConnection().prepareStatement(sql);
//pstmt.setInt(1, sno);
if(params!=null) {
for(int i=0;i<params.length;i++) {
pstmt.setObject(i+1, params[i]);
}}
return pstmt;
}
public static boolean executeupdate(String sql, Object[] params) {
try {
//String sql="delete from student where sno = ?";
pstmt =createPreparedStatement(sql,params);
int count = pstmt.executeUpdate();
if(count>0)
return true;
else
return false;
}catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
finally {
// closeAll(null,pstmt,connection);
}
}
public static ResultSet executeQuery(String sql,Object[]params ) {
List<Student> students= new ArrayList<>();
Student student =null;
try {
//String sql="select * from student ";
pstmt= createPreparedStatement(sql, params);
rs = pstmt.executeQuery();
return rs;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
};
public static void closeAll(ResultSet rs,Statement stmt,Connection connection) {
try {
if(rs!=null)rs.close();
if(pstmt!=null)pstmt.close();
if(connection!=null)connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
IStudentDao 下面写Dao的接口
package org.student.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.student.entity.Student;
public interface IStudentDao {
public boolean isExist(int sno);
public int getTotalCount();
//int currentPage 页码 pageSize数据条数
public List<Student> queryStudentsByPage(int currentPage,int pageSize);
public boolean addStudent(Student student);
public boolean deleteStudentBySno(int sno);
public boolean updateStudentBySno(int sno, Student student) ;
public List<Student> queryAll();
public Student queryStudentBysno(int sno);
}
StudentDaoImpl.java
package org.student.dao.impl;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import org.student.dao.IStudentDao;
import org.student.entity.Student;
import oge.student.util.DBUtil;
import sun.security.pkcs11.Secmod.DbMode;
public class StudentDaoImpl implements IStudentDao{
private final String URL="jdbc:oracle:thin:@localhost:1521:orcl";
private final String USERNAME="sys as sysdba";
private final String PASSWORD="123456";
PreparedStatement pstmt=null;
ResultSet rs=null;
Student student =null;
public boolean isExist(int sno) {
return queryStudentBysno(sno)==null?false:true;
}
public boolean addStudent(Student student) {
String sql="insert into student values(?,?,?,?)";
Object[] params= {student.getSno(),student.getSname(),student.getSage(),student.getSaddress()};
return DBUtil.executeupdate(sql, params);
}
public boolean deleteStudentBySno(int sno) {
String sql="delete from student where sno = ?";
Object[] params= {sno};
return DBUtil.executeupdate(sql, params);
}
public boolean updateStudentBySno(int sno, Student student) {
String sql="update student set sname=?,sage=?,saddress=? where sno=?";
Object[] params= {student.getSname(),student.getSage(),student.getSaddress(),sno};
return DBUtil.executeupdate(sql, params);
}
public List<Student> queryAll() {
PreparedStatement pstmt=null;
Student student =null;
List<Student> students= new ArrayList<>();
try {
String sql="select * from student ";
rs = DBUtil.executeQuery(sql, null);
// rs = pstmt.executeQuery();
while(rs.next()) {
int no= rs.getInt("sno");
String name= rs.getString("sname");
int age= rs.getInt("sage");
String address= rs.getString("saddress");
student= new Student(no,name,age,address);
students.add(student);
}
return students;
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
finally {
try {
if(rs!=null)rs.close();
if(pstmt!=null)pstmt.close();
if(DBUtil.connection!=null)DBUtil. connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
public Student queryStudentBysno(int sno) {
try {
String sql ="select * from student where sno=?";
Object[] params= {sno};
rs = DBUtil.executeQuery(sql, params);
//rs= pstmt.executeQuery();
if(rs.next()) {
int no= rs.getInt("sno");
String name= rs.getString("sname");
int age= rs.getInt("sage");
String address= rs.getString("saddress");
student= new Student(no,name,age,address);
}
return student;
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
finally {
DBUtil. closeAll(rs,pstmt,DBUtil. connection);
}
}
@Override
public int getTotalCount() {
String sql="select count(1) from student";
return DBUtil.getTotalCount(sql);
}
@Override
public List<Student> queryStudentsByPage(int currentPage, int pageSize) {
String sql="select * from"
+"("
+ " select rownum r,t.* from "
+ "(select s.* from student s order by sno asc)t "
+ "where rownum<=?"
+ ")"
+ "where r>=?";
Object[] params= { currentPage*pageSize,(currentPage-1)*pageSize+1 };
List<Student> students= new ArrayList<>();
ResultSet rs= DBUtil.executeQuery(sql,params);
try {
while(rs.next()){
Student student = new Student(rs.getInt("sno"),rs.getString("sname"),
rs.getInt("sage"),
rs.getString("saddress"));
students.add(student);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return students;
}
}
Page.java 写分页
package org.student.entity;
import java.util.List;
public class Page {
private int currentPage;
private int pageSize;
private int totalCount;
private int totalPage;
private List<Student> students;
public Page() {
}
public Page(int currentPage, int pageSize, int totalCount, int totalPage, List<Student> students) {
super();
this.currentPage = currentPage;
this.pageSize = pageSize;
this.totalCount = totalCount;
this.totalPage = totalPage;
this.students = students;
}
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;
this.totalPage= this.totalCount%this.pageSize==0?this.totalCount/this.pageSize:(this.totalCount/this.pageSize)+1;
this.pageSize = pageSize;
}
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;
//}
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
}
Student 类 封装成javabean
package org.student.entity;
public class Student {
private int sno;
private String sname;
private int sage;
private String saddress;
public Student() {};
public Student(int sno, String sname, int sage, String saddress) {
super();
this.sno = sno;
this.sname = sname;
this.sage = sage;
this.saddress = saddress;
}
public Student( String sname, int sage, String saddress) {
super();
this.sname = sname;
this.sage = sage;
this.saddress = saddress;
}
public int getSno() {
return sno;
}
public void setSno(int sno) {
this.sno = sno;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public int getSage() {
return sage;
}
public void setSage(int sage) {
this.sage = sage;
}
public String getSaddress() {
return saddress;
}
public void setSaddress(String saddress) {
this.saddress = saddress;
}
public String toString() {
return this.getSno()+"-"+this.getSname()+"-"+this.getSage()+"-"+this.getSaddress();
}
}
IStudentService.java 服务层接口
package org.student.service;
import java.util.List;
import org.student.entity.Student;
public interface IStudentService {
public boolean addStudent(Student student) ;
public boolean deleteStudentBySno(int sno);
public boolean updateStudentBySno(int sno ,Student student) ;
public List<Student> queryAllStudents();
public Student queryStudentBySno(int sno) ;
public List<Student> queryStudentByPage(int currentPage , int pageSize);
public int getTotalCount();
}
StudentServiceImpl.java 实现
package org.student.service.impl;
import java.util.List;
import org.student.dao.IStudentDao;
import org.student.dao.impl.StudentDaoImpl;
import org.student.entity.Student;
import org.student.service.IStudentService;
//业务逻辑层
public class StudentServiceImpl implements IStudentService {
IStudentDao studentDao =new StudentDaoImpl();
public boolean addStudent(Student student) {
if(!studentDao.isExist(student.getSno())){
studentDao.addStudent(student);
return true;
}
else {
System.out.println("此人已经存在");
return false;
}
}
public boolean deleteStudentBySno(int sno) {
if(studentDao.isExist(sno)) {
return studentDao.deleteStudentBySno(sno);
}
return false;
}
public boolean updateStudentBySno(int sno ,Student student) {
if(studentDao.isExist(sno)) {
studentDao.updateStudentBySno(sno, student);
System.out.println("修改成功");
return true;
}
else {
System.out.println("修改失败");
return false;
}
}
public Student queryStudentBySno(int sno) {
return studentDao.queryStudentBysno(sno);
}
public List<Student> queryAllStudents() {
return studentDao.queryAll();
}
@Override
public List<Student> queryStudentByPage(int currentPage, int pageSize) {
return studentDao.queryStudentsByPage(currentPage, pageSize);
}
@Override
public int getTotalCount() {
// TODO Auto-generated method stub
return studentDao.getTotalCount() ;
}
}
AddStudentServlet Servlet层 增加信息操作
package org.student.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.student.entity.Student;
import org.student.service.IStudentService;
import org.student.service.impl.StudentServiceImpl;
public class AddStudentServlet extends HttpServlet {
private PrintWriter writer;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int sno=Integer.parseInt(request.getParameter("sno"));
String name=request.getParameter("sname");
int age=Integer.parseInt(request.getParameter("sage"));
String address = request.getParameter("saddress");
Student student =new Student(sno,name,age,address);
IStudentService studentService = new StudentServiceImpl();
boolean result= studentService.addStudent(student);
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
if(result) {
request.setAttribute("error", "success");
out.print("添加成功");
// response.sendRedirect("QueryAllStudentServlet");
}
else {
request.setAttribute("error","addError"); // 增加失败
/// response.sendRedirect("QueryAllStudentServlet");
//request.getRequestDispatcher("QueryAllStudentServlet").forward(request, response);
}
request.getRequestDispatcher("QueryStudentByPage").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
DeleteStudentServlet.java
package org.student.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.student.service.IStudentService;
import org.student.service.impl.StudentServiceImpl;
public class DeleteStudentServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
int no = Integer.parseInt(request.getParameter("sno"));
IStudentService service = new StudentServiceImpl();
boolean result = service.deleteStudentBySno(no);
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("utf-8");
if(result) {
response.getWriter().print("删除成功");
response.sendRedirect("QueryStudentByPage");
}
else {
response.getWriter().print("删除失败");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
QueryStudentByPage.java 分页并显示数据
package org.student.servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.student.entity.Page;
import org.student.entity.Student;
import org.student.service.IStudentService;
import org.student.service.impl.StudentServiceImpl;
public class QueryStudentByPage extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
IStudentService studentService = new StudentServiceImpl();
int totalCount =studentService.getTotalCount();
Page page= new Page();
page.setTotalCount(totalCount);
String cPage= request.getParameter("currentPage");
if(cPage==null) {
cPage="1";
}
Integer currentPage= Integer.parseInt(cPage);
page.setCurrentPage(currentPage);
int pageSize=3;
page.setPageSize(pageSize);
List<Student> students= studentService.queryStudentByPage(currentPage, pageSize);
page.setStudents(students);
request.setAttribute("p", page);
//page.getStudents();
request.getRequestDispatcher("index.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
QueryStudentBySnoServlet.java 根据学号查学生 / 方便修改学生信息
package org.student.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.student.entity.Student;
import org.student.service.IStudentService;
import org.student.service.impl.StudentServiceImpl;
public class QueryStudentBySnoServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
int no = Integer.parseInt(request.getParameter("sno"));
IStudentService service = new StudentServiceImpl();
Student student = service.queryStudentBySno(no);
request.setAttribute("student",student) ;
request.getRequestDispatcher("StudentInfo.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
UpdateStudentBySnoServlet.java 更新操作
package org.student.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.student.entity.Student;
import org.student.service.IStudentService;
import org.student.service.impl.StudentServiceImpl;
public class UpdateStudentBySnoServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
int no = Integer.parseInt( request.getParameter("sno")) ;
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("utf-8");
String name = request.getParameter("sname");
int age = Integer.parseInt( request.getParameter("sage")) ;
String address= request.getParameter("saddress");
Student student= new Student(name,age,address);
IStudentService service = new StudentServiceImpl();
boolean result = service.updateStudentBySno(no, student);
if(result) {
response.getWriter().print("修改成功");
response.sendRedirect("QueryStudentByPage");
}
else {
response.getWriter().print("修改失败");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
add.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/jquery-3.4.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
});
function check(){
var sno = $("#sno").val();
var sname = $("#sname").val();
var sage = $("#sage").val();
var saddress = $("#saddress").val();
if(sname==null || sname==""){
alert("姓名不能为空");
return false;
}
if(!(sname.length > 1 && sname.length<5)){
alert("姓名有误");
return false;
}
return true;
}
</script>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body> <!-- onsubmit="return check()"-->
<form action="AddStudentServlet" method="POST" >
学号:<input type="text" name="sno" id="sno"><br/>
姓名:<input type="text" name="sname" id="sname"><br/>
年龄:<input type="text" name="sage" id="sage"><br/>
地址:<input type="text" name="saddress" id="saddress"><br/>
<input type="submit" value="提交" ><br/>
</form>
</body>
</html>
index.jsp
<%@page import="org.student.entity.Page"%>
<%@page import="org.student.entity.Student"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/jquery-3.4.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("tr:odd").css("background-color","lightgray");
});
</script>
<meta charset="UTF-8">
<title>学生信息</title>
</head>
<body>
<%
String error = (String)request.getAttribute("error");
if(error!=null){
if(error.equals("addError")){
out.print("增加失败");
}
else if(error.equals("success")) out.print("增加成功");}
%>
<table border="1px">
<tr>
<th>学号</th>
<th>姓名</th>
<th>年龄</th>
<th>地址</th>
<th>操作</th>
</tr>
<%
Page p =(Page) request.getAttribute("p");
for(Student student:p.getStudents()){
%>
<tr>
<td><a href="QueryStudentBySnoServlet?sno=<%=student.getSno()%>"><%=student.getSno()%></a></td>
<td><%=student.getSname()%></td>
<td><%=student.getSage()%></td>
<td><%=student.getSaddress()%></td>
<td><a href="DeleteStudentServlet?sno=<%=student.getSno()%>">删除</a></td>
</tr>
<%
}
%>
</table>
<a href="add.jsp">新增</a><br/>
<%
if(p.getCurrentPage() ==1)
{%>
<a href="QueryStudentByPage?currentPage=1"> 首页</a>
<a href="QueryStudentByPage?currentPage=<%=p.getCurrentPage()+1%>"> 下一页</a>
<% }
else if(p.getCurrentPage() == p.getTotalPage()){%>
<a href="QueryStudentByPage?currentPage=<%=p.getCurrentPage()-1%>"> 上一页</a>
<a href="QueryStudentByPage?currentPage=1<%=p.getTotalPage() %>"> 尾页</a>
<% }
else { %>
<a href="QueryStudentByPage?currentPage=1"> 首页</a>
<a href="QueryStudentByPage?currentPage=<%=p.getCurrentPage()-1%>"> 上一页</a>
<a href="QueryStudentByPage?currentPage=<%=p.getCurrentPage()+1%>"> 下一页</a>
<a href="QueryStudentByPage?currentPage=<%=p.getTotalPage() %>"> 尾页</a>
<% }%>
</body>
</html>
StudentInfo.jsp
<%@page import="org.student.entity.Student"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
Student student = (Student) request.getAttribute("student");
%>
<form action="UpdateStudentBySnoServlet" >
学号:<input type="text" name="sno" value="<%=student.getSno()%>" readonly="readonly"><br/>
姓名:<input type="text" name="sname" value="<%=student.getSname()%>"><br/>
年龄:<input type="text" name="sage" value="<%=student.getSage()%>"><br/>
地址:<input type="text" name= "saddress" value="<%=student.getSaddress()%>"><br/>
<input type="submit" value="修改"/>
<a href="QueryAllStudentServlet">返回</a>
</form>
</body>
</html>
下面是演示视频
上一篇: js不跳转传值php
下一篇: html div标签什么意思