Servlet实例开发---学生管理系统

Servlet总结

本程序采用Servlet开发技术,MVC分层,所有程序在设计时都要接口为操作的标准,主要逻辑操作只有增删改查。

具体实现操作请看源代码。

本程序采用的是MYSQL数据库,需加入相应的jar包

目录结构

首先贴上底层数据层:

连接数据库

package com.student.dbc ;
import java.sql.* ;
public class DatabaseConnection {
    private static final String DBDRIVER = "org.gjt.mm.mysql.Driver" ;
     private static final String DBURL = "jdbc:mysql://localhost:3306/java_web?useUnicode=true&characterEncoding=UTF-8" ;
    private static final String DBUSER = "root" ;
    private static final String DBPASSWORD = "root" ;
    private Connection conn = null ;
    public DatabaseConnection() throws Exception{
        try{
            Class.forName(DBDRIVER) ;
            this.conn = DriverManager.getConnection(DBURL,DBUSER,DBPASSWORD) ;
        }catch(Exception e){
            throw e ;
        }
    }
    public Connection getConnection(){
        return this.conn ;
    }
    public void close() throws Exception{
        if(this.conn != null){
            try{
                this.conn.close() ;
            }catch(Exception e){
                throw e ;
            }
        }
    }
}
DatabaseConnection.java

实体类

package com.student.vo;

public class Student {
    private String id;
    private String name;
    private int age;
    private int sex;
    private String major;
    private String college;
    private String introduction;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public int getSex() {
        return sex;
    }
    public void setSex(int sex) {
        this.sex = sex;
    }
    public String getMajor() {
        return major;
    }
    public void setMajor(String major) {
        this.major = major;
    }
    public String getCollege() {
        return college;
    }
    public void setCollege(String college) {
        this.college = college;
    }
    public String getIntroduction() {
        return introduction;
    }
    public void setIntroduction(String introduction) {
        this.introduction = introduction;
    }
    
}
Student.java

业务逻辑类

package com.student.action;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import com.mysql.jdbc.Connection;
import com.student.dbc.DatabaseConnection;
import com.student.vo.Student;
public class StudentAction {
    
    private static Connection conn = null ;
    
    
    /**
     * 增加学生
     * @param id
     * @param name
     * @param age
     * @param sex
     * @param major
     * @param college
     * @param introduction
     * @return
     */
    public static boolean addStudent(String id,String name,int age,int sex,String major,String college,String introduction) {
        
        try {
            java.sql.Connection conn=new DatabaseConnection().getConnection();
            PreparedStatement st=conn.prepareStatement("insert into student values(?,?,?,?,?,?,?)");
        
            
            st.setString(1, id);
            st.setString(2, name);
            st.setInt(3, age);
            st.setInt(4, sex);
            st.setString(5, major);
            st.setString(6, college);
            st.setString(7, introduction);
            
            st.execute();
            conn.close();
            return true;
        
        } catch (Exception e) {
            // TODO: handle exception
            return false;
        }
        
    }
    /**
     * 更新学生
     * @param id
     * @param name
     * @param age
     * @param sex
     * @param major
     * @param college
     * @param introduction
     * @return
     */
    
    public static boolean updateStudent(String id,String name,int age,int sex,String major,String college,String introduction) {
        try {
            java.sql.Connection conn=new DatabaseConnection().getConnection();
            PreparedStatement st=conn.prepareStatement("update student set name=?,age=?,sex=?,major=?,college=?,introduction=? where id=?");
            
            st.setString(1, name);
            st.setInt(2, age);
            st.setInt(3, sex);
            st.setString(4, major);
            st.setString(5, college);
            st.setString(6, introduction);
            st.setString(7, id);
            
            st.execute();
            conn.close();
            return true;
        
        } catch (Exception e) {
            // TODO: handle exception
            return false;
        }
    }
    
