Convert servlet code to jsp code [duplicate] - javascript

How do I generate an HTML response in a Java servlet?

You normally forward the request to a JSP for display. JSP is a view technology which provides a template to write plain vanilla HTML/CSS/JS in and provides ability to interact with backend Java code/variables with help of taglibs and EL. You can control the page flow with taglibs like JSTL. You can set any backend data as an attribute in any of the request, session or application scope and use EL (the ${} things) in JSP to access/display them. You can put JSP files in /WEB-INF folder to prevent users from directly accessing them without invoking the preprocessing servlet.
Kickoff example:
#WebServlet("/hello")
public class HelloWorldServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String message = "Hello World";
request.setAttribute("message", message); // This will be available as ${message}
request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
}
}
And /WEB-INF/hello.jsp look like:
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 2370960</title>
</head>
<body>
<p>Message: ${message}</p>
</body>
</html>
When opening http://localhost:8080/contextpath/hello this will show
Message: Hello World
in the browser.
This keeps the Java code free from HTML clutter and greatly improves maintainability. To learn and practice more with servlets, continue with below links.
Our Servlets wiki page
How do servlets work? Instantiation, sessions, shared variables and multithreading
doGet and doPost in Servlets
Calling a servlet from JSP file on page load
How to transfer data from JSP to servlet when submitting HTML form
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
How to use Servlets and Ajax?
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
Also browse the "Frequent" tab of all questions tagged [servlets] to find frequently asked questions.

You need to have a doGet method as:
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Hola</title>");
out.println("</head>");
out.println("<body bgcolor=\"white\">");
out.println("</body>");
out.println("</html>");
}
You can see this link for a simple hello world servlet

Apart of directly writing HTML on the PrintWriter obtained from the response (which is the standard way of outputting HTML from a Servlet), you can also include an HTML fragment contained in an external file by using a RequestDispatcher:
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("HTML from an external file:");
request.getRequestDispatcher("/pathToFile/fragment.html")
.include(request, response);
out.close();
}

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

Passing web browser client input to server Java source code

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

[JS]Return to index page

How can I return to the registration page from the oauth authentication?
I put the url of the app(as &redirect_uri=) but when the user accept the authentication, the script fails:
Error: Access to 'app://6cb90889-d3dd-4ca7-8bab-ea11831b922d/reg.html#access_token=xxxxxxxxxxx' from script denied
It should close the browser and return to the app! Any idea?
redirection of url are taken care by server. Server has to understand the redirect_uri= attribute and need to redirect it.
In case of J2EE.
it will be done as
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
String contextPath= "http://www.java2s.com";
response.sendRedirect(response.encodeRedirectURL(contextPath + "/maps"));
}
Let me know if your trying someting different.
Regards,
Chandra.

Calling servlet doPost method in the javascript

I want to call Servlet doPost() method by using the javascript code but iam getting http 405(HTTP method GET is not supported by this URL) exception.
Here is my javascript code:
url="RedirectServlet?&FD="+FD+"&TD="+TD+"&actionid="+status+"&usercode="+usercode+"&action=reports"+"";
RedirectServlet.java:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
if(action.equals("reports")){
System.out.println("inside reports");
//Getting values from Reports_arb.jsp
String Fromdate=request.getParameter("FD");
String Todate=request.getParameter("TD");
String status=request.getParameter("actionid");
String usercode=request.getParameter("usercode");
//placing given values in a session
request.setAttribute("FD", Fromdate);
request.setAttribute("TD", Todate);
request.setAttribute("actionid", status);
request.setAttribute("usercode", usercode);
//Redirecting to showReport_arb.jsp
//response.sendRedirect("showReport_arb.jsp");
request.getRequestDispatcher("showReport_arb.jsp").include(request, response);
}
}
By seeing you URL, you are sending the data along with the URL. which as servlet get request.
So URL is trying access doGet, but where there is no implemention of doGet in servlet causing problem.
EDIT
use this to make access of your servlet doPost
<form ... method="post">...</form>

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