如何从Java客户端与一个Servlet通信

huangapple go评论101阅读模式
英文:

How to communicate with a servlet from a Java client

问题

我在 Windows 10 上使用 Netbeans 12 开发了一个 servlet。该 servlet 部署在集成了 Netbeans IDE 的我的计算机上的 Apache Tomcat 9.0.39 上。在开发 servlet 时,Netbeans IDE 会自动创建一个带有静态 HTML 内容的 index.html 文件,并将该文件放在“src->main->webapp”文件夹下。
客户端向 servlet 发送一个字符串,servlet 反转该字符串并将其返回给客户端。然而,我的客户端只在来自 servlet 的响应中看到 index.html 的静态内容(如上所述),而没有看到 servlet 将反转的字符串对象写入 PrintWriter 对象(从 Response.getWriter() 获取)。

下面是 index.html 的内容:

<!DOCTYPE html>
<html>
    <head>
        <title>My first servlet</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <h1>Reversing Strings!!!</h1>
        <p> This is index.html page</p>
    </body>
</html>

以下是 web.xml 的内容:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>ReverseString</servlet-name>
        <servlet-class>org.me.servletlearning.ReverseString</servlet-class>
        <init-param>
            <param-name>greeting</param-name>
            <param-value>Hello Tony</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>ReverseString</servlet-name>
        <url-pattern>/reversestring</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

以下是 context.xml 的内容:

<?xml version="1.0" encoding="UTF-8"?>
<Context path="/reversestring"/>

以下是 servlet 的内容:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    String inputString = request.getParameter("reverse_string");
    StringBuilder temp = new StringBuilder(inputString);
    String result = temp.reverse().toString();
    try (PrintWriter out = response.getWriter()) {
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet ReverseString</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet ReverseString at " + request.getContextPath() + "</h1>");
        out.println("<p> The input string:"+inputString+"<br>");
        out.println("The reversed string:"+result+" </p>");
        out.println("</body>");
        out.println("</html>");
    }
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

以下是客户端的内容:

public static void writeToURL() {
    try {
        String stringToReverse = URLEncoder.encode("HelloWorld", "UTF-8");
        URL url = new URL("http://localhost:8080/reversestring/");
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        OutputStreamWriter out = new OutputStreamWriter(
                connection.getOutputStream());
        out.write("reverse_string=" + stringToReverse);
        out.close();
        BufferedReader in = new BufferedReader(
                new InputStreamReader(
                        connection.getInputStream()));
        String decodedString;
        while ((decodedString = in.readLine()) != null) {
            System.out.println(decodedString);
        }
        in.close();
    } catch (UnsupportedEncodingException ex) {
        ex.printStackTrace();
    } catch (MalformedURLException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

客户端从 servlet 收到的内容如下:

<!DOCTYPE html>
<html>
    <head>
        <title>My first servlet</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <h1>Reversing Strings!!!</h1>
        <p> This is index.html page</p>
    </body>
</html>

在我的代码中缺少什么?谢谢。

英文:

I have developed a servlet using Netbeans 12 on Windows 10. The servlet is deployed on Apache Tomcat 9.0.39 on my machine that is integrated with the Netbeans IDE. When developing a servlet, the Netbeans IDE automatically creates an index.html file with static Html content and places the file under the “src->main->webapp” folder.<br>
The client sends a string to the servlet and the servlet reverses the string and returns it back to the client. However my client only sees the static content of the index.html (mentioned above) in the response from the servlet and not the reversed String object that servlet has written to the PrintWriter object (obtained from the Response.getWriter()).
<br>Here is the content of the index.html:

&lt;!DOCTYPE html&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;title&gt;My first servlet&lt;/title&gt;
        &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;h1&gt;Reversing Strings!!!&lt;/h1&gt;
        &lt;p&gt; This is index.html page&lt;/p&gt;
    &lt;/body&gt;
&lt;/html&gt;

<br>Here is the web.xml:

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;web-app version=&quot;3.1&quot; xmlns=&quot;http://xmlns.jcp.org/xml/ns/javaee&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd&quot;&gt;
    &lt;servlet&gt;
        &lt;servlet-name&gt;ReverseString&lt;/servlet-name&gt;
        &lt;servlet-class&gt;org.me.servletlearning.ReverseString&lt;/servlet-class&gt;
        &lt;init-param&gt;
            &lt;param-name&gt;greeting&lt;/param-name&gt;
            &lt;param-value&gt;Hello Tony&lt;/param-value&gt;
        &lt;/init-param&gt;
    &lt;/servlet&gt;
    &lt;servlet-mapping&gt;
        &lt;servlet-name&gt;ReverseString&lt;/servlet-name&gt;
        &lt;url-pattern&gt;/reversestring&lt;/url-pattern&gt;
    &lt;/servlet-mapping&gt;
    &lt;session-config&gt;
        &lt;session-timeout&gt;
            30
        &lt;/session-timeout&gt;
    &lt;/session-config&gt;
&lt;/web-app&gt;

<br>Here is the context.xml:

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;Context path=&quot;/reversestring&quot;/&gt;

<br>Here is the servlet:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType(&quot;text/html;charset=UTF-8&quot;);
    String inputString = request.getParameter(&quot;reverse_string&quot;);
    StringBuilder temp = new StringBuilder(inputString);
    String result = temp.reverse().toString();
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        out.println(&quot;&lt;!DOCTYPE html&gt;&quot;);
        out.println(&quot;&lt;html&gt;&quot;);
        out.println(&quot;&lt;head&gt;&quot;);
        out.println(&quot;&lt;title&gt;Servlet ReverseString&lt;/title&gt;&quot;);            
        out.println(&quot;&lt;/head&gt;&quot;);
        out.println(&quot;&lt;body&gt;&quot;);
        out.println(&quot;&lt;h1&gt;Servlet ReverseString at &quot; + request.getContextPath() + &quot;&lt;/h1&gt;&quot;);
        out.println(&quot;&lt;p&gt; The input string: &quot;+inputString+&quot;&lt;br&gt;&quot;);
        out.println(&quot;The reversed string: &quot;+result+&quot; &lt;/p&gt;&quot;);
        out.println(&quot;&lt;/body&gt;&quot;);
        out.println(&quot;&lt;/html&gt;&quot;);
    }
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}


@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

<br>The client:

public static void writeToURL() {
        try {
            //   need to study and understand servlet
            //   then write to a servelt through a URL object.
            String stringToReverse = URLEncoder.encode(&quot;HelloWorld&quot;, &quot;UTF-8&quot;);
            
            URL url = new URL(&quot;http://localhost:8080/reversestring/&quot;);
            URLConnection connection = url.openConnection();
            connection.setDoOutput(true);
            
            OutputStreamWriter out = new OutputStreamWriter(
                    connection.getOutputStream());
            out.write(&quot;reverse_string=&quot; + stringToReverse);
            out.close();
            
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                            connection.getInputStream()));
            String decodedString;
            while ((decodedString = in.readLine()) != null) {
                System.out.println(decodedString);
            }
            in.close();
        } catch (UnsupportedEncodingException ex) {
                    ex.printStackTrace();
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

<br> The content the client receives from the servlet:

&lt;!DOCTYPE html&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;title&gt;My first servlet&lt;/title&gt;
        &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;h1&gt;Reversing Strings!!!&lt;/h1&gt;
        &lt;p&gt; This is index.html page&lt;/p&gt;
    &lt;/body&gt;
&lt;/html&gt;

<br>What is missing from my code?
Thanks

答案1

得分: 0

你的 web 应用上下文路径是 /reversestring。字符串翻转的 servlet 在该上下文中的路径为 /reversestring。要向 servlet 发送请求,URL 应为:

http://localhost:8080/reversestring/reversestring
英文:

Your webapp context path is /reversestring. The string-reversing servlet is registered at path /reversestring within that context. To make a request to the servlet, the URL should be:

http://localhost:8080/reversestring/reversestring

huangapple
  • 本文由 发表于 2020年10月25日 00:11:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/64515445.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定