    /**
     * 删除
     * @param id
     * @return
     */
    public static boolean deleteStudent(String id) {
        try {
            
            java.sql.Connection conn=new DatabaseConnection().getConnection();
            PreparedStatement st=conn.prepareStatement("delete from student where id=?");
            
            st.setString(1, id);
            
            st.execute();
            
            conn.close();
            return true;
        }catch (Exception e) {
            // TODO: handle exception
            return false;
        }
    }
    /**
     * 获取全部学生
     * @return
     */

    public static  ArrayList getAllstudent() {
        ArrayList students=new ArrayList();
        
        try {
            java.sql.Connection conn=new DatabaseConnection().getConnection();
            PreparedStatement st=conn.prepareStatement("select * from student");
            st.execute();
            ResultSet rs=st.getResultSet();
            while(rs.next()){
                Student student=new Student();
                student.setId(rs.getString("id"));
                student.setName(rs.getString("name"));
                student.setAge(rs.getInt("age"));
                student.setSex(rs.getInt("sex"));
                student.setMajor(rs.getString("major"));
                student.setCollege(rs.getString("college"));
                student.setIntroduction(rs.getString("introduction"));
                students.add(student);
                
            }
            conn.close();
        
        } catch (Exception e) {
            // TODO: handle exception
        }
            return students;
    }
    /**
     * 按学号查询学生
     * @param id
     * @return
     */
    public static  Student getStudent(String id) {
        
        Student student=null;
        try {
            java.sql.Connection conn=new DatabaseConnection().getConnection();
            PreparedStatement st=conn.prepareStatement("select * from student where id=?");
            
            st.setString(1,    id);
            st.execute();
            ResultSet rs=st.getResultSet();
            while(rs.next()){
                student=new Student();
            
                student.setId(rs.getString("id"));
                student.setName(rs.getString("name"));
                student.setAge(rs.getInt("age"));
                student.setSex(rs.getInt("sex"));
                student.setMajor(rs.getString("major"));
                student.setCollege(rs.getString("college"));
                student.setIntroduction(rs.getString("introduction"));
                
            
            }
            conn.close();
        
        } catch (Exception e) {
            // TODO: handle exception
        }
            return student;
    }
}
StudentAction.java

JSP与数据交换层

package com.student.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.student.action.StudentAction;
public class StudentServlet extends HttpServlet {


    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }


    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        
        if(request.getRequestURI().endsWith("/viewStudent")){
            RequestDispatcher dispatcher = request.getRequestDispatcher("viewstudent.jsp");
            dispatcher .forward(request, response);
        }else if(request.getRequestURI().endsWith("/addStudent")){
        
            doAddStudent(request,response);
        }
        else if (request.getRequestURI().endsWith("/updateStudent")) {
            
            doUpdateStudent(request,response);
        }else if (request.getRequestURI().endsWith("/deleteStudent")) {
            doDeleteStudent(request,response);
            
        }
            
        
    }

    private void doAddStudent(HttpServletRequest request, HttpServletResponse response) throws IOException{
        String id=request.getParameter("id");
        String name=request.getParameter("name");
        String age=request.getParameter("age");
        String sex=request.getParameter("sex");
        String major=request.getParameter("major");
        String college=request.getParameter("college");
        String introduction=request.getParameter("introduction");
        
        StudentAction.addStudent(id, name,new Integer(age), new Integer(sex), major, college, introduction);
        response.sendRedirect("index.jsp");
    }
    private void doUpdateStudent(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id=request.getParameter("id");
        
        String name=request.getParameter("name");
        String age=request.getParameter("age");
        String sex=request.getParameter("sex");
        String major=request.getParameter("major");
        String college=request.getParameter("college");
        String introduction=request.getParameter("introduction");
        
        StudentAction.updateStudent(id, name, new Integer(age), new Integer(sex), major, college, introduction);
        response.sendRedirect("index.jsp");
}
    private void doDeleteStudent(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String id=request.getParameter("id");
    StudentAction.deleteStudent(id);
    response.sendRedirect("index.jsp");
}
    
}
StudentServlet.java

数据库表,可直接复制

STUDENT.SQL

