0

I'm following the java tutorial Reading and Writing to a URL and I'm stuck.

https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html

There are two block's of code. One for the servlet and one for the client.

The Servlet.

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.net.*;
 
public class ReverseServlet extends HttpServlet
{
    private static String message = "Error during Servlet processing";
     
    public void doPost(HttpServletRequest req, HttpServletResponse resp) {
        try {
            int len = req.getContentLength();
            byte[] input = new byte[len];
         
            ServletInputStream sin = req.getInputStream();
            int c, count = 0 ;
            while ((c = sin.read(input, count, input.length-count)) != -1) {
                count +=c;
            }
            sin.close();
         
            String inString = new String(input);
            int index = inString.indexOf("=");
            if (index == -1) {
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().print(message);
                resp.getWriter().close();
                return;
            }
            String value = inString.substring(index + 1);
             
            //decode application/x-www-form-urlencoded string
            String decodedString = URLDecoder.decode(value, "UTF-8");
             
            //reverse the String
            String reverseStr = (new StringBuffer(decodedString)).reverse().toString();
             
            // set the response code and write the response data
            resp.setStatus(HttpServletResponse.SC_OK);
            OutputStreamWriter writer = new OutputStreamWriter(resp.getOutputStream());
             
            writer.write(reverseStr);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            try{
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().print(e.getMessage());
                resp.getWriter().close();
            } catch (IOException ioe) {
            }
        }        
    }          
}

and the client

import java.io.*;
import java.net.*;

public class Reverse {
    public static void main(String[] args) throws Exception {

        if (args.length != 2) {
            System.err.println("Usage:  java Reverse "
                + "http://<location of your servlet/script>"
                + " string_to_reverse");
            System.exit(1);
        }

        String stringToReverse = URLEncoder.encode(args[1], "UTF-8");

        URL url = new URL(args[0]);
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);

        OutputStreamWriter out = new OutputStreamWriter(
                                         connection.getOutputStream());
        out.write("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();
    }
}

When I run the client with the command

java http://localhost:8080/ReverseString "Reverse me" 

it outputs a page not a reversed string.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="jetty-dir.css" rel="stylesheet" />
<title>Directory: /ReverseServlet/</title>
</head>
<body>
<h1 class="title">Directory: /ReverseServlet/</h1>
<table class="listing">
<thead>
<tr><th class="name"><a href="?C=N&O=D">Name&nbsp; &#8679;</a></th><th class="lastmodified"><a href="?C=M&O=A">Last Modified</a></th><th class="size"><a href="?C=S&O=A">Size</a></th></tr>
</thead>
<tbody>
<tr><td class="name"><a href="/ReverseServlet/META-INF/">META-INF/&nbsp;</a></td><td class="lastmodified">May 11, 2021, 6:52:48 AM&nbsp;</td><td class="size">4,096 bytes&nbsp;</td></tr>
<tr><td class="name"><a href="/ReverseServlet/ReverseServlet.java">ReverseServlet.java&nbsp;</a></td><td class="lastmodified">May 11, 2021, 6:47:06 AM&nbsp;</td><td class="size">1,551 bytes&nbsp;</td></tr>
</tbody>
</table>
</body></html>

The web.xml is:

<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
      http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
      version="3.1">
      <servlet>
            <servlet-name>ReverseServlet</servlet-name>
        <servlet-class>ReverseServlet</servlet-class>
          </servlet>
          <servlet-mapping>
        <servlet-name>ReverseServlet</servlet-name>
        <url-pattern>/*</url-pattern>
          </servlet-mapping>
    <display-name>ReverseServlet</display-name>
</web-app>

What is it I'm missing?

Edwin
  • 294
  • 2
  • 13
  • should your URL be `http://localhost:8080/ReverseServlet` or `http://localhost:8080/servlet/ReverseServlet`? – Hopey One May 11 '21 at 06:22
  • 1
    This depends on how you have installed your servlet in the webapp`s `web.xml` file. – user207421 May 11 '21 at 07:00
  • Try `/ReverseServlet`. and `java http://localhost:8080/ReverseServlet "Reverse me"`. – user207421 May 13 '21 at 05:56
  • @user207421: Thank I have tried your suggestion and it now response with an HTTP 503 error. – Edwin May 13 '21 at 06:10
  • Which is the value of `HttpServletResponse.SC_SERVICE_UNAVAILABLE`. Something wrong at the Tomcat end. Have a look at the Tomcat logs. – user207421 May 13 '21 at 06:28
  • I was not aware that I need tomcat. I have Jetty 11.0.2. – Edwin May 13 '21 at 06:43
  • You don't. I just assumed it. Have a look in the Jetty logs. – user207421 May 13 '21 at 07:01
  • The first error is: java.lang.NoClassDefFoundError: javax/servlet.http/HttpServlet – Edwin May 13 '21 at 18:48
  • Doesn't look right. Are you sure you quoted that correctly? – user207421 May 14 '21 at 03:27
  • Anyway something wrong with your Jetty installation now. Without that class it can't run at all. – user207421 May 14 '21 at 07:06
  • I have run the demo app of Jetty. That runs fine. So the installation is correct. I assume I have not loaded the right modules for a Servlet. The modules loaded with the --add-module command where: http,server,deploy,servlet,ext. Some other modules came with it. I'm I missing modules? – Edwin May 14 '21 at 08:43
  • I added the javax.servlet.jar to ${jetty_base}/lib/ext. The error now is jakarta.servlet.UnavailableException: Servlet class ReverseServlet is not a is not a jakarta.servlet.Servlet – Edwin May 14 '21 at 09:21
  • You shouldln't add extra JARs for that class. The default servlet is already derived from `javax.servlet.http.HttpServlet`. Maybe you have supplied that JAR file too *many* times? for example, in `WEB-INF\lib`? – user207421 May 14 '21 at 09:38
  • I added the jar only once.The webapps dir contains a war file with: META-INF\MANIFIST.MF, WEB-INF\classes\ ReverseServlet.class and WEB-INF\web.xml – Edwin May 14 '21 at 13:00
  • I change "import javax...." to "import jakarta...." Then I compiled the servlet as javac -cp jetty_home/lib/jetti-jakarta-servlet-api-5.0.2.jar ReverseServlet.java. And put that class file in the webapps/ReverseServlet.war file. Now the server starst without errors. But I'm still not getting the reverse string as a response. – Edwin May 14 '21 at 13:21
  • I assume now the isssu is in the web.xm url-pattern. When I use "/*" the error is 405. When I use "/" the whole page is printed out (as in the question) but not a reversed string. I have tried not url pattern; "/ReverseServlet" and " "ReverseServlet". But so far no luck. – Edwin May 14 '21 at 14:03
  • You haven't tried them why? That's the only suggestion you have so far. – user207421 May 15 '21 at 09:30
  • Sorry the "tried not" in my previous command is a typo . I did try all combinations of url-pattern mentions in the previous commend. But no luck. Now I have changed the module to @Override Protected void doPost(...) { and tried all combination. Again, no luck. The Error is java.io.IOException: Server returned HTTP response code: 405. Why is the GET happening? – Edwin May 15 '21 at 19:09
  • Have you considered looking up HTTP status code 405? – user207421 May 16 '21 at 05:29
  • Yes I did, but it didn't help me much. I have decided to forget about this tutorial for now. @user207421: Thank you for your help. – Edwin May 16 '21 at 06:17

1 Answers1

0

it is solved. I have posted the code on the github and the steps I toke to get it working. https://github.com/viardot/ReadingfromandWritingtoURL

Edwin
  • 294
  • 2
  • 13