week hello2源码解析

hello2应用程序是一个Web模块,它使用Java Servlet技术来显示问候语和响应,源代码位置在_tut-install_/examples/web/servlet/hello2/

虽然该hello2应用程序的表现几乎相同的hello1 应用程序,但它使用Java Servlet技术,而不是JavaServer Faces技术实现的

cd到该目录,命令行打包(可参见上一篇博客步骤)

打开eclipse,点击GreetingServlet.java   Run as    Run on server 

1.选择hello2文件夹并单击“打开项目”

2.点击pom.xml打开网页如图所示:

  

可见,跟hello1 不一样的是hello2是servlet的。

3.

    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">//此标签可告知浏览器文档使用哪种HTML规范;DTD一套文本类型的定义;标准原文的链接
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html">//语言使用英文;xml采用名字空间声明,允许你通过一个网址来识别你的标记;jcp是java社区的执行委员会 <h:head> <title>Facelets Hello Greeting</title> </h:head> <h:body> <h:form> <h:graphicImage url="#{resource['images:duke.waving.gif']}" alt="Duke waving his hand"/>//作为资源形式出现的;alt加载不出来就进行替换 <h2>Hello, my name is Duke. What's yours?</h2> <h:inputText id="username" title="My name is: " value="#{hello.name}" required="true" requiredMessage="Error: A name is required."

<p></p> <h:commandButton id="submit" value="Submit" action="response"> </h:commandButton> <h:commandButton id="reset" value="Reset" type="reset"> </h:commandButton>//Submit commandButton元素将操作指定为response,表示单击按钮时,将response.xhtml显示该页面

</h:form> ... </h:body> </html>


展开“源包”节点,然后展开javaeetutorial.hello2节点。双击该Hello.java文件以查看它。如图所示

点开两个后可参看代码:

greetingservelet.java

/**
 * Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
 *
 * You may not modify, use, reproduce, or distribute this software except in
 * compliance with  the terms of the License at:
 * https://github.com/javaee/tutorial-examples/LICENSE.txt
 */
package javaeetutorial.hello2;

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

/**
 * This is a simple example of an HTTP Servlet. It responds to the GET method of
 * the HTTP protocol.
 */
@WebServlet("/greeting")
public class GreetingServlet extends HttpServlet {

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

        response.setContentType("text/html");
        response.setBufferSize(8192);
        try (PrintWriter out = response.getWriter()) {
            out.println("<html lang=\"en\">"
                    + "<head><title>Servlet Hello</title></head>");
            
            // then write the data of the response
            out.println("<body  bgcolor=\"#ffffff\">"
                    + "<img src=\"resources/images/duke.waving.gif\" "
                    + "alt=\"Duke waving his hand\">"
                    + "<form method=\"get\">"
                    + "<h2>Hello, my name is Duke. What's yours?</h2>"
                    + "<input title=\"My name is: \" type=\"text\" "
                    + "name=\"username\" size=\"25\"/>"
                    + "<p></p>"
                    + "<input type=\"submit\" value=\"Submit\"/>"
                    + "<input type=\"reset\" value=\"Reset\"/>"
                    + "</form>");
            
            String username = request.getParameter("username");
            if (username != null && username.length() > 0) {
                RequestDispatcher dispatcher =
                        getServletContext().getRequestDispatcher("/response");
                
                if (dispatcher != null) {
                    dispatcher.include(request, response);
                }
            }
            out.println("</body></html>");
        }
    }

    @Override
    public String getServletInfo() {
        return "The Hello servlet says hello.";

    }
}

  

这个servlet覆盖了doGet方法,实现了HTTP的GET方法。servlet显示一个简单的HTML问候表单,它的Submit按钮,就像hello1那样,为其操作指定一个响应页面。下面的摘录从@WebServlet注释开始,它指定了相对于上下文根的URL模式:

responseservlet.java

/**
 * Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
 *
 * You may not modify, use, reproduce, or distribute this software except in
 * compliance with  the terms of the License at:
 * https://github.com/javaee/tutorial-examples/LICENSE.txt
 */
