does Jsp runs under the Servlet code? - java

if we write a code in jsp that will convert to servlet code and get runs. is it true? your suggestions are more thankful.

From http://java.sun.com/developer/technicalArticles/javaserverpages/servlets_jsp/
How Do JSP Pages Work?
A JSP page is basically a web page
with traditional HTML and bits of Java
code. The file extension of a JSP page
is .jsp rather than .html or .htm,
which tells the server that this page
requires special handling that will be
accomplished by a server extension or
a plug-in.
When a JSP page is called, it will be compiled (by the JSP engine) into a
Java servlet. At this point the
servlet is handled by the servlet
engine, just like any other servlet.
The servlet engine then loads the
servlet class (using a class loader)
and executes it to create dynamic HTML
to be sent to the browser, as shown in
Figure 1. The servlet creates any
necessary object, and writes any
object as a string to an output stream
to the browser.
(source: sun.com)
HTH

Related

How can I tell the browser to load a html file with a Java servlet?

The idea is that you can add something to a database, which goes from browser -> java code -> JSP -> java code -> database, and you are then redirected to a page containing the information you sent. The servlets are in place but I cannot redirect to the HTML page from a get request.
I have a servlet to PrintWriter().print() the data in a Json object, but that servlet is called from the javascrit within the HTML page. How can I send the HTML page? Should I parse the HTML page and PrintWriter().print() each line? Is there a more proper way of doing this?
Keep in mind that sending HTML straight from JSP is not an option, and I can't change the structure of the system.
edit: Sorry, I typed that in a rush.
As a preface, the system is similar to StackOverflow, whereby you can submit a 'request' which prompts the community to crowd-source learning material.
Right now, the structure of the system is JS/HTML on the browser side, which communicates with a mySQL DB through an API written in Java. The API goes through JSP which communicates with an inner Java API for accessing the DB. The catch is that I must return Json objects from the API. I know that JSP is essentially useless and I could interface the two APIs without JSP, but this is a first year college project so I don't have the choice.
When you submit something to the database using the url /addrequest (or similar), the system puts the text into the database and then redirects you to /request/idnumber. When you access the /request/* URL, another servlet runs. I want this servlet to tell the browser to open my "request_display.html" page. Then the javascript on that page will call another url to get the Json object through the API, and then it will build the page.
I don't know how to tell the browser to open a html page. Should I just parse the html file and then use response.GetWriter().print() to do send the HTML?
If you are in a Servlet:
response.sendRedirect("pathOf YourHTMLPage");
If you are in a JSP page, try using a form or a "a" element. Like this:
<form action="nameOfYourServlet"></form>
or
Can't really understand what you are looking for but if you want to redirect user to an html page using servlet this can be done using response.sendRedirect("path to html");
It would be nice if you could explain via some code as your English is hard to understand.
response.sendRedirect("redirect.html");
Alternative way
ServletContext sc = getServletContext();
sc.getRequestDispatcher("/redirect.html").forward(request, response);

Am I understanding the working of servlets correctly?

So, yeah, I summed up all what I understood and drew a simple diagram.
If I am not wrong, the servlet is the CGI (Common Gateway Interface) because the servelet is THE ONLY way you can get access to the resources on the server. So, in short, it is the COMMON GATEWAY.
The CONTAINER, like Apache Tomcat, is responsible for capturing the request sent by the user and sending it to the servlet.
What the user perceives is a dynamic webpage called web app.
This is what I learnt so far.
Have I learnt it correctly ?
You are almost right. Here are typical workflows you can follow when working with plain servlets:
Servlet renders page
Servlet container find servlet that matches request URL
doGet() or doPost() is called depending on HTTP method requested
Servlet does some processing
Response (HTML, XML, JSON, image...) is generated directly in the servlet and sent to the client using getOutputStream() or getWriter()
PrintWriter out = response.getWriter();
out.println("Hello World");
JSP handles request
Servlet container finds JSP matching request. You must understand that underneath each JSP is translated to some internal servlet
This JSP is interpreted. Raw text is sent directly, Java code in scriptlets is executed
JSP ends, request is done
Servlet forwards to JSP
Same as 1-3 in first scenario
Servlet chooses JSP file and forwards to that JSP
JSP file is then evaluated, it has access to some context (request attributes, session) that was passed by servlet
RequestDispatcher dispatcher = getServletContext()
.getRequestDispatcher("foo.jsp");
dispatcher.forward(request, response);
The last scenario is considered the best one as it does not mix business logic (servlet) and presentation (JSP).
A Servlet processes a request and generates a response.
A JSP gets compiled into a servlet, so JSPs are a subset of servlets.
It is not a Servlet who looks for the correct JSP, this is the container's job.

is it safe to get the java.sql.connection to jsp page form servlet

I have created a servlet called dbConnect(return type Connection). In which i wrote the code to connect to the database. Now I am calling the dbConnect(<%Connection con=dbConnect.getConnection()%>) into the JSP file. Since JSP file will be in the client side is there any possibility that an hacker can hack the connection??
The larger question is whether or not this is a good thing to do.
My preference would be no scriptlet code in JSPs whatsoever. If you must write JSPs, I'd recommend using JSTL tags and a servlet to handle requests. Let a servlet sit between the JSP and the database and intercede on its behalf with the database. You can do authentication, input validation, binding, and routing in the servlet and let the JSP do what it was meant to do: display only.
If this JSP is intended for anything other than a single toy application, I'd recommend that you dig into model-2 web MVC using JSPs and servlets.
JSP files aren't on the client side. A JSP is compiled into a servlet so anything you feel safe doing in a servlet is just as safe in a JSP page. That code snippet inside of <% %> is turned into plain old java code. Your HTML is turned into a string that's spit out from the servlet back to the client.
So yes, it's fine.

Java embedded with html

Is it possible to embed html with java
test.html
<input id="buttonId" type="button" class="button-click"
value="" onClick="checkSucess(2)" onload="counts(count)">
test.js
checkSucess = function(firstVal) {
// Jquery Ajax with url,params and response
doPost('test.java',
'first=' + firstVal,
function(response) {
});
test.java
Here get the 'first' value from ajax request, and further processing.
I believe you're looking for JavaServer Pages (.jsp), a starting point for implementing server-side logic using Java. (You can GET/POST to a jsp.)
Reference
JSP + Ajax Example
JavaServer Pages Technology
JSP Tutorial
Well, Java on the server side doesn't work quite like PHP. i.e. you can't simply drop your java files in your htdocs directory and trigger it by filename directly. Firstly you'll need an app server like tomcat or jetty (instead of just a webserver like apache httpd). Secondly, you'll need to create a Servlet (simplest case) and write your java code there and trigger it using the server request url. Google "servlets" and you should be able to pick it from there..
No, you can't do like that, you have to use AJAX request to interact with java from your html or javascript. For that you have to use servlet and pass the servlet URL to doPost function.
doPost('url to servlet',
'first=' + firstVal,
function(response) {
});
Since this is your first java project, you should do some reading to come up to speed with java. Here are some good tutorials:
Core Servlets, Intermediate Servlets
Apache Tomcat 6 - Apache is a nice tool for learning servlets; it is easy to install and run.
Core Servlets; Advanced Servlets - This may be more than you need.
Applets are Java, and the only (usual) way for Java in the browser.
You can communicate with Applets from Javascript/JQuery code. Applets have ending .class (.java is source code, you can't communicate with it).
In the case you want to communicate with serverside Java, you need servlets there. Then send requests to the url of the servlets.
No. Besides using Java Applets - which are actually just plugins - there is no way to embed Java into HTML.
That being said, It is possible to generate HTML using Java Server Pages.
It is also possible to use an HTML page in conjunction with JavaScript to interact with Java via subsequent HTTP Requests made using AJAX. These requests are initiated on the client browser, and received and fulfilled by a server capable of executing Java Server Pages (JPS).
Example:
An HTML page is loadad with some JavaScript that requests some url upon completion of DOM loading.
The request is received by some server which then responds to the request.
The client browser receives the response and provides it to JavaScript to be dealt with.
JavaScript reads the response, and uses it in some way (like "refreshing" some information on the page).

How to call a function written in JSP from a html page?

How to call a function written in a JSP from a HTML page? I have declared a function to load an image from server in JSP page. Now I want to show that image in another html page by calling that JSP function in HTML page.
i have declared a function to load a image from server in jsp page. now i want to show that image another html page by calling that function in html page.
That's not how it works. Webbrowser sends HTTP request to webserver. Webserver executes some Java/JSP/Servlet code based on the HTTP request (URL, parameters, pathinfo, etc). Java/JSP/Servlet code produces a bunch of HTML code (which can contain CSS/JS code as well). Webserver sends HTML code back to webbrowser as HTTP response. Webbrowser displays HTML. If you rightclick page in webbrowser and choose View Source, then you should not see any line of Java/JSP/Servlet code.
You just need to write your Java/JSP/Servlet code so that it produces exactly that HTML you want. Displaying images in HTML is to be done by <img> tag whose src attribute should point to the URL of the image.
<img src="foo.png" />
Just put that as-is in the JSP. With the above example, put the image file in same folder as the JSP as well.
If the images are however to be retrieved from an external resource as for example a database, then you need to create a Servlet which obtains an InputStream of the image from the external resource based on the parameters/pathinfo provided by the HTTP request and writes it to the OutputStream of the HTTP response along a set of correct response headers (content type, length, etc). Finally let the URL in the src attribute of the HTML <img> element point to the servlet instead.
<img src="imageservlet/foo.png" />
You can find a more detailed example of the servlet in this answer.
Via an HTTP Request - i.e. submitting the page to the web container where the JSP executes. This is a very normal pattern.

Categories

Resources