JavaWeb学习总结-04 Servlet 学习和使用

一 Servlet

1 Servlet概念

Servlet时运行在服务器端的Java程序。

Servlet的框架核心是 javax.servlet.Servlet 接口. 所有自定义的Servlet都必须实现这已接口,Servlet 的常用方法(生命周期的三个阶段):

  • init 方法:负责初始化 Servlet对象。
  • service 方法:负责响应客户的请求。
  • destory 方法:当Servlet对象退出生命周期时,负责释放占用的资源。

它们分别在Servlet的不同阶段被调用。

2 Servlet api

JavaWeb学习总结-04 Servlet 学习和使用

  javax.servlet.http.HttpServlet类的所有doXXX()方法可以开发者去实现它们,具体设计模式参考模板模式

  自定义的Servlet继承(extend)了HttpServlet类,通常不比实现service方法,因为HttpServlet已经实现了service方法,该方法声明如下:

JavaWeb学习总结-04 Servlet 学习和使用

  在HttpServlet的service方法中,首先从ServletRequest获取HTTP的请求信息,然后根据请求方式调用响应的请求方法。例如如果请求方式为GET,那么调用doGet方法,如果请求方式为POST,那么调用doPOST方法,其他请求方式以此类推。

3 Servlet的生命周期

Servlet的初始化阶段

1)在下列时刻Servlet容器加载Servlet

  • Servlet容器启动时自动加载Servlet。
  • 在Servlet容器启动后,客户首次向Servlet发送请求。
  • Servlet的类文件更新后,重新加载Servlet。

2)Servlet被装载后,Servlet容器创建一个Servlet实例,并调用Servlet的init()方法进行初始化,在Servlet的整个声明周期 init()方法只被调用一次。

Servlet的响应客户阶段

  对于到达Servlet容器的客户请求,Servlet容器创建于这个请求的ServletRequest对象和ServletResponse对象,然后调用Servlet的service()方法,service方法从ServletRequest对象获得客户请求信息,处理改请求。并通过ServletResponse对象向客户返回响应结果。

Servlet的终止阶段

  当web应用被终止,或Servlet容器终止运行,或Servlet容器重新加载servlet实例时,Servlet容器会调用Servlet的destory() 方法,在destory()方法中可以释放Servlet所占用的资源。

  如何让Servlet容器动态加载servlet类文件,请参考JavaWeb学习总结-02 Tomcat 学习和使用 的热部署。

二 例子

1 第一个Servlet

新建java web项目 javaWeb1.

Servlet1.java

package com.test;

import java.io.IOException;
import java.io.PrintWriter;

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

public class Servlet1 extends HttpServlet {

    private static final long serialVersionUID = 1L;

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

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE html>  ");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.print("    This is ");
        out.print(this.getClass());
        out.println(", using the <h1>GET method</h1>");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

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

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE html>");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.print("    This is ");
        out.print(this.getClass());
        out.println(", using the POST method");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID" version="3.1">
    <display-name>javaWeb1</display-name>

    <servlet>
        <servlet-name>Servlet1</servlet-name>
        <servlet-class>com.test.Servlet1</servlet-class>
    </servlet>

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

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>

访问url地址 http://127.0.0.1:8080/javaWeb1/servlet/Servlet1,测试在 get,post下的返回值。

2 通过表单提交数据,servlet响应请求

index.jsp

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

<!DOCTYPE  >
<html>
  <head>
    <base href="<%=basePath%>">

    <title>title1</title>
    <meta charset="utf-8">
  </head>

  <body>
  <form action="/javaWeb1/servlet/Servlet2">
      用户名: <input type=" /> <br>
      密码: <input type="password" name="password" /> <br>
   <input type="submit" value="提交">&nbsp;&nbsp;
   <input type="reset" value="重置" >
  </form>
  </body>
</html>

  表单默认不设置提交方法是按照 get方式提交的, method可以设置get,post方式提交数据。

get和post方式的区别?

1)处理方式不同

2)地址栏呈现的结果不同

  get方式是把传递的参数放在url里。

  post方式是放在请求头里,地址栏里不会带参数。

Servlet2.java

package com.test;

import java.io.IOException;
import java.io.PrintWriter;

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

public class Servlet2 extends HttpServlet {

    private static final long serialVersionUID = 1L;

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

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

    public void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println("username=" + username);
        System.out.println("password=" + password);

        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>qqqqqq</TITLE></HEAD>");
        out.println("  <BODY>");
        out.print("username=" + username + "<br>");
        out.print("password=" + password);
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

}

访问url地址 http://127.0.0.1:8080/javaWeb1/index.jsp

实验

response.setContentType("text/html;charset=utf-8");标签换为 response.setContentType("text/html ");并在输出中输出中文。

3 通过表单提交数据,jsp响应请求

getPara.jsp

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

    String username = request.getParameter("username");
    String password = request.getParameter("password");
    System.out.println("username=" + username);
    System.out.println("password=" + password);

%>

<!DOCTYPE HTML >
<html>
<head>
<base href="<%=basePath%>">

<title> </title>
</head>

<body>

username=<%= username %> <br>
password=<%= password %>

</body>
</html>

index2.jsp

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

<!DOCTYPE  >
<html>
  <head>
    <base href="<%=basePath%>">

    <title>title1</title>
    <meta charset="utf-8">
  </head>

  <body>
  <form action="/javaWeb1/getPara.jsp" method="post"  >
      用户名: <input type=" /> <br>
      密码: <input type="password" name="password" /> <br>
   <input type="submit" value="提交">&nbsp;&nbsp;
   <input type="reset" value="重置" >
  </form>
  </body>
</html>

访问url地址 http://127.0.0.1:8080/javaWeb1/index2.jsp

参考资料:

j2ee在线文档工具

上一篇:Change default network name (ens33) to old “eth0” on Ubuntu 18.04 / Ubuntu 16.04


下一篇:[ES6] Object.assign (with defaults value object)