Servlet——執行在伺服器端的小程式(基於Servlet的學生後臺管理系統)

2020-10-08 11:00:37

一、何為Servlet

Servlet就是一個介面,定義了Java類被瀏覽器存取到(tomcat識別)的規則。

將來我們自定義一個類,實現Servlet介面,複寫方法。

public class MyServlet implements Servlet

在這裡插入圖片描述

二、如何設定Servlet

1.在web.xml中設定

	<!--設定Servlet -->
    <servlet>
        <servlet-name>SelUserServlet</servlet-name>
        <servlet-class>com.beizhen.servlet.SelUserServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>SelUserServlet</servlet-name>
        <url-pattern>/seluser</url-pattern>
    </servlet-mapping>

2.通過註解設定

@WebServlet("/seluser")

在這裡插入圖片描述

三、執行原理

1.當伺服器接受到使用者端瀏覽器的請求後,會解析請求URL路徑,獲取存取的Servlet的資源路徑
2. 查詢web.xml檔案,是否有對應的標籤體內容。
3. 如果有,則在找到對應的全類名
4. tomcat會將位元組碼檔案載入進記憶體,並且建立其物件
5. 呼叫其方法

四、Servlet生命週期

1.Servlet 通過呼叫 init () 方法進行初始化。init 方法只呼叫一次。
2.Servlet 呼叫 service() 方法來處理使用者端的請求。
3.Servlet 通過呼叫 destroy() 方法終止(結束)。destroy() 方法只會被呼叫一次
4.最後,Servlet 是由 JVM 的垃圾回收器進行垃圾回收的。

五、使用servlet實現學生資訊後臺管理

學生資訊後臺管理效果圖
在這裡插入圖片描述
專案分包圖:
在這裡插入圖片描述
查詢所有學生 SelStuServlet

package com.beizhen.servlet;

import com.beizhen.bean.Student;
import com.beizhen.bean.User;
import com.beizhen.dao.StudentDao;
import com.beizhen.dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : Bei-Zhen
 * @date : 2020-10-06 13:00
 */
@WebServlet("/selstu")
public class SelStuServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //設定請求和響應編碼
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //獲得所有學生資訊
        StudentDao studao = new StudentDao();
        List<Student> stus = studao.queryAllStus("");
        //列印流
        PrintWriter out = response.getWriter();
        out.write("<html><body><h1 align='center'>學生資訊管理系統</h1>" +
                "<div align='center'><form action='selstuat' method='get'>" +
                "<input type='text' name='sName'>" +
                "<button type='submit'>查詢</button></form></div>" +
                "<table border='1' cellspacing='0' cellpadding='10' align='center'>");
        out.write("<tr><td>"+"學生編號"
                +"</td><td>"+"學號"
                +"</td><td>"+"學校"
                +"</td><td>"+"姓名"
                +"</td><td>"+"暱稱"
                +"</td><td>"+"手機號"
                +"</td><td>"+"生日"
                +"</td><td>"+"新增操作"
                +"</td><td>"+"刪除操作"
                +"</td><td>"+"修改操作"
                +"</td></tr>");
        for (int i = 0; i < stus.size(); i++) {
            Student stu = stus.get(i);
            out.write("<tr><td>"+stu.getsId()
                    +"</td><td>"+stu.getsNum()
                    +"</td><td>"+stu.getsSchool()
                    +"</td><td>"+stu.getsName()
                    +"</td><td>"+stu.getsNickname()
                    +"</td><td>"+stu.getsTel()
                    +"</td><td>"+stu.getsBDay()
                    +"</td><td>"+"<a href='register.jsp' style='text-decoration:none'>新增</a>"
                    +"</td><td>"+"<a href='/delstu?id=" +stu.getsId() + "' style='text-decoration:none'>刪除</a>"
                    +"</td><td>"+"<a href='/updstu?sId=" +stu.getsId() + "&sNum=" + stu.getsNum()
                    + "&sSchool=" + stu.getsSchool() + "&sName=" + stu.getsName()
                    + "&sNName=" + stu.getsNickname() + "&sTel=" + stu.getsTel()
                    + "&sBDay=" + stu.getsBDay() + "' style='text-decoration:none'>修改</a>"
                    +"</td></tr>");
        }
        out.write("</table></body></html>");
    }
}

實現增加功能直接跳轉註冊頁面,註冊成功直接跳轉selstu
在這裡插入圖片描述

package com.beizhen.servlet;

import com.beizhen.bean.Student;
import com.beizhen.dao.StudentDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author : Bei-Zhen
 * @date : 2020-10-06 13:27
 */
@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //設定請求和響應編碼
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //獲取請求引數
        String sNum = request.getParameter("sNum");
        String sSchool = request.getParameter("sSchool");
        String sName = request.getParameter("sName");
        String sNickname = request.getParameter("sNickname");
        String sTel = request.getParameter("sTel");
        String sBDay = request.getParameter("sBDay");
        Student stu = new Student(0,sNum,sSchool,sName,sNickname,sTel,sBDay);
        int i = new StudentDao().addStu(stu);
        PrintWriter out = response.getWriter();
        if(i != 0){
            out.write("<script type='text/javascript'>");
            out.write("alert('恭喜你註冊成功!');");
            out.write("alert('即將跳轉學生資訊管理!');");
            out.write("window.location='selstu';");
            out.write("</script>");
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

實現刪除功能,通過get請求向伺服器傳送url獲得id

<a href='/delstu?id=" +stu.getsId() + "' style='text-decoration:none'>刪除</a>

在這裡插入圖片描述

package com.beizhen.servlet;

import com.beizhen.bean.Student;
import com.beizhen.dao.StudentDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author : Bei-Zhen
 * @date : 2020-10-06 15:31
 */
@WebServlet("/delstu")
public class DelStuServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //設定請求和響應編碼
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //獲取請求引數
        int id = Integer.parseInt(request.getParameter("id"));
        int num = new StudentDao().deleteStu(id);
        PrintWriter out = response.getWriter();
        if(num != 0){
            out.write("<script type='text/javascript'>");
            out.write("alert('恭喜你刪除成功!');");
            out.write("window.location='selstu';");
            out.write("</script>");
        } else {
            out.write("<script type='text/javascript'>");
            out.write("alert('刪除失敗!');");
            out.write("window.location='selstu';");
            out.write("</script>");
        }

    }
}