JSP页面

<%@page import="com.student.vo.Student"%>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page import="com.student.action.StudentAction"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>学生管理系统</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <link id="bs-css" href="css/bootstrap-cerulean.min.css" rel="stylesheet">

    <link href="css/charisma-app.css" rel="stylesheet">
    
   
    

  </head>

  <body>

<div class="box col-md-12" >
            <div class="box-inner">
                <div class="box-header well" data-original-title="">
                    <h2><i class="glyphicon glyphicon-user"></i> 学生管理系统</h2>
                     <div class="box-icon">
                        <a href="addstudent.jsp" class="btn btn-minimize btn-round btn-default"><i
                                class="glyphicon glyphicon-chevron-up"></i>添加学生</a>
                      
                              
                    </div>  
                </div>
                <div class="box-content">
                    <table class="table table-striped table-bordered responsive" width="80%">
                        <thead>
                        <tr>
                              <th class="center">&nbsp;&nbsp;&nbsp;&nbsp;学号</th>
                              <th class="center">&nbsp;&nbsp;&nbsp;&nbsp;姓名</th>
                              <th>&nbsp;&nbsp;&nbsp;&nbsp;年龄</th>
                              <th>&nbsp;&nbsp;&nbsp;&nbsp;性别</th>
                              <th>&nbsp;&nbsp;&nbsp;&nbsp;专业</th>
                              <th>&nbsp;&nbsp;&nbsp;&nbsp;学院</th>
                              <th>&nbsp;&nbsp;&nbsp;&nbsp;简介</th>
                            <th>&nbsp;&nbsp;&nbsp;&nbsp;操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        <tr>
                        <% ArrayList students=StudentAction.getAllstudent();
            for(int i=0;i<students.size();i++){
                Student student=(Student)students.get(i);%>
                
                            <td class="center">&nbsp;&nbsp;&nbsp;&nbsp;<%=student.getId() %></td>
                            <td class="center">&nbsp;&nbsp;&nbsp;&nbsp;<%=student.getName() %></td>
                            <td class="center">&nbsp;&nbsp;&nbsp;&nbsp;<%=student.getAge()%></td>
                            <% if(student.getSex()==1){%>
                            <td class="center">&nbsp;&nbsp;&nbsp;&nbsp;</td><%}else{ %>
                            <td class="center">&nbsp;&nbsp;&nbsp;&nbsp;</td>
                            <%} %>
                            <td class="center">&nbsp;&nbsp;&nbsp;&nbsp;<%=student.getMajor()%></td>
                            <td class="center">&nbsp;&nbsp;&nbsp;&nbsp;<%=student.getCollege()%></td>
                            <td class="center">&nbsp;&nbsp;&nbsp;&nbsp;<%=student.getIntroduction()%>...</td>
                        <td >
                              <a class="btn btn-success"href="viewStudent?id=<%=student.getId()%>">
                                    <i class="glyphicon glyphicon-zoom-in icon-white"></i>
                                    查看
                                </a>
                                
                                <a class="btn btn-info" href="updatestudent.jsp?id=<%=student.getId()%>">
                                    <i class="glyphicon glyphicon-edit icon-white"></i>
                                    修改
                                </a>
                                <a class="btn btn-danger" href="deleteStudent?id=<%=student.getId()%>">
                                    <i class="glyphicon glyphicon-trash icon-white"></i>
                                    删除
                                </a>
                           </td>
                            
                        </tr>
                       
                        </tbody>
                            <%
        
    } %>
                    </table>
                </div>
            </div>
        </div>

  </body>
