JavaWeb学习总结-05 Servlet 学习和使用(01)

时间:2024-11-28 20:06:43

一 Servlet的原理

1 Servlet 的创建

  当Servlet容器启动web应用时,需要立即加载Servlet时:

  Servlet容器启动web应用时,将按照指定的顺序初始化Servlet,需要设置<Servlet>元素的<load-on-startup>子元素。<load-on-startup>设置的值为数字,当值为0或者大于0时,表示容器在应用启动时就顺序加载并初始化这个servlet。

  当Servlet容器启动时会启动所有的web应用。

2 ServletContex与web应用的关系。

  当Servlet容器启动Web应用时,并为每个Web应用创建唯一的ServletCOntext对象。可以把ServletContext看成是一个Web应用的服务器端组件的共享内存。在ServletContext中可以存放共享数据,它提供了读取或设置共享数据的方法。

  ServletContext中可以存放共享数据,它提供了读取或设置共享数据的方法:

  • setAttribute(String name, Object object)把一个对象和一个属性名绑定,将这个对象存储在ServletContext中。
  • getAttribute(String name)根据给定的属性名返回所绑定的对象。

3 getRequestDispatcher()与sendRedirect()的区别

  • request.getRequestDispatcher()是请求转发,前后页面共享一个request ;
  • response.sendRedirect()是重新定向,前后页面不是一个request。

二 例子

1 Servlet容器启动web应用时,将按照指定的顺序初始化Servlet

LoadInitServlet.java

package com.test;

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

public class LoadInitServlet extends HttpServlet {

    public void init() throws ServletException {
        super.init();
    }
}

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>LoadInitServlet</servlet-name>
        <servlet-class>com.test.LoadInitServlet</servlet-class>
        <load-on-startup></load-on-startup>
    </servlet>

</web-app>

2 ServletContex的计时器例子

CounterServlet.java

package com.test;

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

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

public class CounterServlet extends HttpServlet {

    private static final String CONTENT_TYPE = "text/html;charset=utf-8";

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        System.out.println("init invoked");
    }

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

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

        // 获得ServletContext的引用
        ServletContext context = getServletContext();
        // 从ServletContext读取count属性
        Integer count = (Integer) context.getAttribute("count");

        // 如果count属性还没有设置, 那么创建count属性,初始值为0
        // one and add it to the ServletContext
        if (count == null) {
            count = );
            context.setAttribute());
        }

        response.setContentType(CONTENT_TYPE);
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head><title>WebCounter</title></head>");
        out.println("<body>");
        // 输出当前的count属性值
        out.println("<p><h1>The current COUNT is : " + count + ".</h1></p>");
        out.println("</body></html>");
        // 创建新的count对象,其值增1
        count = );
        // 将新的count属性存储到ServletContext中
        context.setAttribute("count", count);
    }

    public void destroy() {
    }
}

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>CounterServlet</servlet-name>
        <servlet-class>com.test.CounterServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>CounterServlet</servlet-name>
        <url-pattern>/CounterServlet</url-pattern>
    </servlet-mapping>
</web-app>

3 请求转发例子

TestServlet.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 TestServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("--- TestServlet doGet --");

        request.setAttribute("name", "zhangsan");

        //请求转发
        request.getRequestDispatcher("/test2.jsp").forward(request, response);;
     //重定向
        /*String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path;
        response.sendRedirect(basePath + "/test2.jsp");*/
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("--- TestServlet doPost --");

    }

}

test2.jsp

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

    String name = (String)request.getAttribute("name");
%>

<!DOCTYPE HTML >
<html>
<head>
<base href="<%=basePath%>">
<title>test2.jsp</title>

</head>

<body>
你好 <%= name %>

</body>
</html>

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>TestServlet</servlet-name>
        <servlet-class>com.test.TestServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>TestServlet</servlet-name>
        <url-pattern>/TestServlet</url-pattern>
    </servlet-mapping>
</web-app>

  要对传输的中文字符串进行编码,参考使用Wireshark 抓取数据包