上次仅仅就做了登入界面,觉得jsp挺有意思的。这次做了简单的学生信息管理系统.
主要是功能:
新增学生信息修改学生信息删除学生信息查询全部学生信息按学号或者姓名查询学生信息学生的信息主要有:学号、姓名、年龄、地址
这是系统的主页:会显示所有的数据
动态搜索学生信息框可以根据学号或者姓名搜索点击每个学号可以查看具体信息表格最后一栏有删除功能表格左下角是新增学生信息
这是系统新增学生信息页面
这是查询学生信息结果的页面,当中加了修改信息功能
学生管理系统的工程目录
学生管理系统采用的是MVC的设计模式
Model 模型层:一个功能。用javaBean实现,这里只的是数据库增删改查代码进一步优化.
模型层是Dao类和service成写成接口和实现类,service实现类创建Dao类的对象,通过对象调用Dao的方法并返回数据库增删改查的返回值。
View 视图层:用于展示给用户看的和操作的,一般用HTML,CSS,JS等。
视图层的jsp将的用户交互的输入值或者鼠标的点击事件,通过action传到servlet控制台。
Controller 控制器层:接受请求,并跳转到模型层进行处理,处理完毕后,再将处理的结果返回给请求处。
一般用Servlet实现控制器。servlet控制台则创建service的对象,通过对象调用service的方法,返回一个返回值。通过重定向或者请求转发将数据返回给视图层
重定向:response.sendRedirect(“success.jsp”);
Redirect:发送定向转向到
请求转发:
request.getRequestDispatcher(“success.jsp”).forward(request,response);
getRequestDispatcher:得到请求调度到
entity放实体类
用来封装数据:如学生信息 学号、姓名、年龄、地址
util放工具类
JDBC工具类:一些重复写的代码可以提炼出来写成一些方法,存放到类中,方便调用.
关于servlet流程:
a) Eclipse每创建一个Servlet, 就会在web.xml文件中添加两个标签:和标签(可以将这两个标签看成一个组的标签)
b) 和标签内都会有一个标签,标签的内容可以更改,但要求更改后的这两个标签的内容也必须一致。
c) 标签用于配置Servlet类的全路径名(即包名+类名)
需要注意:如果在创建Servlet后修改了Servlet类的名称,这个地方也要一起更改,否则将会出现"ClassNotFoundException" 即类找不到异常
d) 标签用于配置浏览器以什么路径访问当前Servlet(即Servlet对外访问的路径),默认的路径是:/类名
例如:上面为addStudentServlet配置的为 /addStudentServlet,因此我们在浏览器中的访问路径则为http://主机名/web项目访问路径/addStudentServlet
视图层:主页查询并显示全部信息jsp代码
<%@page import="org.student.entity.Student"%><%@page import="java.util.List"%><%@page import="java.util.ArrayList"%><%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><!DOCTYPE html><html><head><meta charset="UTF-8"><title>学生信息列表</title><style>#customers {font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;width: 100%;border-collapse: collapse;}#customers td, #customers th {font-size: 1em;border: 1px solid #98bf21;padding: 3px 7px 2px 7px;}#customers th {font-size: 1.1em;text-align: left;padding-top: 5px;padding-bottom: 4px;background-color: #A7C942;color: #ffffff;}#customers tr.alt td {color: #000000;background-color: #EAF2D3;}a.one:link, a:visited {display: block;font-weight: bold;background-color: #98bf21;width: 120px;text-align: center;padding: 4px;text-decoration: none;}a.one:hover, a:active {background-color: #7A991A;}input[type=text] {width: 130px;box-sizing: border-box;border: 2px solid #ccc;border-radius: 4px;font-size: 16px;background-color: white;background-image: url('searchicon.png');background-position: 10px 10px;background-repeat: no-repeat;padding: 12px 20px 12px 40px;-webkit-transition: width 0.4s ease-in-out;transition: width 0.4s ease-in-out;}input[type=text]:focus {width: 100%;}</style></head><body><p>动态搜索学生信息框:</p><form action="SpeciallyDesignatedStudentServlet" method="post"><input type="text" name="search" placeholder="搜索.."></form><table id="customers"><tr><th>学号</th><th>姓名</th><th>年龄</th><th>删除</th></tr><%List<Student> students = (List<Student>) request.getAttribute("students");for (Student student : students) {%><tr><td><ahref="QueryStudentIdServlet?studentid=<%=student.getId()%> "><%=student.getId()%></a></td><td><%=student.getName()%></td><td><%=student.getAge()%></td><td><ahref="DeleteStudentServlet?studentid=<%=student.getId()%> ">删除</a></td></tr><%}%></table><a class="one" href="addstudent.jsp">添加学生信息</a><%Student student = (Student) request.getAttribute("student");String text = (String) request.getAttribute("error");if (text != null) {//判断是否为空是防止首次登入就宝新增失败if ("error".equals(text)) {out.print("增加失败,学号为" + student.getId() + "或者姓名" + student.getName() + "已存在");} else if ("success".equals(text)) {out.print("增加成功");}}%></body></html>
以下是新增学生信息jsp代码
<%@page import="org.student.entity.Student"%><%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><!DOCTYPE html><html><head><style>input[type=text], select {width: 100%;padding: 12px 20px;margin: 8px 0;display: inline-block;border: 1px solid #ccc;border-radius: 4px;box-sizing: border-box;}input[type=submit] {width: 100%;background-color: #4CAF50;color: white;padding: 14px 20px;margin: 8px 0;border: none;border-radius: 4px;cursor: pointer;}input[type=submit]:hover {background-color: #45a049;}div {border-radius: 5px;background-color: #f2f2f2;padding: 20px;}form {position: absolute;left: 20px;top: 0px;}.button {background-color: #e7e7e7;border: none;width: 50%;color: white;padding: 15px 32px;text-align: center;text-decoration: none;display: inline-block;font-size: 16px;margin: 4px 2px;cursor: pointer;float: left;}</style><meta charset="UTF-8"><script type="text/javascript" src="js/jquery-1.8.3.js"></script><script type="text/javascript">function check() {var studentid = $("studentid").val();var studentname = $("studentname").val();var studentage = $("studentage").val();var studentaddress = $("studentaddress").val();if (!(studentid > 0 && studentid < 100)) {alert("学号必须是1-100");return false;}if (!(studentage > 0 && studentage < 100)) {alert("年龄必须是1-100");return false;}}</script><title>添加学生信息</title></head><body><form action="AddStudentServlet" method onsubmit="return check()">学号:<input type="text" name="studentid" id="studentid"><br />姓名:<input type="text" name="studentname" id="studentname"><br />年龄: <input type="text" name="studentage" id="studentage"><br />地址:<input type="text" name="studentaddress" id="studentaddress"><br /><input type="submit" value="新增学生信息"><%String text = (String) request.getAttribute("error");if (text != null) {//判断是否为空是防止首次登入就宝新增失败out.print(text);}%></form></body></html>
以下是servlet控制器部分代码,这里就放查询全部信息的代码
package org.student.Servlet;import java.io.IOException;import java.sql.SQLException;import java.util.ArrayList;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.Student;import org.student.service.IStudentService;import org.student.service.impl.StudentServiceImpl;public class QueryAllStudents extends HttpServlet {protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("UTF-8");IStudentService studentservice=new StudentServiceImpl();try {List<Student> students = studentservice.QuerAllStudent();for(Student student:students) {System.out.println(student);}request.setAttribute("students", students);request.getRequestDispatcher("index.jsp").forward(request, response);} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubdoGet(request, response);}}
servlet新增学生代码
package org.student.Servlet;import java.io.IOException;import java.io.PrintWriter;import java.sql.SQLException;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 {protected void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException {response.setContentType("text/html; charset=UTF-8");request.setCharacterEncoding("UTF-8");String studentid = request.getParameter("studentid");if (request.getParameter("studentid") == "") {request.setAttribute("error", "学生学号不能为空");request.getRequestDispatcher("addstudent.jsp").forward(request, response);}int id = Integer.parseInt(studentid);if (id <= 0) {request.setAttribute("error", "学生学号不能为负数");request.getRequestDispatcher("addstudent.jsp").forward(request, response);}String name = request.getParameter("studentname");if (name == "") {request.setAttribute("error", "学生姓名不能为空");request.getRequestDispatcher("addstudent.jsp").forward(request, response);}String studentage = request.getParameter("studentage");if (request.getParameter("studentage") == "") {request.setAttribute("error", "学生年龄不能为空");request.getRequestDispatcher("addstudent.jsp").forward(request, response);}int age = Integer.parseInt(studentage);if (age <= 0) {request.setAttribute("error", "学生年龄年龄不能为负数的");request.getRequestDispatcher("addstudent.jsp").forward(request, response);}String address = request.getParameter("studentaddress");if (address == "") {request.setAttribute("error", "学生地址不能为空");request.getRequestDispatcher("addstudent.jsp").forward(request, response);}System.out.println(name + "----" + age);Student student = new Student(id, name, age, address);IStudentService studentservice = new StudentServiceImpl();request.setAttribute("student", student);try {boolean result = studentservice.AddStudent(student);if (result) {request.setAttribute("error", "success");request.getRequestDispatcher("QueryAllStudents").forward(request, response);// response.sendRedirect("QueryAllStudents");} else {request.setAttribute("error", "error");request.getRequestDispatcher("QueryAllStudents").forward(request, response);}} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// TODO Auto-generated method stubdoGet(request, response);}
以下是模型层代码
数据库接口类
package org.student.dao;import java.sql.DriverManager;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 addStudent(Student student) throws SQLException, Exception;// 修改学生信息public boolean modifyStudent(Student student) throws SQLException,Exception;// 删除学生信息public boolean deleteStudent(int id) throws SQLException,Exception;// 调用查询信息方法判断学生信息是否存在public boolean isExit(int id) throws SQLException, Exception;// 查询学生信息public Student queryStudent(int id)throws SQLException, Exception;// 查询全部学生导入import java.util.ArrayList;import java.util.List;public List<Student> queryAllStudents() throws SQLException, Exception;//查询特定信息public Student designatedquery(String name)throws SQLException, Exception;}
数据库实现类
package org.student.dao.impl;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.dao.IStudentDao;import org.student.entity.Student;import org.student.util.DBUtil;//数据访问层:原子性的public class StudentDaoImpl implements IStudentDao {// 添加学生信息public boolean addStudent(Student student) throws Exception {String sql = "INSERT INTO studentmessage ( id,name, age,address ) VALUES (?,?,?,?)";Object[] params = { student.getId(), student.getName(), student.getAge(), student.getAddress() };return DBUtil.executeUpdate(sql, params);}// 修改学生信息public boolean modifyStudent(Student student) throws Exception {String sql = "UPDATE studentmessage SET name=?,age=?,address=? WHERE id=?";Object[] params = { student.getName(), student.getAge(), student.getAddress(), student.getId() };return DBUtil.executeUpdate(sql, params);}// 删除学生信息public boolean deleteStudent(int id) throws Exception {String sql = "DELETE FROM studentmessage WHERE id=?";Object[] params = { id };return DBUtil.executeUpdate(sql, params);}// 调用查询信息方法判断学生信息是否存在public boolean isExit(int id) throws Exception {return queryStudent(id) == null ? false : true;}// 查找特定信息public Student designatedquery(String name) throws Exception {Student student = null;try {String sql = "SELECT * FROM studentmessage WHERE name=? ";Object[] params = { name };ResultSet rs = DBUtil.executeQuery(sql, params);if (rs.next()) {int stid = rs.getInt("id");String stname = rs.getString("name");int stage = rs.getInt("age");String staddress = rs.getString("address");student = new Student(stid, stname, stage, staddress);}return student;} finally {if (DBUtil.rs != null)DBUtil.rs.close();if (DBUtil.pstmt != null)DBUtil.pstmt.close();if (DBUtil.conn != null)DBUtil.conn.close();}}// 查询学生信息public Student queryStudent(int id) throws Exception {Student student = null;try {String sql = "SELECT * FROM studentmessage WHERE id=? ";Object[] params = { id };ResultSet rs = DBUtil.executeQuery(sql, params);if (rs.next()) {int stid = rs.getInt("id");String stname = rs.getString("name");int stage = rs.getInt("age");String staddress = rs.getString("address");student = new Student(stid, stname, stage, staddress);}return student;} finally {if (DBUtil.rs != null)DBUtil.rs.close();if (DBUtil.pstmt != null)DBUtil.pstmt.close();if (DBUtil.conn != null)DBUtil.conn.close();}}// 查询全部学生导入import java.util.ArrayList;import java.util.List;public List<Student> queryAllStudents() throws Exception {List<Student> students = new ArrayList<>();String sql = "SELECT * FROM studentmessage ";ResultSet rs = DBUtil.executeQuery(sql, null);while (rs.next()) {int stid = rs.getInt("id");String stname = rs.getString("name");int stage = rs.getInt("age");String staddress = rs.getString("address");Student student = new Student(stid, stname, stage, staddress);students.add(student);}return students;}}
数据库工具类,简化数据库代码量
package org.student.util;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 class DBUtil {private static String JDriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";private static String connectDB = "jdbc:sqlserver://localhost:1433;DatabaseName=JDBCTest";private static String youuser = "sa";private static String youpwd = "zm123456";public static PreparedStatement pstmt = null;public static Connection conn = null;public static ResultSet rs = null;public static void connect() {try {Class.forName(JDriver);} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}try {conn = DriverManager.getConnection(connectDB, youuser, youpwd);} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}// 增删改public static boolean executeUpdate(String sql, Object[] params) throws SQLException {try {connect();// 不同的类型加入数组只能用object数组Object[] obs={id ,name,age,address}// String sql = "INSERT INTO studentmessage ( id,name, age,address ) VALUES// (?,?,?,?)";pstmt = conn.prepareStatement(sql);for (int i = 0; i < params.length; i++) {pstmt.setObject(i + 1, params[i]);}int rs = pstmt.executeUpdate();if (rs > 0) {return true;} else {return false;}} finally {if (pstmt != null)pstmt.close();if (conn != null)conn.close();}}// 查:返回的是集合类型 (List<Student> Student null)public static ResultSet executeQuery(String sql, Object[] params) throws SQLException {List<Student> students = new ArrayList<>();connect();pstmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);if (params != null) {for (int i = 0; i < params.length; i++) {pstmt.setObject(i + 1, params[i]);}}rs = pstmt.executeQuery();return rs;}}
如果觉得《学生信息管理系统(eclipse+Tomcat+SQL server )》对你有帮助,请点赞、收藏,并留下你的观点哦!