Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 4 of 4

Thread: Request page not found error

  1. #1
    Junior Member
    Join Date
    Apr 2020
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Request page not found error

    package webserver;

    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.util.concurrent.*;

    public class WebServer {

    static ServerSocket requestListener;
    static Socket requestHandler;
    static Scanner requestReader;
    static String HTTPMessage;

    static String requestedFile;
    public static int HTTP_PORT = 12346;

    public static void main(String[] args) {

    try{
    requestListener = new ServerSocket(HTTP_PORT);

    System.out.println("Waiting For IE to request a page");
    requestHandler = requestListener.accept();
    System.out.println("Page Requested: Request Header");

    requestReader = new Scanner(new InputStreamReader(requestHandler.getInputStream()) );

    int lineCount = 0;
    do{
    lineCount++; //This will be used later
    HTTPMessage = requestReader.nextLine();
    System.out.println(HTTPMessage);

    HTTPMessage = requestReader.next();
    if(lineCount==1){
    requestedFile="WebRoot\\" + HTTPMessage.substring(5,HTTPMessage.indexOf("HTTP/1.1")-1);
    requestedFile = requestedFile.trim();

    pageReader = new Scanner(new File(requestedFile));
    pageWriter = new DataOutputStream(requestHandler.getOutputStream()) ;
    while(pageReader.hasNext()){
    String s = pageReader.nextLine();
    pageWriter.writeBytes(s);

    pageReader.close();
    pageWriter.close();
    requestHandler.close();
    }
    }
    }while(HTTPMessage.length() != 0);
    }catch(Exception e){
    System.out.println(e.toString());
    System.out.println("\n");
    e.printStackTrace();
    }

    }

    }

    --- Update ---

    Kindly help look at the reason why this code is not running.

    The browser was showing waiting for the request page, but would eventually not find it

    Thanks

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Request page not found error

    Can you explain what the posted code is supposed to do when it is executed?
    What steps must a user take to test the program?
    What is supposed to happen?

    Please edit your post and wrap your code with code tags:

    [code]
    **YOUR CODE GOES HERE**
    [/code]

    to get highlighting and preserve formatting.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Apr 2020
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Request page not found error

    Thanks

    package webserver;
     
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.util.concurrent.*;
     
    public class WebServer {
     
        static ServerSocket requestListener;
        static Socket requestHandler;
        static Scanner requestReader;
        static String HTTPMessage;
     
        static String requestedFile;
        public static int HTTP_PORT = 12346;
     
        public static void main(String[] args) {
     
            try{
                requestListener = new ServerSocket(HTTP_PORT);
     
                System.out.println("Waiting For IE to request a page");
                requestHandler = requestListener.accept();
                System.out.println("Page Requested: Request Header");
     
                requestReader = new Scanner(new InputStreamReader(requestHandler.getInputStream()));
     
                int lineCount = 0;
                do{
                    lineCount++; //This will be used later
                    HTTPMessage = requestReader.nextLine();
                    System.out.println(HTTPMessage);
     
                    HTTPMessage = requestReader.next();
                    if(lineCount==1){
                        requestedFile="WebRoot\\" + HTTPMessage.substring(5,HTTPMessage.indexOf("HTTP/1.1")-1);
                        requestedFile = requestedFile.trim();
     
                        pageReader = new Scanner(new File(requestedFile));
                        pageWriter = new DataOutputStream(requestHandler.getOutputStream());
                        while(pageReader.hasNext()){
                            String s = pageReader.nextLine();
                            pageWriter.writeBytes(s);
     
                            pageReader.close();
                            pageWriter.close();
                            requestHandler.close();
                        }
                    }
                }while(HTTPMessage.length() != 0);
            }catch(Exception e){
                System.out.println(e.toString());
                System.out.println("\n");
                e.printStackTrace();
            }
     
        }
     
    }



    This is the instruction

    This is, in part, a research project and requires some additional research using the Java API, your textbook, and HTML references (See www.w3schools.com) may be required.

    Getting Started: Reading the HTTP Request from IE
    All communication on the web is based on the HTTP protocol. When a browser requests a page it sends an HTTP request. An HTTP request contains the name of the Web page that the browser wants to display, and information about the browser and its capabilities. This information is stored in the HTTP headers. Communication is similar to your chat program. The only difference is the objects used for input and output.

    Start by creating a program that outputs the HTTP request to the console so we can see what it looks like. This information will allow us to locate the requested file and send it back.

    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.util.concurrent.*;

    public class WebServer{

    static ServerSocket requestListener;
    static Socket requestHandler;
    static Scanner requestReader;
    static String HTTPMessage;

    static String requestedFile;
    public static int HTTP_PORT = 12346;


    public static void main(String[] args){


    try{

    requestListener = new ServerSocket(HTTP_PORT);

    System.out.println("Waiting For IE to request a page:");
    requestHandler = requestListener.accept();
    System.out.println("Page Requested: Request Header:");



    requestReader = new Scanner(
    new InputStreamReader(
    requestHandler.getInputStream()));

    int lineCount=0;
    do{

    lineCount++; //This will be used later
    HTTPMessage = requestReader.nextLine();
    System.out.println(HTTPMessage);

    }while(HTTPMessage.length()!=0);
    }
    catch(Exception e){

    System.out.println(e.toString());
    System.out.println("\n");
    e.printStackTrace();
    }
    }
    }


    If you run this program, then launch IE and type the following URL into the browser location bar:

    http://localhost:12346/testpage.htm

    Your program will display the following message from the browser as output:



    The line we will be most interested in is the first one, because it contains the requested file name:

    GET /testpage.htm HTTP/1.1



    Before we can write the code that will respond a page you will have to create two Web pages. There are many programs that will make Web pages for us, but let’s use notepad so we can learn HTML, we will need to learn a bit about HTML to create our Web based data service.

    You will create the following pages in a “WebRoot” subfolder of your project:

    Testpage.htm
    Default.htm

    Here’s the HTML code for the test page:



    And here’s what it looks like in the browser:




    Here’s how it works:

    HTML stands for Hyper Text Markup Language. It consists of tags enclosed in angle brackets <>. Tags “Markup” the text they contain. This means they provide formatting instructions to the browser. For example, this code:



    Told the browser to place the text in the title bar:





    Create a similar page for default.htm that looks like this:





    Getting Started: Sending the Web page to IE

    This is a little trickier. It involves the following steps:

    1. Get the file name from the HTTP request
    2. Read the file
    3. Send the file


    Step 1.

    When we read the first line of the HTTP request, we extract the requested file from that line. To do this, place this code in front of the output line:

    HTTPMessage = requestReader.next();
    if (lineCount==1){
    requestedFile="WebRoot\\" +
    HTTPMessage.substring(5, HTTPMessage.indexOf("HTTP/1.1")-1);
    }

    Here we are building a string to hold the path to the requested file.

    “WebRoot\” + “testpage.htm”

    GET /testpage.htm HTTP/1.1


    The first “\” is an escape sequence. By putting 2 in we are saying we mean \ and are not beginning a special command, like \n. We add to “WebRoot\” the substring of the above that starts at position 5 (the “t”, and ends 1 position before the beginning of “HTTP/1.1”, in this case position 17 (the space after the file name)


    To be safe, when the string building is done it can’t hurt to trim any trailing or leading spaces:

    requestedFile = requestedFile.trim();

    Step 2.

    You have read a file in Java before. This code creates a Scanner that reads a file and loops through the file and outputs it to the console.

    pageReader = new Scanner( new File(requestedFile));
    while(pageReader.hasNext()){
    String s=pageReader.nextLine();
    System.out.println(s);
    }

    If you run it you should see your Web page printed to the console as text.
    Step 3.

    Now you want to change the output line so that it prints to the IE. You can’t use an ObjectOutputStream, because IE doesn’t have an ObjectInputStream on the other end. If you do you’ll get messy output like this:




    This is caused by the serialization data that IE didn’t expect. It turns out IE is expecting a stream of Bytes that it will parse character by character. You will need to use a DataOutputStream object, and its writeBytes method to do this.

    Like this:

    pageReader = new Scanner( new File(requestedFile));
    pageWriter = new DataOutputStream( requestHandler.getOutputStream());
    while(pageReader.hasNext()){
    String s=pageReader.nextLine();
    pageWriter.writeBytes(s);
    }

    //Tells the Browser we’re done sending
    pageReader.close();
    pageWriter.close();
    requestHandler.close();


    You now have a working “1-shot” Web server.



    Enhancement 1: Error Pages and Default Page

    If a user enters either of these:

    1. http://localhost:12346/
    2. http://localhost:12346/subdir or http://localhost:12346/subdir/

    Your WebServer should display WebRoot\Default.htm in the first case, and WebRoot\subdir\Default.htm in the second case.

    If there is no occurrence of “.htm” in the requested file name you may assume either:

    1. They a requesting a file other than a web page which you are not responsible for handling (for now).
    2. They have requested the default page in a sub folder

    In either case, append default.htm to the file name.

    Use a small try-catch block around the code that opens the requested file. If the server code throws a FileNotFoundException catch it and set the requested file to WebRoot\Util\Error404.htm.

    A 404 is the HTTP code for file not found.

    Create a Util sub folder and add this page to it:



    If the words “HTTP 404” appear anywhere on your page, IE will override it and display its own 404 error page.




    Enhancement 2: Serving Multiple Requests Simultaneously

    In this enhancement you will split the project into two classes. On will be WebServer, and it will manage the incoming connections. The other will be Responder. Responders will be created by WebServer and run in their own thread. Here are the class diagrams:


    WebServer
    - requestListener : ServerSocket
    - Static HTTP_PORT : int
    - responses : ExecutorService
    + WebServer() //Create an instance of RequestListener and Creates an instance
    //of ExecutorService, threadpool size 100

    + start() // Enters an infinite while loop and accepts connections
    // Each connection is used to create a new responder, like this:
    Responder r=new Responder(requestListener.accept());
    // “r” is then passed to responses to execute

    + main() //Creates and instance of WebServer and starts it.





    Responder implements Runnable
    - requestHandler : Socket
    - requestReader : Scanner
    - pageReader : Scanner
    - pageWriter : DataOutputStream
    - HTTPMessage : String
    - requestedURL : String
    - requestedFile : String

    + Responder(requestHandler Socket)
    + run() //Now handles all of the response code from the one shot server

    The flow of logic of the server is now as follows:

    Open a port
    Accept connections on that port
    As connections come in, create a “Runnable” to execute them
    Pass the runnable to an execute method of an ExecutorService

    So all requests are serviced in their own thread.
    Enhancement 3: Adding a Database Service

    Step 1. Move the Web Page into WebRoot
    The following Web Page will be used to execute the Service:





    The page has these features:

    The form is on pccommon. Clicking the “Run Service” button with the above test data would produce this line in your HTTP header:


    GET WebRoot\doSERVICE?Criteria=TEST&Field=FirstName&su bmit=Run+Service HTTP/1.1

    This line contains everything we need to build a SQL Query from your Oracle database. When we trim it down to a file request we have this:

    WebRoot\doSERVICE?Criteria=TEST&Field=FirstName&su bmit=Run+Service

    Step 2: Create the Service Classes
    Let’s create a service to handle this. We’re going to base it on an abstract service class so that we can swap in any new service we want so long as it has a doWork() method. In the code provided you will have to address the visibility issue with responseWriter in the base class, but it will basically look like this:

    public abstract class Service{

    private DataOutputStream responseWriter;

    public Service( DataOutputStream responseWriter){
    this.responseWriter=responseWriter;
    }

    public abstract void doWork();
    }

    And

    class SQLSelectService extends Service{

    private String requestString;
    private SQLCommand;

    //This construcotr will be called from the run method of a
    //Responder. It passes the HTTP request info, and the output
    //object to the service.
    public SQLSelectService(DataOutputStream responseWriter, String
    requestString){

    super(responseWriter);
    this.requestString=requestString;
    }

    public void setSQLCommand(){

    //This method extracts the criteria and field name from the
    //request string (using indexOf)and builds a valid SQL query.
    //something like:

    //”SELECT * FROM EMPLOYEE WHERE “+fieldName+” = ‘“ criteria +”’”
    }

    public void doWork(){
    try{

    //calls setSQLCommand
    //This method connects to an Oracle Database

    //Executes the query to get a resultset

    //Set up the Web page:

    responseWriter.writeBytes("<html><head><title>test ”);
    responseWriter.writeBytes(“</title></head><body>”);

    //Loops through the resultset writing it to IE using the
    //responseWriter. You will have to format the Strings with
    //a little HTML.

    } //Then catch and close class.



    Step 3: Pass service requests to an instance of the SQLSelectService

    The basic idea here is if a request string contains the line “doService” you’re not going to send a page, instead you will create a SQLSelectService object and pass it the requestedFile string and the pageWriter reference.

    It goes something like this:

    pageWriter = new DataOutputStream( requestHandler.getOutputStream());
    pageWriter.flush();

    if(requestedFile.indexOf("doSERVICE")>-1){

    Service s=new SQLSelectService(pageWriter,requestedFile);
    s.doWork();


    }
    else{

    //continue on with code to send a page.




    Enhancement 4. Logging.


    Write all requests to a text file. Include the page that was requested and when. Also, write all page now found errors to the file also.

    Hint: This will get the date. It uses java.text.*;

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calenda r.getInstance().getTime());
    System.out.println(timeStamp );


    Enhancement 5. GUI Server.

    Create a GUI server that when runs, uses a JOptionPane to prompt the user for a port number. It runs the server on that port and displays a GUI console with the following functionality:
    • Stop button to stop the server
    • Start button to start accepting connections
    • JTextArea or similar control displaying the page requests as they come in. (This is a live display of the logging)



    You’re dun!

    --- Update ---

    The code did not run on the browser. But could not figure out what was wrong. the question was pasted below. Meanwhile I have like 3 hours left to submit. Please I will appreciate your help. thanks

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Request page not found error

    What messages does the server receive from the browser? Add some more print statements to print out ALL of the received messages.
    The current code only prints one.
    Copy the contents of the console when the program is executed and paste it here so we can see what happens when the code is executed.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Replies: 4
    Last Post: March 27th, 2014, 09:57 AM
  2. Scanning and displaying every word from a website source code Java
    By Lilac in forum What's Wrong With My Code?
    Replies: 12
    Last Post: February 19th, 2014, 02:10 PM
  3. Replies: 0
    Last Post: May 23rd, 2013, 04:35 PM
  4. Help on developing code for autoform fill in website
    By hari061204 in forum What's Wrong With My Code?
    Replies: 6
    Last Post: March 6th, 2012, 05:49 PM
  5. Getting Value from Website source code.
    By Blackbird94 in forum Java Theory & Questions
    Replies: 2
    Last Post: August 26th, 2011, 07:16 AM