servlet技术用于处理页面的请求,创建servletJAVA类,里面有响应页面请求的方法
servlet的生命周期为:
- package Servlet;
-
- import java.io.IOException;
- import jakarta.servlet.ServletConfig;
- import jakarta.servlet.ServletException;
- import jakarta.servlet.annotation.WebServlet;
- import jakarta.servlet.http.HttpServlet;
- import jakarta.servlet.http.HttpServletRequest;
- import jakarta.servlet.http.HttpServletResponse;
-
- /**
- * Servlet implementation class Servletshengmingzhouqi
- */
- //@WebServlet("/Servletshengmingzhouqi")
- public class Servletshengmingzhouqi extends HttpServlet {
- private static final long serialVersionUID = 1L;
-
- /**
- * Default constructor.
- */
- static {
- System.out.println("Servlet被加载....");
- }
-
- public Servletshengmingzhouqi() {
- System.out.println("Servlet被实例化....");
- }
-
- /**
- * @see Servlet#init(ServletConfig)
- */
- public void init(ServletConfig config) throws ServletException {
- System.out.println("Servlet被初始化....");
- }
-
- /**
- * @see Servlet#destroy()
- */
- public void destroy() {
- System.out.println("Servlet被销毁....");
- }
-
- /**
- * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
- * response)
- */
- protected void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- System.out.println("Servlet请求处理中....");
- }
-
- /**
- * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
- * response)
- */
- protected void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- System.out.println("Servlet请求服务中....");
- }
-
- }
加载-实例化-初始化-处理-销毁
servlet类中的主要方法就是:
init:初始化方法,在构造函数后面调用
destroy:销毁方法,在手动关闭servlet时调用
doGet、doPost:浏览器使用get、post方法时调用指定方法
默认情况下,浏览器发送请求时servlet进行加载-实例化-初始化,不过可以在wep.xml配置默认服务器开启时自动 加载-实例化-初始化:
1 给定的数字参数越大,服务器在实例化它时优先级就越高,0为浏览器发送请求时实例化
浏览器页面若想使用servlet就需要配置路径:
- <servlet>
- <servlet-name>smzqservlet-name>
- <servlet-class>Servlet.Servletshengmingzhouqiservlet-class>
-
- servlet>
- <servlet-mapping>
- <servlet-name>smzqservlet-name>
- <url-pattern>/Servletsmzqurl-pattern>
- servlet-mapping>
servlet-name:servlet的别名
servlet-class:servlet类的地址
url-pattern:将servlet访问地址切换为这个名字,form地址栏可以直接用这个地址
以上配置文件也许有一些繁琐,也可以直接在servlet类中配置:
@WebServlet("/Servletsmzq")
这两种方法选其中一种就像,但是同时只能出现一种,不然你懂的:
既然已经了解了基本方法,我们来写一个网页提交信息的练习:
写前端:
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>Insert title heretitle>
- head>
- <body>
- <form action="AddServlet" method="post">
- <table border="1px">
- <tr>
- <td>商品名称td>
- <td><input type="text" name="name" />td>
- tr>
- <tr>
- <td>商品编号td>
- <td><input type="text" name="on" />是否递增<input type="checkbox"
- name="diZeng" value="auto" />td>
-
- tr>
- <tr>
- <td>商品品牌td>
- <td><input type="text" name="logo" />td>
- tr>
- <tr>
- <td>供应商td>
- <td><input type="text" name="supplier" />td>
- tr>
- <tr>
- <td>商品价格td>
- <td><input type="text" name="price" />td>
- tr>
- <tr>
- <td>商品备注td>
- <td><input type="text" name="remark" />td>
- tr>
- <tr>
- <td colspan="2" align="center" id="cuoWu">
- <%
- Object s = request.getAttribute("error");
- if (s != null) {
- %> <span style="color: red"> <%=s%>
- span> <%
- }
- %>
- td>
- tr>
- <tr>
- <td colspan="2" align="center"><input type="submit" value="添加"
- onclick="cheak()" /><input type="button" value="返回"
- onclick="history.back()" />td>
- tr>
- table>
- form>
- body>
- html>
写pojo:
- package Pojo;
-
- import java.util.ArrayList;
- import java.util.List;
-
- public class ShangPin {
- public static List
ShangPinList = new ArrayList<>(); - public static int baseNo = 0;
- private String name;// 名字
- private int on;// 编号
- private String logo;// 品牌
- private String supplier;// 供应商
- private double price;// 价格
- private String remark;// 备注
-
- public ShangPin(String name, int on, String logo, String supplier, double price, String remark) {
- this.name = name;
- this.on = on;
- this.logo = logo;
- this.supplier = supplier;
- this.price = price;
- this.remark = remark;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public int getOn() {
- return on;
- }
-
- public void setOn(int no) {
- this.on = no;
- }
-
- public String getLogo() {
- return logo;
- }
-
- public void setLogo(String logo) {
- this.logo = logo;
- }
-
- public String getSupplier() {
- return supplier;
- }
-
- public void setSupplier(String supplier) {
- this.supplier = supplier;
- }
-
- public double getPrice() {
- return price;
- }
-
- public void setPrice(double price) {
- this.price = price;
- }
-
- public String getRemark() {
- return remark;
- }
-
- public void setRemark(String remark) {
- this.remark = remark;
- }
- }
写Servlet:
- package Servlet;
-
- import java.io.IOException;
-
- import Pojo.ShangPin;
- import jakarta.servlet.ServletException;
- import jakarta.servlet.annotation.WebServlet;
- import jakarta.servlet.http.HttpServlet;
- import jakarta.servlet.http.HttpServletRequest;
- import jakarta.servlet.http.HttpServletResponse;
-
- /**
- * Servlet implementation class AddServlet
- */
- @WebServlet("/AddServlet")
- public class AddServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
-
- /**
- * Default constructor.
- */
- public AddServlet() {
- // TODO Auto-generated constructor stub
- }
-
- /**
- * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
- * response)
- */
- protected void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doPost(request, response);
- }
-
- /**
- * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
- * response)
- */
- protected void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- request.setCharacterEncoding("utf-8");
- String name = request.getParameter("name");// 名字
- String logo = request.getParameter("logo");// 获取品牌
- String supplier = request.getParameter("supplier");// 供应商
- String price = request.getParameter("price");// 价格
- String remark = request.getParameter("remark");// 备注
- String[] cbx = request.getParameterValues("diZeng");// 递增
- String on = "";
- if (cbx != null) {
- on = "" + (++(ShangPin.baseNo));
- } else {
- on = request.getParameter("on");// 编号
- }
- if (name.equals("") || logo.equals("") || supplier.equals("") || price.equals("") || remark.equals("")
- || on.equals("")) {
- request.setAttribute("error", "数据不能少");
- request.getRequestDispatcher("ZhuYe.jsp").forward(request, response);
- } else {
- ShangPin sp = new ShangPin(name, Integer.parseInt(on), logo, supplier, Double.parseDouble(price), remark);
- System.out.println(sp.getName());
- System.out.println(sp.getOn());
- System.out.println(sp.getLogo());
- System.out.println(sp.getSupplier());
- System.out.println(sp.getPrice());
- System.out.println(sp.getRemark());
- }
-
- }
-
- }
前端负责收集信息、
提交到后端时,右AddServlet处理信息,把每个数据取出来:
request.getParameter("")
request主要用于取出前端提交的信息
是否递增选项为多选框,使用:
String[] arr = request.getParameterValues("");
后端逻辑:
主要难点为多选框选中时和未选中时;
选中时不取手动填写编号框
未选中时取出手动填写编号框
将所有数据取出后同一进行非空判断,
如果不满足利用重定义方法重新定义到前端页面
request.setAttribute("error", "数据不能少");//定义传回前端的提示数据
request.getRequestDispatcher("ZhuYe.jsp").forward(request, response);//定义重定义页面,和传回的数据
逻辑比较简单,仔细一点就能完成,404、500不要怕,奥里给!!干就完了!!
Servlet返回响应response使用
- response.setContentType("text/html;charset=UTF-8");
- PrintWriter out = response.getWriter();
- out.println("
"
+ sp.getName() + ""); - out.println("
"
+ sp.getOn() + ""); - out.println("
"
+ sp.getLogo() + ""); - out.println("
"
+ sp.getSupplier() + ""); - out.println("
"
+ sp.getPrice() + ""); - out.println("
"
+ sp.getRemark() + "");
首先设置编码格式,获取输出对象、输出
显示当前登录名和安全退出按钮:
使用session存入数据,只要浏览器没被关闭,就能使用
登录页面:
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>Insert title heretitle>
- head>
- <body>
- <form action="loginServlet" method="post">
- <table border="1px">
- <tr>
- <td>
- 用户名:
- td>
- <td>
- <input type="text" name=name />
- td>
- tr>
- <tr>
- <td>密码:td>
- <td><input type="password" name="pwd" />td>
- tr>
- <tr>
- <td>
- <%Object s=request.getAttribute("error");
- if(s!=null){
- out.print("<p style='color:red'>"+s+"p>");
- }
- %>
-
- td>
- <td><input type="submit" value="登录" />td>
- tr>
- table>
-
-
- form>
- body>
- html>
处理登录servlet类:
- package Servlet;
-
- import java.io.IOException;
- import jakarta.servlet.ServletException;
- import jakarta.servlet.annotation.WebServlet;
- import jakarta.servlet.http.HttpServlet;
- import jakarta.servlet.http.HttpServletRequest;
- import jakarta.servlet.http.HttpServletResponse;
- import jakarta.servlet.http.HttpSession;
-
- /**
- * Servlet implementation class loginServlet
- */
- @WebServlet("/loginServlet")
- public class loginServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
-
- /**
- * Default constructor.
- */
- public loginServlet() {
- // TODO Auto-generated constructor stub
- }
-
- /**
- * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
- * response)
- */
- protected void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doPost(request, response);
- }
-
- /**
- * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
- * response)
- */
- protected void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- String name = "test";
- String pwd = "test";
- String htmlName = request.getParameter("name");
- String htmlPwd = request.getParameter("pwd");
- if (name.equals(htmlName) && pwd.equals(htmlPwd)) {
- HttpSession session=request.getSession();
- session.setAttribute("NAME", name);
- request.getRequestDispatcher("ZhuYe.jsp").forward(request, response);
- } else {
- request.setAttribute("error", "用户名或密码错误");
- request.getRequestDispatcher("login.jsp").forward(request, response);
- }
- }
-
- }
显示当前登录名字和安全退出按钮:
- <div id="yonghu">
- <%
- out.print(session.getAttribute("NAME"));
- %>
- <a href="tuiChuServlet">退出登录a>
- div>
安全退出servlet类:
- package Servlet;
-
- import java.io.IOException;
- import jakarta.servlet.ServletException;
- import jakarta.servlet.annotation.WebServlet;
- import jakarta.servlet.http.HttpServlet;
- import jakarta.servlet.http.HttpServletRequest;
- import jakarta.servlet.http.HttpServletResponse;
- import jakarta.servlet.http.HttpSession;
- import jakarta.websocket.Session;
-
- /**
- * Servlet implementation class tuiChuServlet
- */
- @WebServlet("/tuiChuServlet")
- public class tuiChuServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
-
- /**
- * Default constructor.
- */
- public tuiChuServlet() {
- // TODO Auto-generated constructor stub
- }
-
- /**
- * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
- * response)
- */
- protected void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doPost(request, response);
- }
-
- /**
- * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
- * response)
- */
- protected void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- HttpSession session = request.getSession();
- session.invalidate();
- request.getRequestDispatcher("login.jsp").forward(request, response);
- }
-
- }
逻辑为:清除session数据,
重定义页面。