Passing web browser client input to server Java source code - javascript

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);
}
}

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

Related

How to redirect/forward to a new html page with variable content?

The problem
I'm creating a web app where the user is served a login page, login.html, and has to enter his credentials. The servlet class grabs the information using ajax in the form of a POST request, generated by the user clicking the submit button. After checking the correctness of the credentials, i wish to serve the user with a new HTML page, a welcome page, where the response of the servlet is transferred. The problem i'm facing is how to transfer the response from a starting LoginServlet class to a WelcomeServlet all the meanwhile, the client is projecting a new HTML page, welcome.html, and catch the response of the WelcomeServlet in an ajax call made by a js script in the new HTML page.
Background
I'm just starting to delve into the development of web-apps, so if i'm mistaken in any part of my logic and understanding of the whole frontend-to-backend process, please say so. I'm aware of the redirect() and forward() functions but i'm not understanding the way these functions can be used in conjunction, or the complete difference, with the client side of things.
I have the following servlets:
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher dispatcher = request.getRequestDispatcher("welcomeservlet");
dispatcher.forward(request, response);
}
public class WelcomeServlet extends HttpServlet {
private static final long serialVersionUID = 2L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//parse request and send response
}
In the login.html file i've included the following js code:
function loadNewPage() {
// retrieve data and store them in a js Object
$.ajax({
url: "loginservlet",
type: 'POST',
dataType: 'json',
data: JSON.stringify(jsObject),
contentType: 'application/json',
mimeType: 'application/json',
success: function (data) {
window.location.href = "welcome.html";
},
error: function (data, status, er) {
alert("error: " + data.text + " status: " + status + " er:" + er);
}
});
}
I'm not including another js script which would be placed inside the welcome.html purposely since i don't know what would i have to add in there to catch the response of the new servlet. A possible reason why this whole thing isn't working could be that i'm missing something in the functionality of the forward() function but couldn't find an example online that does the exact thing that i want to do.
(Image credit w3schools)
The fact is you can't jump to another servlet. Ajax response will be sent back to the same webpage from which request was generated.
For your requirement what you can do is, Check whether login is success or not in LoginServlet. If yes create a token, save it in database along with the username and send the same token as response to the client.
Now in client save the token in localStorage and redirect to welcome.html.
On welcome.html page loading check whether token saved in localStorage exists or not. If yes, check whether it's valid or not. If valid the call WelcomeServlet . Else display login screen.
It's called token based authentication. You can read more about it here

Correct way of making POST request with JSON in SPRING MVC?

I am fairly new to spring and want to the correct way of making post request. I have a list of json object that I want to post to my server
for example
var list = [{name:"abc",age:23},{name:"xyz",age:22},{name:"xcx",age:33}]
I am making a post request in google closure using xhr to my server in this fashion
model.xhrPost(id,url,"list="+JSON.stringify(this.list),callback);
This is what my controller looks like
#RequestMapping(value={"/getInput"}, method = RequestMethod.POST)
#ResponseBody
public String logClientError(ModelMap model, HttpServletRequest request, HttpServletResponse response) throws Exception{
JSONObject result = new JSONObject();
try{
String errorObj = request.getParameter("list");
JSONArray errors = new JSONArray(errorObj);
some more code here which loops through the list...
result.put("isSuccess", true);
return result.toString();
}catch(JSONException e){
result.put("isSuccess", false);
return result.toString();
}
}
So in short I am making a post request by passing querystring parameter. Is this the correct way or should the content be posted in the body? If I post in the body what changes do I have to make ?
This is definitely not how you should post the data to REST endpoint. Going this way you can use GET instead of POST and it will work as well. However POST should be definitely used to create new resource and the content should be carried in message body not as a query param.
On the backend side you can catch and parse the content yourself or create a class (see below) that will be filled with data from body.
DTO:
class Person {
String name
Integer age
}
class PersonList {
List<Person> persons
}
Endpoint:
public String logClientError(#RequestBody PersonList list, HttpServletRequest request, HttpServletResponse response) throws Exception
Body:
{
"persons": [{name:"abc",age:23},{name:"xyz",age:22},{name:"xcx",age:33}]
}
#ResponseBody can be used in the same manner for responses.

javascript - Handling redirect from http response

I am trying to build a html page that when I enter it, it will redirect me to another page, depending on an attribute in the session.
If there is an attribute named "username" in the session, it will not redirect me, and otherwise it will.
In order to do so, I wrote a javascript function that calles a java servlet that checks whether or not the attribute exists.
<script type="text/javascript">
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4) {
var data = req.responseText;
}
document.write(req.readyState);
}
req.open('POST','sessionCheck',true);
req.send(null);
</script>
The code in the servlet is:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession hs = request.getSession();
String username = (String) hs.getAttribute("username");
if (username == null)
response.sendRedirect("/login.html");
}
I know that the resonse did send the redirect but the webpage was not redirected.
*Note: I am using Eclipse Java EE for Web Developers.
Thanks!
Javascript AJAX requests follow redirects. It is likely that your javascript code ended up requesting the page that you wished to redirect the browser to.
Try returning the page to redirect to as your response and then getting the browser to navigate to that page.
You can see that the XMLHttpRequest standard states that redirects will be followed:
HEADERS_RECEIVED (numeric value 2)
All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available.