</html>
index.jsp
<%@page import="com.student.vo.Student"%>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page import="com.student.action.StudentAction"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>添加学生信息</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
        <link id="bs-css" href="css/bootstrap-cerulean.min.css" rel="stylesheet">

    <link href="css/charisma-app.css" rel="stylesheet">
    
  </head>

  <body>
    <div class="box col-md-3">
        <div class="box-inner">
            <div class="box-header well" data-original-title="">
                <h2><i class="glyphicon glyphicon-edit"></i>学生信息</h2>
            </div>
            <div class="box-content">
                <form action="addStudent" method="post" role="form">
                    <div class="form-group">
                       
                        <input type="text" class="form-control" name="id" placeholder="学号">
                        
                        <input type="text" class="form-control" name="name" placeholder="姓名">
                        <input type="text" class="form-control"  name="age" placeholder="年龄">
                      
                       
                         <select  class="form-control" name="sex"><option value="1" >--------性别--------</option><option value="1"></option><option value="0"></option></select>
                        <input type="text" class="form-control"  name="major" placeholder="专业">
                       
                        <input type="text" class="form-control"  name="college" placeholder="学院">
                        <label for="exampleInputEmail1">简介</label>
                        <textarea type="text" class="form-control" rows="5" name="introduction" style="
resize: none;" ></textarea>
                    </div>
             
                    <button type="submit" class="btn btn-default">提交</button>
                </form>

            </div>
        </div>
    </div>
  
  </body>
</html>
addstudent.jsp
<%@page import="com.student.vo.Student"%>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page import="com.student.action.StudentAction"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>添加学生信息</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
        <link id="bs-css" href="css/bootstrap-cerulean.min.css" rel="stylesheet">

    <link href="css/charisma-app.css" rel="stylesheet">
    
  </head>
<%
String id=request.getParameter("id");
Student student=StudentAction.getStudent(id); %>
  <body>
        <div class="box col-md-3">
        <div class="box-inner">
            <div class="box-header well" data-original-title="学生信息">
                <h2><i class="glyphicon glyphicon-edit"></i>修改学生信息</h2>
            </div>
            <div class="box-content">
                <form action="updateStudent" method="post" role="form">
                    <div class="form-group">
                       <label>学号</label>
                        <input type="text" class="form-control" name="id" value="<%=student.getId() %>">
                        <label>姓名</label>
                        <input type="text" class="form-control" name="name" value="<%=student.getName() %>">
                        <label>年龄</label>  <input type="text" class="form-control"  name="age" value="<%=student.getAge() %>">
                           <label>性别</label><% if(student.getSex()==1){%><%}else{ %><%} %>
                             <select  class="form-control" name="sex"><option  value="1">--------性别--------</option><option value="1"></option><option value="0"></option></select>
                         <label>专业</label> <input type="text" class="form-control"  name="major" value="<%=student.getMajor()%>">
                       
                        <label>学院</label>  <input type="text" class="form-control"  name="college" value="<%=student.getCollege()%>">
                        <label for="exampleInputEmail1">简介</label>
                        <textarea class="form-control" rows="5" name="introduction" placeholder=" <%=student.getIntroduction()%>" style="
resize: none;" ><%=student.getIntroduction()%></textarea>
                    </div>
             
                    <button type="submit" class="btn btn-default">更新信息</button>
                </form>

            </div>
        </div>
    </div>
  
  <form action="updateStudent" method="post">

<table >
<tr><td>学号</td><td><input type="text" name="id" value="<%=id %>" readonly="true" ></td></tr>
<tr><td>姓名</td><td><input type="text" name="name" value="<%=student.getName() %>"></td></tr>
<tr><td>年龄</td><td><input type="text" name="age" value="<%=student.getAge()%>"></td></tr>
<tr><td>性别</td><td><select name="sex"><option value="1"></option><option value="0"></option></select></td></tr>
<tr><td>专业</td><td><input type="text" name="major" value="<%=student.getMajor()%>"></td></tr>
<tr><td>学院</td><td><input type="text" name="college" value="<%=student.getCollege()%>"></td></tr>
<tr><td>简介</td><td><textarea  rows="10" cols="30" name="introduction" ><%=student.getIntroduction() %></textarea></td></tr>
<tr><td colspan="2"><input type="submit" value="提交"></td></tr>
</table>
</form>

  </body>