實現修改功能,同樣通過get請求向伺服器傳送url獲得id等其他資訊,同時學號不能編輯

//學號不可編輯
readonly unselectable='on' 
package com.beizhen.servlet;

import com.beizhen.bean.Student;
import com.beizhen.dao.StudentDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author : Bei-Zhen
 * @date : 2020-10-06 16:35
 */
@WebServlet("/updstu")
public class UpdStuServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //設定請求和響應編碼
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //獲取請求引數
        int sId = Integer.parseInt(request.getParameter("sId"));
        String sNum = request.getParameter("sNum");
        String sSchool = request.getParameter("sSchool");
        String sName = request.getParameter("sName");
        String sNickname = request.getParameter("sNickname");
        String sTel = request.getParameter("sTel");
        String sBDay = request.getParameter("sBDay");
        Student stu = new Student(sId,sNum,sSchool,sName,sNickname,sTel,sBDay);
        int i = new StudentDao().updateStu(stu);
        PrintWriter out = response.getWriter();
        if(i != 0){
            out.write("<script type='text/javascript'>");
            out.write("alert('恭喜你修改成功!');");
            out.write("window.location='selstu';");
            out.write("</script>");
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //設定請求和響應編碼
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //列印流
        PrintWriter out = response.getWriter();
        out.write("<html><body>");
        out.write("<form action='updstu' method='post'>");
        //學號不可編輯
        out.write("ID:<input type='text' name='sId' readonly unselectable='on' value='" + request.getParameter("sId") + "'><br>");
        out.write("學號:<input type='text' name='sNum' readonly unselectable='on' value='" + request.getParameter("sNum") + "'><br>");
        out.write("學校:<input type='text' name='sSchool' value='" + request.getParameter("sSchool") + "'><br>");
        out.write("姓名:<input type='text' name='sName' readonly unselectable='on' value='" + request.getParameter("sName")+ "' required><br>");
        out.write("暱稱:<input type='text' name='sNickname' value='" + request.getParameter("sNName") + "'><br>");
        out.write("電話:<input type='text' name='sTel' value='" + request.getParameter("sTel") + "'><br>");
        out.write("生日:<input type='text' name='sBDay' value='" + request.getParameter("sBDay") + "'><br>");
        out.write("<button type='submit'>修改</button>");
        out.write("</form><html><body>");
    }
}

實現查詢功能,根據名字查詢

package com.beizhen.servlet;

import com.beizhen.bean.Student;
import com.beizhen.dao.StudentDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author : Bei-Zhen
 * @date : 2020-10-06 22:30
 */
@WebServlet("/selstuat")
public class SelStuAtServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //設定請求和響應編碼
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //獲得學生請求資訊
        String sName = request.getParameter("sName");
        //獲得資料庫所有學生資訊
        StudentDao studao = new StudentDao();
        List<Student> stus = studao.queryAllStus(sName);
        //列印流
        PrintWriter out = response.getWriter();
        out.write("<html><body><h1 align='center'>學生資訊管理系統</h1>" +
                "<div align='center'><form action='selstuat' method='get'>" +
                "<input type='text' name='sName'>" +
                "<button type='submit'>查詢</button></form></div>" +
                "<table border='1' cellspacing='0' cellpadding='10' align='center'>");
        out.write("<tr><td>"+"學生編號"
                +"</td><td>"+"學號"
                +"</td><td>"+"學校"
                +"</td><td>"+"姓名"
                +"</td><td>"+"暱稱"
                +"</td><td>"+"手機號"
                +"</td><td>"+"生日"
                +"</td><td>"+"新增操作"
                +"</td><td>"+"刪除操作"
                +"</td><td>"+"修改操作"
                +"</td></tr>");
        for (int i = 0; i < stus.size(); i++) {
            Student stu = stus.get(i);
            out.write("<tr><td>"+stu.getsId()
                    +"</td><td>"+stu.getsNum()
                    +"</td><td>"+stu.getsSchool()
                    +"</td><td>"+stu.getsName()
                    +"</td><td>"+stu.getsNickname()
                    +"</td><td>"+stu.getsTel()
                    +"</td><td>"+stu.getsBDay()
                    +"</td><td>"+"<a href='register.jsp' style='text-decoration:none'>新增</a>"
                    +"</td><td>"+"<a href='/delstu?id=" +stu.getsId() + "' style='text-decoration:none'>刪除</a>"
                    +"</td><td>"+"<a href='/updstu?sId=" +stu.getsId() + "&sNum=" + stu.getsNum()
                    + "&sSchool=" + stu.getsSchool() + "&sName=" + stu.getsName()
                    + "&sNName=" + stu.getsNickname() + "&sTel=" + stu.getsTel()
                    + "&sBDay=" + stu.getsBDay() + "' style='text-decoration:none'>修改</a>"
                    +"</td></tr>");
        }
        out.write("</table></body></html>");
    }
}