package javaeetutorial.hello2;

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

/**
 * This is a simple example of an HTTP Servlet. It responds to the GET method of
 * the HTTP protocol.
 */
@WebServlet("/greeting")
public class GreetingServlet extends HttpServlet {

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

        response.setContentType("text/html");
        response.setBufferSize(8192);
        try (PrintWriter out = response.getWriter()) {
            out.println("<html lang=\"en\">"
                    + "<head><title>Servlet Hello</title></head>");
            
            // then write the data of the response
            out.println("<body  bgcolor=\"#ffffff\">"
                    + "<img src=\"resources/images/duke.waving.gif\" "
                    + "alt=\"Duke waving his hand\">"
                    + "<form method=\"get\">"
                    + "<h2>Hello, my name is Duke. What's yours?</h2>"
                    + "<input title=\"My name is: \" type=\"text\" "
                    + "name=\"username\" size=\"25\"/>"
                    + "<p></p>"
                    + "<input type=\"submit\" value=\"Submit\"/>"
                    + "<input type=\"reset\" value=\"Reset\"/>"
                    + "</form>");
            
            String username = request.getParameter("username");
            if (username != null && username.length() > 0) {
                RequestDispatcher dispatcher =
                        getServletContext().getRequestDispatcher("/response");
                
                if (dispatcher != null) {
                    dispatcher.include(request, response);
                }
            }
            out.println("</body></html>");
        }
    }

    @Override
    public String getServletInfo() {
        return "The Hello servlet says hello.";

    }
}
 

要理解上面代码我们必须先要理解以下概念

(1)getParameter

String javax.servlet.ServletRequest.getParameter(String name)

以String形式返回请求参数的值,如果参数不存在,则返回null。请求参数是随请求一起发送的额外信息。对于HTTP servlet,参数包含在查询字符串或发布的表单数据中。只有在确定参数只有一个值时才应使用此方法  

(2)RequestDispatcher

javax.servlet.RequestDispatcher 

定义一个对象,该对象接收来自客户端的请求,并将它们发送到服务器上的任何资源(例如servlet,HTML文件或JSP文件)。 servlet容器创建RequestDispatcher对象,该对象用作位于特定路径或由特定名称给出的服务器资源的包装器。此接口旨在包装servlet,但servlet容器可以创建RequestDispatcher对象来包装任何类型的资源。

(3)getServletContext()

ServletContext javax.servlet.GenericServlet.getServletContext()

提供该方法是为了方便起见。它从servlet的ServletConfig对象获取上下文。

返回:ServletContext由init方法传递给此servlet的ServletContext对象

(4)getRequestDispatcher()

RequestDispatcher javax.servlet.ServletContext.getRequestDispatcher(String path)

返回一个RequestDispatcher对象,该对象充当位于给定路径的资源的包装器。 RequestDispatcher对象可用于将请求转发到资源或将资源包含在响应中。资源可以是动态的也可以是静态的。路径名必须以 / 开头,并且被解释为相对于当前上下文根。使用getContext为外部上下文中的资源获取RequestDispatcher。如果ServletContext无法返回RequestDispatcher,则此方法返回null。 

(5)  include(request, response)

void javax.servlet.RequestDispatcher.include(ServletRequest request, ServletResponse response) throws ServletException, IOException 

包含响应中的资源(servlet,JSP页面,HTML文件)的内容。从本质上讲,这种方法可以实现程序化服务器端包含。 ServletResponse对象的路径元素和参数与调用者保持不变。包含的servlet无法更改响应状态代码或设置标头;任何改变的尝试都会被忽略。请求和响应参数必须是传递给调用servlet的服务方法的相同对象,或者是包装它们的ServletRequestWrapper或ServletResponseWrapper类的子类。此方法将给定请求的调度程序类型设置为DispatcherType.INCLUDE。

参数:

Parameters:

  • request a ServletRequest object that contains the client's request

  • response a ServletResponse object that contains the servlet's response

运行后结果:

 

posted @ 2019-03-23 20:18  肥鹤不只是肉多还追光  阅读(200)  评论(0编辑  收藏  举报