1

I am developing a web application in Java that takes a string containing a website URL, parses the website HTML to gather information, then uses that information to query a postgresql database. This is already written using Java, HTML, JS and CSS.

In my HTML I have a text input box where the user can paste a URL and submit it using a button. What I would like to do, is get this URL as the String I mentioned above in my Java code, versus hard coding it myself. Eventually, after parsing that URL HTML file and running whatever queries I need on my database, I will return the query results back to the browser for the user to see.

I understand that JavaScript runs in the browser while my Java source code is server side at different times. I've gathered that a possible solution is to submit a HTTPServletRequest in my Java source code that communicates with my JavaScript; however I am unsure of the right steps to accomplish this. XmlHTTPRequest is something else I've seen being used.

Edit - After further reading I am deciding between programming a Java servlet, or a JSP to handle this. I am leaning towards a servlet as I am more familiar with Java than HTML, and will be using more logic (HTML parsing, RDBMS querying using jdbc, returning data).

Does this seem to be the correct decision?

I hope I worded this clearly and that this is a valid question! Thank you!

UPDATE/EDIT

Here is my code I've done so far after thinking about Mois44's answer. I am unsure what to put for the URL in my xmlHttp.send() request. In the browser, there is a text box, and submit button for the user as I said.

Error: url.html:91 POST http://localhost:8080/myapplication/GetURL?url=http://mywebsite.com/category/123986/webpage/ 404 (Not Found)

This is the project structure for these files:

src/main/
|
|----java/
|   |
|   |----path/to/java/servlet/myServlet.java
|
|----webapp/
    |
    |----META-INF/
    |   |----web.xml
    |
    |----pages/
        |----url.html
    |
    index.html

web.xml:

<servlet>
   <servlet-name>GetURL</servlet-name>
   <servlet-class>path.to.java.servlet.myServlet</servlet-class>

   <init-param>
    <param-name>url</param-name>
    <param-value>www.testurl.com</param-value>  // don't I set this in my url.html from user?
  </init-param>

</servlet>

<servlet-mapping>
  <servlet-name>myServlet</servlet-name>
  <url-pattern>/myServlet/*</url-pattern> // not sure about this...
</servlet-mapping>

url.html:

<div class="url-input">
    <input type="text" id="txtUrl" class="text-box" value="Paste recipe website URL here" align="middle">
    <button onclick="urlRequest()" id="myid" value="myvalue">Go!</button>
        <script>
            function getURL(xmlHttp) {
                document.getElementById("myid").value = xmlHttp.responseText;
                return document.getElementById("txtUrl").value
            }
        </script>
        <script>
            function urlRequest() {
                var xmlHttp = new XMLHttpRequest();
                var url = getURL(xmlHttp);
                xmlHttp.open('POST', 'http://localhost:8080/myapplication/GetURL?url='+url, true);

                xmlHttp.onreadystatechange = function () {
                    if (xmlHttp.readyState = 4 && xmlHttp.status == 200) {
                        alert(xmlHttp.responseText);
                    }
                };
                xmlHttp.send(url);
            }
        </script>
</div>

myServlet.java:

public class Servlet extends HttpServlet {

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

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

    protected void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

        String p = request.getParameter("url");
        System.out.println("test");
        System.out.println(p);
    }
}

1 Answer 1

1

If you want to use the tools you already know, use JSF.

You also could create a simple HTTP Endpoint in your Java Server and use JavaScript to communicate with it. (You send the String as http payload to the Server with an XmlHTTPRequest and then receive the response in XML, JSON or whatever format you like (raw string?). JSON would be a good choice, because JavaScript supports it very well. For JSON in Java i recommend the Jackson Project)

Edit: JavaScript part example:

// get user input from input field..
var userInput = document.getElementById("#my-input").value;

xmlHttp = new XMLHttpRequest();
//         HTTP Method, URL, async
xmlHttp.open('POST', '/myJavaEndPoint', true);
// create onreadystatechange callback function,
// it gets called everytime the readyState changes..
xmlHttp.onreadystatechange = function () {
    // readyState 4 means "DONE" - request is complete, responseText now contains the full response..
    if (xmlHttp.readyState == 4) {
        alert(xmlHttp.responseText); // Show the result to the user. 
    }
};
xmlHttp.send(userInput); // Start Request, send the user input as post-payload
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you Mois! I actually need to learn more JavaScript, so I think I will take the latter option and create a RESTful HTTP endpoint in my Java Servlet as you mentioned. I'll use XmlHTTPRequest and can hopefully return it as a raw string in Java since it is only one attribute. I assume I could make my queries, construct the results in JSON format using the Jackson Project, then send that as a response back to my JavaScript for user-visible output on the browser side? Does this seem correct? Thanks again!
Yes, thats correct! You don't even need to use JSON format and Jackson for the response. Just send the attribute back as a String! I added an example for the client-side javascript code.
Could you possibly help with what my url should be for the .open() call? I have edited my original post with my current code. I am getting a 404 error in inspector when I use my submit button. Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.