</html>
updatestudent.jsp
<%@page import="com.student.vo.Student"%>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page import="com.student.action.StudentAction"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>查看学生信息</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
        <link id="bs-css" href="css/bootstrap-cerulean.min.css" rel="stylesheet">

    <link href="css/charisma-app.css" rel="stylesheet">
    
  </head>
<%
String id=request.getParameter("id");
Student student=StudentAction.getStudent(id); %>
  <body>
      <div class="box col-md-3">
        <div class="box-inner">
            <div class="box-header well" data-original-title="学生信息">
                <h2><i class="glyphicon glyphicon-edit"></i>学生信息</h2>
               
                        &nbsp;<a href="index.jsp" ><h5 align="right">返回</h5></a>
                      
                              
                  
            </div>
            <div class="box-content">
                <form action="#" method="post" role="form">
                    <div class="form-group">
                       <label>学号</label>
                        <input type="text" class="form-control" name="id" placeholder="<%=student.getId() %>" readonly="readonly">
                        <label>姓名</label>
                        <input type="text" class="form-control" name="name" placeholder="<%=student.getName() %>" readonly="readonly">
                        <label>年龄</label>  <input type="text" class="form-control"  name="age" placeholder="<%=student.getAge() %>" readonly="readonly">
                           <label>性别</label><% if(student.getSex()==1){%>
                             <input type="text" class="form-control"  placeholder="男" readonly="readonly"><%}else{ %>
                            <input type="text" class="form-control"  placeholder="女" readonly="readonly"></td>
                            <%} %>
                         <label>专业</label> <input type="text" class="form-control"  name="major" placeholder="<%=student.getMajor()%>" readonly="readonly">
                       
                        <label>学院</label>  <input type="text" class="form-control"  name="college" placeholder="<%=student.getCollege()%>" readonly="readonly">
                        <label for="exampleInputEmail1">简介</label>
                        <textarea type="text" class="form-control" rows="5" name="introduction" placeholder=" <%=student.getIntroduction()%>" style="
resize: none;" readonly="readonly"></textarea>
                    </div>
             
                </form>

            </div>
        </div>
    </div>
  


  </body>
</html>
viewstudent.jsp

web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <servlet>
   
    <servlet-name>StudentServlet</servlet-name>
    <servlet-class>com.student.servlet.StudentServlet</servlet-class>
  </servlet>
  
  <servlet>
    <servlet-name>addStudent</servlet-name>
    <servlet-class>com.student.servlet.StudentServlet</servlet-class>
  </servlet>
  
 <servlet>
    <servlet-name>viewStudent</servlet-name>
    <servlet-class>com.student.servlet.StudentServlet</servlet-class>
  </servlet>
  
  
    <servlet>
    <servlet-name>deleteStudent</servlet-name>
    <servlet-class>com.student.servlet.StudentServlet</servlet-class>
  </servlet>
    <servlet>
    <servlet-name>updateStudent</servlet-name>
    <servlet-class>com.student.servlet.StudentServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>StudentServlet</servlet-name>
    <url-pattern>/StudentServlet</url-pattern>
  </servlet-mapping>
  
    <servlet-mapping>
    <servlet-name>updateStudent</servlet-name>
    <url-pattern>/updateStudent</url-pattern>
  </servlet-mapping>

  <servlet-mapping>
    <servlet-name>deleteStudent</servlet-name>
    <url-pattern>/deleteStudent</url-pattern>
  </servlet-mapping>


  <servlet-mapping>
    <servlet-name>addStudent</servlet-name>
    <url-pattern>/addStudent</url-pattern>
  </servlet-mapping>
 

  <servlet-mapping>
    <servlet-name>viewStudent</servlet-name>
    <url-pattern>/viewStudent</url-pattern>
  </servlet-mapping>
</web-app>
web.xml

css样式,可以自己添加,本人就不贴css了。

园友可以思考下分页效果怎么实现?

程序效果图

 

posted @ 2015-02-06 21:48  偶my耶  阅读(13347)  评论(10编辑  收藏  举报