• servlet介绍


    servlet技术用于处理页面的请求,创建servletJAVA类,里面有响应页面请求的方法

    servlet的生命周期为:

    1. package Servlet;
    2. import java.io.IOException;
    3. import jakarta.servlet.ServletConfig;
    4. import jakarta.servlet.ServletException;
    5. import jakarta.servlet.annotation.WebServlet;
    6. import jakarta.servlet.http.HttpServlet;
    7. import jakarta.servlet.http.HttpServletRequest;
    8. import jakarta.servlet.http.HttpServletResponse;
    9. /**
    10. * Servlet implementation class Servletshengmingzhouqi
    11. */
    12. //@WebServlet("/Servletshengmingzhouqi")
    13. public class Servletshengmingzhouqi extends HttpServlet {
    14. private static final long serialVersionUID = 1L;
    15. /**
    16. * Default constructor.
    17. */
    18. static {
    19. System.out.println("Servlet被加载....");
    20. }
    21. public Servletshengmingzhouqi() {
    22. System.out.println("Servlet被实例化....");
    23. }
    24. /**
    25. * @see Servlet#init(ServletConfig)
    26. */
    27. public void init(ServletConfig config) throws ServletException {
    28. System.out.println("Servlet被初始化....");
    29. }
    30. /**
    31. * @see Servlet#destroy()
    32. */
    33. public void destroy() {
    34. System.out.println("Servlet被销毁....");
    35. }
    36. /**
    37. * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
    38. * response)
    39. */
    40. protected void doGet(HttpServletRequest request, HttpServletResponse response)
    41. throws ServletException, IOException {
    42. System.out.println("Servlet请求处理中....");
    43. }
    44. /**
    45. * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
    46. * response)
    47. */
    48. protected void doPost(HttpServletRequest request, HttpServletResponse response)
    49. throws ServletException, IOException {
    50. System.out.println("Servlet请求服务中....");
    51. }
    52. }

    加载-实例化-初始化-处理-销毁

     

      servlet类中的主要方法就是:

    init:初始化方法,在构造函数后面调用

    destroy:销毁方法,在手动关闭servlet时调用

    doGet、doPost:浏览器使用get、post方法时调用指定方法

    默认情况下,浏览器发送请求时servlet进行加载-实例化-初始化,不过可以在wep.xml配置默认服务器开启时自动 加载-实例化-初始化:

    1

    给定的数字参数越大,服务器在实例化它时优先级就越高,0为浏览器发送请求时实例化

     浏览器页面若想使用servlet就需要配置路径:

    1. <servlet>
    2. <servlet-name>smzqservlet-name>
    3. <servlet-class>Servlet.Servletshengmingzhouqiservlet-class>
    4. servlet>
    5. <servlet-mapping>
    6. <servlet-name>smzqservlet-name>
    7. <url-pattern>/Servletsmzqurl-pattern>
    8. servlet-mapping>

    servlet-name:servlet的别名

    servlet-class:servlet类的地址

    url-pattern:将servlet访问地址切换为这个名字,form地址栏可以直接用这个地址

     以上配置文件也许有一些繁琐,也可以直接在servlet类中配置:

    @WebServlet("/Servletsmzq")

     这两种方法选其中一种就像,但是同时只能出现一种,不然你懂的:

    既然已经了解了基本方法,我们来写一个网页提交信息的练习:

    写前端:

    1. <%@ page language="java" contentType="text/html; charset=UTF-8"
    2. pageEncoding="UTF-8"%>
    3. html>
    4. <html>
    5. <head>
    6. <meta charset="UTF-8">
    7. <title>Insert title heretitle>
    8. head>
    9. <body>
    10. <form action="AddServlet" method="post">
    11. <table border="1px">
    12. <tr>
    13. <td>商品名称td>
    14. <td><input type="text" name="name" />td>
    15. tr>
    16. <tr>
    17. <td>商品编号td>
    18. <td><input type="text" name="on" />是否递增<input type="checkbox"
    19. name="diZeng" value="auto" />td>
    20. tr>
    21. <tr>
    22. <td>商品品牌td>
    23. <td><input type="text" name="logo" />td>
    24. tr>
    25. <tr>
    26. <td>供应商td>
    27. <td><input type="text" name="supplier" />td>
    28. tr>
    29. <tr>
    30. <td>商品价格td>
    31. <td><input type="text" name="price" />td>
    32. tr>
    33. <tr>
    34. <td>商品备注td>
    35. <td><input type="text" name="remark" />td>
    36. tr>
    37. <tr>
    38. <td colspan="2" align="center" id="cuoWu">
    39. <%
    40. Object s = request.getAttribute("error");
    41. if (s != null) {
    42. %> <span style="color: red"> <%=s%>
    43. span> <%
    44. }
    45. %>
    46. td>
    47. tr>
    48. <tr>
    49. <td colspan="2" align="center"><input type="submit" value="添加"
    50. onclick="cheak()" /><input type="button" value="返回"
    51. onclick="history.back()" />td>
    52. tr>
    53. table>
    54. form>
    55. body>
    56. html>

    写pojo:

    1. package Pojo;
    2. import java.util.ArrayList;
    3. import java.util.List;
    4. public class ShangPin {
    5. public static List ShangPinList = new ArrayList<>();
    6. public static int baseNo = 0;
    7. private String name;// 名字
    8. private int on;// 编号
    9. private String logo;// 品牌
    10. private String supplier;// 供应商
    11. private double price;// 价格
    12. private String remark;// 备注
    13. public ShangPin(String name, int on, String logo, String supplier, double price, String remark) {
    14. this.name = name;
    15. this.on = on;
    16. this.logo = logo;
    17. this.supplier = supplier;
    18. this.price = price;
    19. this.remark = remark;
    20. }
    21. public String getName() {
    22. return name;
    23. }
    24. public void setName(String name) {
    25. this.name = name;
    26. }
    27. public int getOn() {
    28. return on;
    29. }
    30. public void setOn(int no) {
    31. this.on = no;
    32. }
    33. public String getLogo() {
    34. return logo;
    35. }
    36. public void setLogo(String logo) {
    37. this.logo = logo;
    38. }
    39. public String getSupplier() {
    40. return supplier;
    41. }
    42. public void setSupplier(String supplier) {
    43. this.supplier = supplier;
    44. }
    45. public double getPrice() {
    46. return price;
    47. }
    48. public void setPrice(double price) {
    49. this.price = price;
    50. }
    51. public String getRemark() {
    52. return remark;
    53. }
    54. public void setRemark(String remark) {
    55. this.remark = remark;
    56. }
    57. }

    写Servlet:

    1. package Servlet;
    2. import java.io.IOException;
    3. import Pojo.ShangPin;
    4. import jakarta.servlet.ServletException;
    5. import jakarta.servlet.annotation.WebServlet;
    6. import jakarta.servlet.http.HttpServlet;
    7. import jakarta.servlet.http.HttpServletRequest;
    8. import jakarta.servlet.http.HttpServletResponse;
    9. /**
    10. * Servlet implementation class AddServlet
    11. */
    12. @WebServlet("/AddServlet")
    13. public class AddServlet extends HttpServlet {
    14. private static final long serialVersionUID = 1L;
    15. /**
    16. * Default constructor.
    17. */
    18. public AddServlet() {
    19. // TODO Auto-generated constructor stub
    20. }
    21. /**
    22. * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
    23. * response)
    24. */
    25. protected void doGet(HttpServletRequest request, HttpServletResponse response)
    26. throws ServletException, IOException {
    27. doPost(request, response);
    28. }
    29. /**
    30. * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
    31. * response)
    32. */
    33. protected void doPost(HttpServletRequest request, HttpServletResponse response)
    34. throws ServletException, IOException {
    35. request.setCharacterEncoding("utf-8");
    36. String name = request.getParameter("name");// 名字
    37. String logo = request.getParameter("logo");// 获取品牌
    38. String supplier = request.getParameter("supplier");// 供应商
    39. String price = request.getParameter("price");// 价格
    40. String remark = request.getParameter("remark");// 备注
    41. String[] cbx = request.getParameterValues("diZeng");// 递增
    42. String on = "";
    43. if (cbx != null) {
    44. on = "" + (++(ShangPin.baseNo));
    45. } else {
    46. on = request.getParameter("on");// 编号
    47. }
    48. if (name.equals("") || logo.equals("") || supplier.equals("") || price.equals("") || remark.equals("")
    49. || on.equals("")) {
    50. request.setAttribute("error", "数据不能少");
    51. request.getRequestDispatcher("ZhuYe.jsp").forward(request, response);
    52. } else {
    53. ShangPin sp = new ShangPin(name, Integer.parseInt(on), logo, supplier, Double.parseDouble(price), remark);
    54. System.out.println(sp.getName());
    55. System.out.println(sp.getOn());
    56. System.out.println(sp.getLogo());
    57. System.out.println(sp.getSupplier());
    58. System.out.println(sp.getPrice());
    59. System.out.println(sp.getRemark());
    60. }
    61. }
    62. }

    前端负责收集信息、

    提交到后端时,右AddServlet处理信息,把每个数据取出来:

    request.getParameter("")

    request主要用于取出前端提交的信息

    是否递增选项为多选框,使用:

    String[] arr = request.getParameterValues("");

    后端逻辑:

    主要难点为多选框选中时和未选中时;

    选中时不取手动填写编号框

    未选中时取出手动填写编号框

     将所有数据取出后同一进行非空判断,

    如果不满足利用重定义方法重新定义到前端页面

    request.setAttribute("error", "数据不能少");//定义传回前端的提示数据
    request.getRequestDispatcher("ZhuYe.jsp").forward(request, response);//定义重定义页面,和传回的数据

    逻辑比较简单,仔细一点就能完成,404、500不要怕,奥里给!!干就完了!! 

    Servlet返回响应response使用

    1. response.setContentType("text/html;charset=UTF-8");
    2. PrintWriter out = response.getWriter();
    3. out.println("

      " + sp.getName() + "

      "
      );
    4. out.println("

      " + sp.getOn() + "

      "
      );
    5. out.println("

      " + sp.getLogo() + "

      "
      );
    6. out.println("

      " + sp.getSupplier() + "

      "
      );
    7. out.println("

      " + sp.getPrice() + "

      "
      );
    8. out.println("

      " + sp.getRemark() + "

      "
      );

    首先设置编码格式,获取输出对象、输出 

    显示当前登录名和安全退出按钮:

    使用session存入数据,只要浏览器没被关闭,就能使用

    登录页面:

    1. <%@ page language="java" contentType="text/html; charset=UTF-8"
    2. pageEncoding="UTF-8"%>
    3. html>
    4. <html>
    5. <head>
    6. <meta charset="UTF-8">
    7. <title>Insert title heretitle>
    8. head>
    9. <body>
    10. <form action="loginServlet" method="post">
    11. <table border="1px">
    12. <tr>
    13. <td>
    14. 用户名:
    15. td>
    16. <td>
    17. <input type="text" name=name />
    18. td>
    19. tr>
    20. <tr>
    21. <td>密码:td>
    22. <td><input type="password" name="pwd" />td>
    23. tr>
    24. <tr>
    25. <td>
    26. <%Object s=request.getAttribute("error");
    27. if(s!=null){
    28. out.print("<p style='color:red'>"+s+"p>");
    29. }
    30. %>
    31. td>
    32. <td><input type="submit" value="登录" />td>
    33. tr>
    34. table>
    35. form>
    36. body>
    37. html>

    处理登录servlet类:

    1. package Servlet;
    2. import java.io.IOException;
    3. import jakarta.servlet.ServletException;
    4. import jakarta.servlet.annotation.WebServlet;
    5. import jakarta.servlet.http.HttpServlet;
    6. import jakarta.servlet.http.HttpServletRequest;
    7. import jakarta.servlet.http.HttpServletResponse;
    8. import jakarta.servlet.http.HttpSession;
    9. /**
    10. * Servlet implementation class loginServlet
    11. */
    12. @WebServlet("/loginServlet")
    13. public class loginServlet extends HttpServlet {
    14. private static final long serialVersionUID = 1L;
    15. /**
    16. * Default constructor.
    17. */
    18. public loginServlet() {
    19. // TODO Auto-generated constructor stub
    20. }
    21. /**
    22. * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
    23. * response)
    24. */
    25. protected void doGet(HttpServletRequest request, HttpServletResponse response)
    26. throws ServletException, IOException {
    27. doPost(request, response);
    28. }
    29. /**
    30. * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
    31. * response)
    32. */
    33. protected void doPost(HttpServletRequest request, HttpServletResponse response)
    34. throws ServletException, IOException {
    35. String name = "test";
    36. String pwd = "test";
    37. String htmlName = request.getParameter("name");
    38. String htmlPwd = request.getParameter("pwd");
    39. if (name.equals(htmlName) && pwd.equals(htmlPwd)) {
    40. HttpSession session=request.getSession();
    41. session.setAttribute("NAME", name);
    42. request.getRequestDispatcher("ZhuYe.jsp").forward(request, response);
    43. } else {
    44. request.setAttribute("error", "用户名或密码错误");
    45. request.getRequestDispatcher("login.jsp").forward(request, response);
    46. }
    47. }
    48. }

    显示当前登录名字和安全退出按钮:

    1. <div id="yonghu">
    2. <%
    3. out.print(session.getAttribute("NAME"));
    4. %>
    5. <a href="tuiChuServlet">退出登录a>
    6. div>

    安全退出servlet类:

    1. package Servlet;
    2. import java.io.IOException;
    3. import jakarta.servlet.ServletException;
    4. import jakarta.servlet.annotation.WebServlet;
    5. import jakarta.servlet.http.HttpServlet;
    6. import jakarta.servlet.http.HttpServletRequest;
    7. import jakarta.servlet.http.HttpServletResponse;
    8. import jakarta.servlet.http.HttpSession;
    9. import jakarta.websocket.Session;
    10. /**
    11. * Servlet implementation class tuiChuServlet
    12. */
    13. @WebServlet("/tuiChuServlet")
    14. public class tuiChuServlet extends HttpServlet {
    15. private static final long serialVersionUID = 1L;
    16. /**
    17. * Default constructor.
    18. */
    19. public tuiChuServlet() {
    20. // TODO Auto-generated constructor stub
    21. }
    22. /**
    23. * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
    24. * response)
    25. */
    26. protected void doGet(HttpServletRequest request, HttpServletResponse response)
    27. throws ServletException, IOException {
    28. doPost(request, response);
    29. }
    30. /**
    31. * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
    32. * response)
    33. */
    34. protected void doPost(HttpServletRequest request, HttpServletResponse response)
    35. throws ServletException, IOException {
    36. HttpSession session = request.getSession();
    37. session.invalidate();
    38. request.getRequestDispatcher("login.jsp").forward(request, response);
    39. }
    40. }

    逻辑为:清除session数据,

    重定义页面。

  • 相关阅读:
    希尔伯特变换分析及应用
    【Tomcat】项目部署和Servlet的生命周期
    Android网络基础面试题之HTTPS的工作流程和原理
    【云原生之k8s】K8s 管理工具 kubectl 详解(二)
    修改docker默认存储位置【高版本的docker】
    低代码开发
    趣链的产品构架
    【Tools】i1Profiler1.7安装教程详解
    [C++]C++入门--引用
    11_printf函数移植串口通信
  • 原文地址:https://blog.csdn.net/qx020814/article/details/126171134