这一次的设计我用到了JSP, Servlet, Maven,JDBC,Tomcat,Oracle数据库。我学习了B站的javaweb课程,就是那个黑马程序员的课程,听了关于以上技术的部分,时间实在太紧,没办法听完。但是我之前有xml的基础,所以这部分的内容也需要听一下才能做好这一次的设计。这一次开发我用的是IDEA。
废话就不说了,一步一步的来。
首先要明确自己的功能,你是想做一个什么样的系统,又要用到那些表,创建表的时候又要那些属性,这些时必须先要弄明白的。我课程设计做的是一个学生宿舍管理系统,前端用网页展示我在这里就只写登录页面和宿舍表的增删改查。
我用的是oracle数据库,当然mysql的数据库也是一样的,sql语句稍微有一点区别。
首先创建表
CREATE TABLE Student(
Sno VARCHAR(10) PRIMARY KEY,
Sname VARCHAR(12) NOT NULL,
Ssex CHAR(4),
Stelephone VARCHAR(12) UNIQUE,
department VARCHAR(30),
password VARCHAR(10)
);//创建学生表
CREATE SEQUENCE squence_of_Student//创建学生表序列
INCREMENT BY 1
START WITH 20231001
MINVALUE 20231001;
//插入数据
INSERT INTO Student(Sno,Sname,Ssex,password,Stelephone,department)values(squence_of_Student.nextval,'张三','男','20231001','18956304722','计算机学院');
INSERT INTO Student(Sno,Sname,Ssex,password,Stelephone,department)values(squence_of_Student.nextval,'李丽','女','20231002','17328453433','计算机学院');
INSERT INTO Student(Sno,Sname,Ssex,password,Stelephone,department)values(squence_of_Student.nextval,'朱莉','女','20231003','15523476982','临床医学院');
INSERT INTO Student(Sno,Sname,Ssex,password,Stelephone,department)values(squence_of_Student.nextval,'薛菱','女','20231004','17956348729','药学院');
INSERT INTO Student(Sno,Sname,Ssex,password,Stelephone,department)values(squence_of_Student.nextval,'凌归','男','20231005','17034867859','计算机学院');
INSERT INTO Student(Sno,Sname,Ssex,password,Stelephone,department)values(squence_of_Student.nextval,'常贵','男','20231006','13327684390','临床医学院');
INSERT INTO Student(Sno,Sname,Ssex,password,Stelephone,department)values(squence_of_Student.nextval,'朱琳','女','20231007','16934075439','计算机学院');
INSERT INTO Student(Sno,Sname,Ssex,password,Stelephone,department)values(squence_of_Student.nextval,'曾可','女','20231008','15745903456','药学院');
INSERT INTO Student(Sno,Sname,Ssex,password,Stelephone,department)values(squence_of_Student.nextval,'张科','男','20231009','18845092543','临床医学院');
INSERT INTO Student(Sno,Sname,Ssex,password,Stelephone,department)values(squence_of_Student.nextval,'李杨','男','20231010','17426478935','计算机学院');
CREATE TABLE HouseMaster(
HMno VARCHAR2(10) PRIMARY KEY,
HMname VARCHAR2(12) NOT NULL,
HMsex CHAR(4),
HMtelephone VARCHAR2(12) UNIQUE,
password VARCHAR2(10)
);//宿舍管理员表
DROP SEQUENCE squence_of_HouseMaster;//宿舍管理员编号序列
CREATE SEQUENCE squence_of_HouseMaster
INCREMENT BY 1
START WITH 231001
MINVALUE 231001;
//插入宿舍管理员表的序列
INSERT INTO HouseMaster(HMno,HMname,HMsex,password,HMtelephone)values(squence_of_HouseMaster.nextval,'张岭','男','231001','18956304722');
INSERT INTO HouseMaster(HMno,HMname,HMsex,password,HMtelephone)values(squence_of_HouseMaster.nextval,'李韵','女','231002','15634279575');
CREATE TABLE Manager(
Mno VARCHAR(10) PRIMARY KEY,
Mname VARCHAR(12) NOT NULL,
Msex CHAR(4) DEFAULT '男' CHECK(Msex='男'or Msex='女'),
Mtelephone VARCHAR2(12) UNIQUE,
password VARCHAR(10)
);//管理员表
drop SEQUENCE squence_of_Manager;//管理员编号序列
CREATE SEQUENCE squence_of_Manager
INCREMENT BY 1
START WITH 1001
MINVALUE 1001;
//插入管理员表数据
INSERT INTO Manager(Mno,Mname,Msex,password,Mtelephone)values(squence_of_Manager.nextval,'云宇','男','1001','17635478714');
INSERT INTO Manager(Mno,Mname,Msex,password,Mtelephone)values(squence_of_Manager.nextval,'李艳','女','1002','18534905687');
CREATE TABLE House(
hno VARCHAR2(10) primary key,
num number,
HMno VARCHAR2(10) references HouseMaster(HMno),
Hmessage char(250)
);//创建宿舍表
//插入宿舍表数据
INSERT INTO House(hno,num,HMno,Hmessage)values('1-1-01',4,'231001','今天下午大扫除');
INSERT INTO House(hno,num,HMno,Hmessage)values('1-1-02',6,'231001','今天下午大扫除');
INSERT INTO House(hno,num,HMno,Hmessage)values('1-1-03',4,'231001','今天下午大扫除');
INSERT INTO House(hno,num,HMno,Hmessage)values('1-1-04',8,'231001','今天下午大扫除');
INSERT INTO House(hno,num,HMno,Hmessage)values('1-1-05',4,'231001','今天下午大扫除');
INSERT INTO House(hno,num,HMno,Hmessage)values('2-1-01',4,'231002','无');
INSERT INTO House(hno,num,HMno,Hmessage)values('2-1-02',6,'231002','无');
INSERT INTO House(hno,num,HMno,Hmessage)values('2-1-03',4,'231002','无');
INSERT INTO House(hno,num,HMno,Hmessage)values('2-1-04',8,'231002','无');
INSERT INTO House(hno,num,HMno,Hmessage)values('2-1-05',4,'231002','无');
CREATE TABLE Allocation(
Ano VARCHAR2(10) PRIMARY KEY,
hno VARCHAR2(10) references House(hno),
badno varchar2(2),
Sno VARCHAR2(10) references Student(Sno),
HMno VARCHAR2(10) references HouseMaster(HMno)
);//宿舍分配表
drop SEQUENCE squence_of_Allocation;//创建宿舍分配号序列
CREATE SEQUENCE squence_of_Allocation
INCREMENT BY 1
START WITH 1
MINVALUE 1;
//插入分配表数据
INSERT INTO Allocation(Ano,hno,Sno,badno,HMno)values(squence_of_Allocation.nextval,'1-1-01','20231001',1,'231001');
INSERT INTO Allocation(Ano,hno,Sno,badno,HMno)values(squence_of_Allocation.nextval,'1-1-01','20231005',2,'231001');
INSERT INTO Allocation(Ano,hno,Sno,badno,HMno)values(squence_of_Allocation.nextval,'1-1-01','20231006',3,'231001');
INSERT INTO Allocation(Ano,hno,Sno,badno,HMno)values(squence_of_Allocation.nextval,'1-1-01','20231009',4,'231001');
INSERT INTO Allocation(Ano,hno,Sno,badno,HMno)values(squence_of_Allocation.nextval,'2-1-01','20231002',1,'231002');
INSERT INTO Allocation(Ano,hno,Sno,badno,HMno)values(squence_of_Allocation.nextval,'2-1-01','20231003',2,'231002');
INSERT INTO Allocation(Ano,hno,Sno,badno,HMno)values(squence_of_Allocation.nextval,'2-1-01','20231004',3,'231002');
INSERT INTO Allocation(Ano,hno,Sno,badno,HMno)values(squence_of_Allocation.nextval,'2-1-01','20231007',4,'231002');
INSERT INTO Allocation(Ano,hno,Sno,badno,HMno)values(squence_of_Allocation.nextval,'1-1-02','20231010',1,'231001');
INSERT INTO Allocation(Ano,hno,Sno,badno,HMno)values(squence_of_Allocation.nextval,'2-1-02','20231008',1,'231002');
//创建了两个视图方便数据查询
create or replace view house_student
AS select hno,Student.Sno,Sname,Ssex,Stelephone,department,badno from Student,Allocation
where Student.Sno=Allocation.Sno;
create or replace view house_master
AS select House.hno,HouseMaster.HMno,HMname,HMtelephone,Hmessage from HouseMaster,Allocation,House
where HouseMaster.HMno=Allocation.HMno and House.hno=Allocation.hno;
创建好数据库中的表之后就可以开始IDEA部分了
什么?idea还没有下载?我当时是在B站找了一个安装破解版的idea的视频一步一步来的,你们也可以试试。
还需要下载maven和tomcat并在idea上配置maven,详细请见我的博客文章http://t.csdn.cn/cxQUK
配置好了之后就是创建项目了file->new->project
之后就是这个样子
会弹出小方框
检查项目名称是不是刚才创建的项目名称,不是的话要改一下,然后点击OK就好了。
成功后目录变成这样
记得要看web这个文件夹上面有小蓝点,如果没有应该是目录路径出现问题,路径不一致导致的,建议删掉重新创建,步骤和上面一样。
接下来解释tomcat的配置,这个前提是安装好了tomcat并进行了相关的配置工作。安装和配置我会写在别的文章中。
在pom.xml这个文件中加入如图的build代码
点击框出来的小方框就可以了,检查成功与否,可以选中项目名称并且右击选择 run maven,看下下面是否有tomcat run,有就成功了。
然后就可以正式开始了,首先是JDBC,创建数据池连接数据库,先选中java然后右击new->package,名字为com,然后选中com再new一个package,名字是util,再选中util然后new一个javaclass,名字是DButil。成功之后如下图:
DButil的代码
package com.util;//包名
import java.sql.*;
public class DButil {
public Connection getCon() throws Exception {
String url = "jdbc:oracle:thin:@127.0.0.1:1521/ORACLE_50";//ORACLE_50改为自己的数据库名,1521是默认的端口号,如果你更改了oracle数据库的端口号就要改成你自己的。
String user = "sys as sysdba";//你的用户名
String password = "Sa123456";//你的oracle登录密码
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = (Connection) DriverManager.getConnection(url, user, password);
return conn;
}
public void closeCon(Connection con) throws Exception {
if(con!=null) {
con.close();
}
}
public static void main(String[] args) {
DButil dbUtil = new DButil();
try {
dbUtil.getCon();
} catch (Exception e) {
System.out.println("no");
e.printStackTrace();
}
}
}
还要导入项目相关的jar包,如果没有maven就需要自己建一个文件夹导入相关的包,有Maven就修改pom.xml文件的内容,在project内加入如下内容
<dependencies>
<dependency>
<groupId>cn.easyproject</groupId>
<artifactId>ojdbc7</artifactId>
<version>12.1.0.2.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
</dependencies>
然后就是创建实体类,先在com包中创建一个包名字是model,再在里面分别创建自己在数据库中创建的所有表的实体类,也就是在model中创建Student, HouseMaster ,Manager ,House ,house_student ,house_master ,PageBean(如果展示在前端的时候不需要页码的话可以不写)这几个类,类中的属性就写自己在数据库中定义的属性,再加上get ,set方法,以及构造方法。
以学生类为例
package com.model;
public class Student {
private String Sno;
private String Sname;
private String Ssex;
private String password;
private String Stelephone;
private String department;
public Student() {}
public Student(String sno, String password) {
this.Sno = sno;
this.password = password;
}
public Student(String sno) {
this.Sno = sno;
}
public Student(String sno, String sname, String ssex, String password, String stelephone, String department) {
this.Sno = sno;
this.Sname = sname;
this.Ssex = ssex;
this.password = password;
this.Stelephone = stelephone;
this.department = department;
}
public String getSno() {
return Sno;
}
public void setSno(String sno) {
Sno = sno;
}
public String getSname() {
return Sname;
}
public void setSname(String sname) {
Sname = sname;
}
public String getSsex() {
return Ssex;
}
public void setSsex(String ssex) {
Ssex = ssex;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getStelephone() {
return Stelephone;
}
public void setStelephone(String stelephone) {
Stelephone = stelephone;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
}
PageBean:
package com.model;
public class PageBean {
private int page; // 第几页
private int pageSize; // 每页记录数
private int start; // 起始页
public PageBean(int page, int pageSize) {
super();
this.page = page;
this.pageSize = pageSize;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getStart() {
return (page-1)*pageSize;
}
}
其他几个类都和Student类差不多,都是数据库中的属性。
创建完实体类后就是SQL语句了,各种增删改查,所以我在com包中又创建了一个Dao包,在里面创建了UserDao和HouseDao这两个类,一个用来放登录时对数据库进行查找用户相关的代码,另外一个来放对House表的增删改查的代码。
UserDao
package com.dao;//包不一样的记得改掉
import com.model.HouseMaster;
import com.model.Manager;
import com.model.Student;
import java.sql.*;
public class UserDao {
public Manager Login(Connection con,Manager manager) throws SQLException {
Manager resultmanager = null;
String sql = "select * from Manager where Mno=? and password=?";//sql语句
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, manager.getMno());//填充?占位符
pstmt.setString(2, manager.getPassword());
ResultSet rs = pstmt.executeQuery();//执行SQL语句,并把查到的结果返回给rs,一般查询语句用executeQuery(),更新,删除,修改用executeUpdate()。
if(rs.next()) {
resultmanager = new Manager();
resultmanager.setMno(rs.getString("Mno"));
resultmanager.setPassword(rs.getString("password"));
resultmanager.setMname(rs.getString("Mname"));
resultmanager.setMsex(rs.getString("Msex"));
}
return resultmanager;//返回查到的结果
}
public HouseMaster Login(Connection con, HouseMaster houseMaster) throws SQLException {
HouseMaster resulthouseMaster = null;
String sql = "select * from HouseMaster where HMno=? and password=?";
PreparedStatement pstmt1 = con.prepareStatement(sql);
pstmt1.setString(1, houseMaster.getHMno());
pstmt1.setString(2, houseMaster.getPassword());
ResultSet rs = pstmt1.executeQuery();
if(rs.next()) {
resulthouseMaster = new HouseMaster();
resulthouseMaster.setHMno(rs.getString("HMno"));
resulthouseMaster.setPassword(rs.getString("password"));
resulthouseMaster.setHMname(rs.getString("HMname"));
resulthouseMaster.setHMsex(rs.getString("HMsex"));
}
return resulthouseMaster;
}
public Student Login(Connection con, Student student) throws SQLException {
Student resultstudent = null;
String sql = "select * from Student where Sno=? and password=?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, student.getSno());
pstmt.setString(2, student.getPassword());
ResultSet rs = pstmt.executeQuery();
if(rs.next()) {
resultstudent = new Student();
resultstudent.setSno(rs.getString("Sno"));
resultstudent.setPassword(rs.getString("password"));
resultstudent.setSname(rs.getString("Sname"));
resultstudent.setSsex(rs.getString("Ssex"));
}
return resultstudent;
}
//更新密码的操作,相关的sql语句
public int managerUpdate(Connection con, String Mno, String password)throws Exception {
String sql = "update Manager set password=? where Mno=?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, password);
pstmt.setString(2, Mno);
return pstmt.executeUpdate();
}
public int houseMasterUpdate(Connection con, String HMno, String password)throws Exception {
String sql = "update HouseMaster set password=? where HMno=?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, password);
pstmt.setString(2, HMno);
return pstmt.executeUpdate();
}
public int studentUpdate(Connection con, String Sno, String password)throws Exception {
String sql = "update Student set password=? where Sno=?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, password);
pstmt.setString(2, Sno);
return pstmt.executeUpdate();
}
}
HouseDao:
package com.dao;
import com.model.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
public class HouseDao {
public List<House> houseList(Connection con, PageBean pageBean, House house) throws Exception {
List<House> houseList = new ArrayList<House>();
StringBuffer sb = new StringBuffer("select * from House");
PreparedStatement pstmt = con.prepareStatement(sb.toString());
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
House dormBuild = new House();
dormBuild.setHno(rs.getString("hno"));
dormBuild.setNum(rs.getInt("num"));
dormBuild.setHMno(rs.getString("HMno"));
dormBuild.setHmessage(rs.getString("Hmessage"));
houseList.add(dormBuild);
}
return houseList;
}
public static List<house_student> house_studentlist(Connection con, String hno) throws Exception {
List<house_student> house_studentsList = new ArrayList<house_student>();
StringBuffer hm = new StringBuffer("select * from house_student where hno='"+ hno +"'");
PreparedStatement pstmt = con.prepareStatement(hm.toString());
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
house_student hs = new house_student();
hs.setHno(rs.getString("hno"));
hs.setSno(rs.getString("Sno"));
hs.setSname(rs.getString("Sname"));
hs.setSsex(rs.getString("Ssex"));
hs.setStelephone(rs.getString("Stelephone"));
hs.setDepartment(rs.getString("department"));
hs.setBadno(rs.getString("badno"));
house_studentsList.add(hs);
}
return house_studentsList;
}
public static List<house_student> house_studentone(Connection con, String sno) throws Exception {
List<house_student> house_studentsList = new ArrayList<house_student>();
StringBuffer hm = new StringBuffer("select * from house_student where Sno='"+ sno +"'");
PreparedStatement pstmt = con.prepareStatement(hm.toString());
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
house_student student = new house_student();
student.setHno(rs.getString("hno"));
student.setSno(rs.getString("Sno"));
student.setSname(rs.getString("Sname"));
student.setSsex(rs.getString("Ssex"));
student.setStelephone(rs.getString("Stelephone"));
student.setDepartment(rs.getString("department"));
student.setBadno(rs.getString("badno"));
house_studentsList.add(student);
}
return house_studentsList;
}
public static List<house_master> house_hmasterlist(Connection con, String hmno) throws Exception {
List<house_master> housemasterList = new ArrayList<house_master>();
StringBuffer hm = new StringBuffer("select * from house_master where HMno='" + hmno + "'");
PreparedStatement pstmt = con.prepareStatement(hm.toString());
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
house_master hs = new house_master();
hs.setHno(rs.getString("hno"));
hs.setHMno(rs.getString("HMno"));
hs.setHMname(rs.getString("HMname"));
hs.setHMtelephone(rs.getString("HMtelephone"));
hs.setHmessage(rs.getString("Hmessage"));
housemasterList.add(hs);
}
return housemasterList;
}
public int houseCount(Connection con, House house) throws Exception {
StringBuffer sb = new StringBuffer("select count(*) as total from House");
PreparedStatement pstmt = con.prepareStatement(sb.toString());
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
return rs.getInt("total");
} else {
return 0;
}
}
public int houseAdd(Connection con, House house) throws Exception {
String sql = "insert into House(hno,num,HMno,Hmessage)values(?,?,?,?)";
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, house.getHno());
stmt.setInt(2,house.getNum());
stmt.setString(3, house.getHMno());
stmt.setString(4, house.getHmessage());
return stmt.executeUpdate();
}
public int houseDelete(Connection con, String hno) throws Exception {
String sql = "delete from House where hno=?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, hno);
return pstmt.executeUpdate();
}
public int houseUpdate(Connection con, House house) throws Exception {
String sql = "update House set num=?,HMno=?,Hmessage=? where hno=?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setInt(1,house.getNum());
pstmt.setString(2,house.getHMno());
pstmt.setString(3, house.getHmessage());
pstmt.setString(4, house.getHno());
return pstmt.executeUpdate();
}
public static House houseShow(Connection con, String hno) throws Exception {
String sql = "select * from House where hno=?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, hno);
ResultSet rs = pstmt.executeQuery();
House house = new House();
if (rs.next()) {
house.setHno(rs.getString("hno"));
house.setHMno(rs.getString("num"));
house.setHMno(rs.getString("HMno"));
house.setHmessage(rs.getString("Hmessage"));
}
return house;
}
}
这里面的函数功能写自己规划好的功能的,语句都差不多。
然后就是中间的servlet,来调用刚才dao这个包中的SQL语句去数据库进行一系列的操作,并且把得到的结果和前端的jsp页面进行交互
我就又在com包中创建了一个Servlet包,我所有的目录创建完成之后,java包是这样的
webapp也就是之前创建的web是这样的,webapp是我自己之前创建的。
Servlet包中就以loginservlet和HouseServlet为例展示一下,servlet的重点在获取前端数据,并且调用Dao中的方法,获取或者更新数据库信息,并且对前端做一个反馈
package com.Servlet;
import com.dao.UserDao;
import com.model.HouseMaster;
import com.model.Manager;
import com.model.Student;
import com.util.DButil;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.Connection;
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
DButil dbUtil = new DButil();
UserDao userDao = new UserDao();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
HttpSession session = request.getSession();
String userName = request.getParameter("username");//获取前端数据
String password = request.getParameter("password");
String userType = request.getParameter("type");
Connection con = null;
try {
con =dbUtil.getCon();
Manager currentmanager = null;
HouseMaster currenthouseMaster = null;
Student currentStudent = null;
if("manager".equals(userType)) {
Manager manager = new Manager(userName,password);
currentmanager = userDao.Login(con, manager);//调用Login并且接受返回结果
if(currentmanager == null) {
request.setAttribute("user", manager);
request.setAttribute("currentUserType", "manager");
request.setAttribute("error", "用户名或密码错误!");
request.getRequestDispatcher("/login.jsp").forward(request, response);
} else {
session.setAttribute("currentUserType", "manager");
session.setAttribute("currentUser", currentmanager);
request.setAttribute("mainPage", "manager/blank.jsp");
request.getRequestDispatcher("mainManager.jsp").forward(request, response);//进行页面的跳转
}
} else if("housemaster".equals(userType)) {
HouseMaster houseMaster = new HouseMaster(userName,password);
currenthouseMaster = userDao.Login(con,houseMaster);
if(currenthouseMaster == null) {
request.setAttribute("user", houseMaster);
request.setAttribute("currentUserType", "housemaster");
request.setAttribute("error", "用户名或密码错误!");
request.getRequestDispatcher("/login.jsp").forward(request, response);
} else {
session.setAttribute("currentUserType", "housemaster");
session.setAttribute("currentUser", currenthouseMaster);
request.setAttribute("mainPage", "housemaster/blank.jsp");
request.getRequestDispatcher("mainhouseMaster.jsp").forward(request, response);
}
} else if("student".equals(userType)) {
Student student = new Student(userName, password);
currentStudent = userDao.Login(con, student);
if(currentStudent == null) {
request.setAttribute("user", student);
request.setAttribute("currentUserType", "student");
request.setAttribute("error", "用户名或密码错误!");
request.getRequestDispatcher("/login.jsp").forward(request, response);
} else {
session.setAttribute("currentUserType", "student");
session.setAttribute("currentUser", currentStudent);
request.setAttribute("mainPage", "student/blank.jsp");
request.getRequestDispatcher("mainStudent.jsp").forward(request, response);
}
}
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
dbUtil.closeCon(con);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
package com.Servlet;
import com.dao.HouseDao;
import com.model.House;
import com.model.PageBean;
import com.model.house_master;
import com.model.house_student;
import com.util.DButil;
import com.util.StringUtil;
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.sql.Connection;
import java.util.List;
@WebServlet("/HouseServlet")
public class HouseServlet extends HttpServlet {
DButil dbUtil = new DButil();
HouseDao houseDao = new HouseDao();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
HttpSession session = request.getSession();
Object currentUserType = session.getAttribute("currentUserType");
String Sno = request.getParameter("Sno");
String hno = request.getParameter("hno");
String HMno = request.getParameter("HMno");
String page = request.getParameter("page");
String action = request.getParameter("action");
House house = new House();
if("preSave".equals(action)) {//查询一条单独的宿舍记录通过宿舍号查询
try {
housePreSave(request, response);
} catch (Exception e) {
throw new RuntimeException(e);
}
return;
} else if("save".equals(action)){//保存,更新,或者增加
houseSave(request, response);
return;
} else if("delete".equals(action)){//删除
houseDelete(request, response);
return;
} else if("list".equals(action)) {//展示宿舍信息
} else if("search".equals(action)){//查找宿舍管
if(StringUtil.isNotEmpty(Sno)){
houseSearch_Sno(request,response);
return;
} else if (StringUtil.isNotEmpty(hno)) {
houseSearch_hno(request,response);
return;
} else if (StringUtil.isNotEmpty(HMno)) {
houseSearch_HMno(request,response);
return;
}
}
if(StringUtil.isEmpty(page)) {
page="1";
}
Connection con = null;
PageBean pageBean = new PageBean(Integer.parseInt(page), 5);
request.setAttribute("pageSize", pageBean.getPageSize());
request.setAttribute("page", pageBean.getPage());
try {
con=dbUtil.getCon();
List<House> houseList = houseDao.houseList(con,pageBean,house);
int total=houseDao.houseCount(con,house);
String pageCode = this.genPagation(total, Integer.parseInt(page), 5);
request.setAttribute("pageCode", pageCode);
request.setAttribute("houseList", houseList);
if ("manager".equals(currentUserType)){
request.setAttribute("mainPage", "manager/house.jsp");
request.getRequestDispatcher("mainManager.jsp").forward(request, response);
} else if ("housemaster".equals(currentUserType)) {
request.setAttribute("mainPage", "housemaster/house.jsp");
request.getRequestDispatcher("mainhouseMaster.jsp").forward(request, response);
}else if ("student".equals(currentUserType)) {
request.setAttribute("mainPage", "student/house.jsp");
request.getRequestDispatcher("mainStudent.jsp").forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
dbUtil.closeCon(con);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void houseSearch_hno(HttpServletRequest request,
HttpServletResponse response){
String hno = request.getParameter("hno");
HttpSession session = request.getSession();
Object currentUserType = session.getAttribute("currentUserType");
Connection con = null;
try {
con = dbUtil.getCon();
List<house_student> house_studentList= houseDao.house_studentlist(con,hno);
request.setAttribute("house_studentList", house_studentList);
if ("manager".equals(currentUserType)){
request.setAttribute("mainPage", "manager/house_student.jsp");
request.getRequestDispatcher("mainManager.jsp").forward(request, response);
} else if ("housemaster".equals(currentUserType)) {
request.setAttribute("mainPage", "housemaster/house_student.jsp");
request.getRequestDispatcher("mainhouseMaster.jsp").forward(request, response);
} else if ("student".equals(currentUserType)) {
request.setAttribute("mainPage", "student/house_student.jsp");
request.getRequestDispatcher("mainStudent.jsp").forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
dbUtil.closeCon(con);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void houseSearch_Sno(HttpServletRequest request,
HttpServletResponse response){
String Sno = request.getParameter("Sno");
HttpSession session = request.getSession();
Object currentUserType = session.getAttribute("currentUserType");
Connection con = null;
try {
con = dbUtil.getCon();
List<house_student> house_student= houseDao.house_studentone(con,Sno);
request.setAttribute("house_studentList", house_student);
if ("manager".equals(currentUserType)){
request.setAttribute("mainPage", "manager/house_student.jsp");
request.getRequestDispatcher("mainManager.jsp").forward(request, response);
} else if ("housemaster".equals(currentUserType)) {
request.setAttribute("mainPage", "housemaster/house_student.jsp");
request.getRequestDispatcher("mainhouseMaster.jsp").forward(request, response);
} else if ("student".equals(currentUserType)) {
request.setAttribute("mainPage", "student/house_student.jsp");
request.getRequestDispatcher("mainStudent.jsp").forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
dbUtil.closeCon(con);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void houseSearch_HMno(HttpServletRequest request,
HttpServletResponse response){
String HMno = request.getParameter("HMno");
HttpSession session = request.getSession();
Object currentUserType = session.getAttribute("currentUserType");
Connection con = null;
try {
con = dbUtil.getCon();
List<house_master> house_masterList=houseDao.house_hmasterlist(con,HMno);
request.setAttribute("house_masterList",house_masterList);
if ("manager".equals(currentUserType)){
request.setAttribute("mainPage", "manager/house_master.jsp");
request.getRequestDispatcher("mainManager.jsp").forward(request, response);
} else if ("housemaster".equals(currentUserType)) {
request.setAttribute("mainPage", "housemaster/house_master.jsp");
request.getRequestDispatcher("mainhouseMaster.jsp").forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
dbUtil.closeCon(con);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void houseDelete(HttpServletRequest request,
HttpServletResponse response) {
String hno = request.getParameter("hno");
Connection con = null;
try {
con = dbUtil.getCon();
houseDao.houseDelete(con,hno);
request.getRequestDispatcher("house?action=list").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
dbUtil.closeCon(con);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void houseSave(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
String hno = request.getParameter("hno");
int num = Integer.parseInt(request.getParameter("num"));
String HMno = request.getParameter("HMno");
String Hmessage = request.getParameter("hmessage");
House house = new House(hno,num,HMno,Hmessage);
Connection con = null;
try {
con = dbUtil.getCon();
House house1 = houseDao.houseShow(con,hno);
int saveNum = 0;
if(StringUtil.isNotEmpty(house1.getHno())) {
saveNum = houseDao.houseUpdate(con, house);
} else {
saveNum = houseDao.houseAdd(con, house);
}
if(saveNum > 0) {
request.getRequestDispatcher("house?action=list").forward(request, response);
} else {
request.setAttribute("hno", hno);
request.setAttribute("error", "保存失败");
request.setAttribute("mainPage", "manager/houseSave.jsp");
request.getRequestDispatcher("mainManager.jsp").forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
dbUtil.closeCon(con);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void housePreSave(HttpServletRequest request, HttpServletResponse response) throws Exception {
String hno = request.getParameter("hno");
Connection con = null;
con = dbUtil.getCon();
House house = houseDao.houseShow(con,hno);
if(StringUtil.isNotEmpty(house.getHno())) {
try {
request.setAttribute("house", house);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
dbUtil.closeCon(con);
} catch (Exception e) {
e.printStackTrace();
}
}
}
request.setAttribute("mainPage", "manager/houseSave.jsp");
request.getRequestDispatcher("mainManager.jsp").forward(request, response);
}
private String genPagation(int totalNum, int currentPage, int pageSize){
int totalPage = totalNum%pageSize==0?totalNum/pageSize:totalNum/pageSize+1;
StringBuffer pageCode = new StringBuffer();
pageCode.append("<li><a href='House?page=1'>首页</a></li>");
if(currentPage==1) {
pageCode.append("<li class='disabled'><a href='#'>上一页</a></li>");
}else {
pageCode.append("<li><a href='House?page="+(currentPage-1)+"'>上一页</a></li>");
}
for(int i=currentPage-2;i<=currentPage+2;i++) {
if(i<1||i>totalPage) {
continue;
}
if(i==currentPage) {
pageCode.append("<li class='active'><a href='#'>"+i+"</a></li>");
} else {
pageCode.append("<li><a href='House?page="+i+"'>"+i+"</a></li>");
}
}
if(currentPage==totalPage) {
pageCode.append("<li class='disabled'><a href='#'>下一页</a></li>");
} else {
pageCode.append("<li><a href='House?page="+(currentPage+1)+"'>下一页</a></li>");
}
pageCode.append("<li><a href='House?page="+totalPage+"'>尾页</a></li>");
return pageCode.toString();
}
}
这些做完就是前端页面的设计,重点是前端怎么把数据放进缓冲区,又怎么从缓冲区拿数据
放数据的话就看一下login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<html>
<head>
<title>登录界面</title>
<style type="text/css">
.center{
text-align:center;
margin-top: 200px;
}
.bu{
background-color: transparent;
outline: none;
color: black;
margin-top: 10px;
}
body{
background: url('resources/images/bg.jpg');
background-size: 100% 100%;
}
input {
background-color: transparent;
outline: none;
color: black;
}
.commit{
background-color: transparent;
outline: none;
color: black;
margin-top: 10px;
}
</style>
</head>
<body>
<div class="center">
<h1>登录界面</h1>
<form method="post" action="/dormitory/loginServlet">
用户名:<input type="text" name="username" style="width: 300px;height: 50px" placeholder="请输入用户名:" > <br>
密码: <input type="password" name="password" style="width: 300px;height: 50px" placeholder="请输入密码:" > <br>
<select name="type" class="bu">
<option value="student">学生</option>
<option value="housemaster">宿舍管理员</option>
<option value="manager">管理员</option>
</select><br>
<button type="submit" style="width:80px;height:40px; font-size: 20px" class="commit">登录</button><br>
<%
request.setCharacterEncoding("utf-8");
String user = (String) session.getAttribute("username");//获取输入框中的内容
String pass = (String) session.getAttribute("password");
String type = (String) session.getAttribute("type");
String user1 = request.getParameter(user);
session.setAttribute("username",user1);//把内容放进缓冲区,用username来表示,所以在前面的HouseServlet中可以获取username中的数据。
String pass1 = request.getParameter(pass);
session.setAttribute("password",pass1);
String type1 = request.getParameter(type);
session.setAttribute("type",type1);
%>
</div>
</form>
</body>
</html>
然后就是前端获取数据就是展示所有宿舍信息的house.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="utf-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>pageEncoding="utf-8"
<html>
<head>
<title>宿舍信息</title>
<script type="text/javascript">
$(document).ready(function(){
$("ul li:eq(3)").addClass("active");
$('.dataTable').dataTable( {
"oLanguage": {
"sProcessing": "处理中...",
"sLengthMenu": "_MENU_ 记录/页",
"sZeroRecords": "没有匹配的记录",
"sInfo": "显示第 _START_ 至 _END_ 项记录,共 _TOTAL_ 项",
"sInfoEmpty": "显示第 0 至 0 项记录,共 0 项",
"sInfoFiltered": "(由 _MAX_ 项记录过滤)",
"sInfoPostFix": "",
"sSearch": "查找(所有信息):",
},
"bPaginate": false,//该参数为是否显示分页
"bLengthChange": false, //改变每页显示数据数量
"bStateSave": true,
"bFilter": true, //过滤功能
"aoColumns": [
null,
null,
{ "asSorting": [ ] },
{ "asSorting": [ ] }
]
});
});
</script>
</head>
<body>
<div class="data_list">
<div class="data_list_title">
宿舍楼管理
</div>
<form name="myForm" class="form-search" method="post" action="house?action=search">
<button class="btn btn-success" type="button" style="margin-right: 50px;" onclick="javascript:window.location='house?action=preSave'">添加</button>
<span class="data_search">
宿舍号: <input id="hno" name="hno" type="text" style="width:120px;height: 30px;" class="input-medium search-query" value="${hno}">
宿舍管理人员编号:<input id="HMno" name="HMno" type="text" style="width:120px;height: 30px;" class="input-medium search-query" value="${HMno}">
学号:<input id="Sno" name="Sno" type="text" style="width:120px;height: 30px;" class="input-medium search-query" value="${Sno}">
<button type="submit" class="btn btn-info" onkeydown="if(event.keyCode==13) myForm.submit()">搜索</button>
</span>
</form>
<div>
<table class="table table-striped table-bordered table-hover dataTable">
<thead>
<tr>
<th width="15%">宿舍号</th>
<th>人数</th>
<th>宿舍管理人员编号</th>
<th>通知</th>
<th width="20%">操作</th>
</tr>
</thead>
<tbody>
<c:forEach varStatus="i" var="house" items="${houseList }">//获取缓冲区中houseList的数据,并且进行展示
<tr>
<td>${house.hno }</td>
<td>${house.num}</td>
<td>${house.HMno }</td>
<td>${house.hmessage==null||house.hmessage==""?"无":house.hmessage }</td>
<td>
<button class="btn btn-mini btn-info" type="button" onclick="javascript:window.location='house?action=preSave&hno=${house.hno }'">修改</button>
<button class="btn btn-mini btn-danger" type="button" onclick="javascript:window.location='house?action=delete&hno=${house.hno }'">删除</button>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
<div align="center"><font color="red">${error }</font></div>
<div class="pagination pagination-centered">
<ul>
${pageCode }
</ul>
</div>
</div>
</body>
</html>
由于所有的代码有一点多,实在是很难都展示,以上的代码可以实现一个登录页面,,宿舍表的增删改查也写了 具体的功能,但是没有写前端的页面,图片的链接也不能用,所以我附上我的代码。但是一定要配置好maven 和tomcat否则应该很难运行,建议自己配置好再复制我的代码上去,不然应该会出错。完整代码放在百度网盘
链接:https://pan.baidu.com/s/1mIH9Mal8RNfZJbgKVme5Gg
提取码:1234