How to get response form servlet using XMLHttpRequest

I have a jetty server running which responds to get requests. If I make the request using a browser:
localhost:8080/sp or 127.0.0.1:8080/sp
I get the correct data back.
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
out.println("{foobar: true"});
response.flushBuffer();
out.flush();
out.close();
}
but when I try to access the same url using JS the response body is empty.
I've tried serving the webpage using both the OS X webserver(port 80) and python SimpleHTTPServer (port 3000).
In both cases the response is empty.
<h1>Single Test Page</h1>
<script>
var httpReq = null;
var url = "http://127.0.0.1:8080/sp";
window.onload = function(){
var myRequest = new XMLHttpRequest();
myRequest.open('get', url);
myRequest.onreadystatechange = function(){
if ((myRequest.readyState == 4) || (myRequest.status == 200)){
alert(myRequest.responseText);
}
}
myRequest.send(null);
}
</script>
Could it be an issue with xss attack prevention?
How can I change my setup to use JS to talk to my servlet?
Is there any other way I can make the HTTP get request from JS?
I even added an entry into my /etc/hosts file:
127.0.0.1 foo.com
and changed the JS url to no avail.
Yes, the problem is that it's a cross domain request.
2 possible solutions :
use JSONP
set CORS headers so that the browser knows it may embed your servlet answer
Both are easy but the second one has the advantage that you just have to set the headers in the servlet code. For example :
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Request-Method", "GET");
Another thing : be careful to open your html file in http:// and not file://.

How to perform Ajax call from Javascript to JSP?

I have a JavaScript from which I am making an Ajax Call to a JSP. Both JavaScript and JSP are deployed in the same web server. From JSP I am forwarding the request to one of the service (servlet) available in other web server using HttpURLConnection. I got the response in JSP, but now I need to pass the response back to JavaScript which made an Ajax Call. How I can do it?
My ultimate goal is to make an Ajax request from JavaScript to a JSP and from that JSP to one of the services and return the response back to JavaScript.
JSP is the wrong tool for the job. The output would be corrupted with template text. Replace it by a Servlet. You just need to stream URLConnection#getInputStream() to HttpServletResponse#getOutputStream() the usual Java IO way.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
URLConnection connection = new URL("http://other.service.com").openConnection();
// Set necessary connection headers, parameters, etc here.
InputStream input = connection.getInputStream();
OutputStream output = response.getOutputStream();
// Set necessary response headers (content type, character encoding, etc) here.
byte[] buffer = new byte[10240];
for (int length = 0; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
}
That's all. Map this servlet in web.xml on a certain url-pattern and have your ajax stuff call that servlet URL instead.

Categories

Resources