Am I understanding the working of servlets correctly? - java

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.

Related

How to handle no request on servlet

I have a .jsp page where I've coded a form that submits some input to a servlet. The servlet manipulates the input and then sends a message to the same page. This is working fine, however, when I get back to the .jsp page, or in other words, when I get the answer from the servlet, the url that is visible in the browser contains the path to the servlet (e.g http:/index.jsp/servlet_name ), so, when I refresh the page, the browser redirects to the servlet and it get stuck because there was no get/post submission, so doGet() or doPost() are never active.. Is it possible to handle no get/post request in the servlet ? If not, how should I handle this problem ?
Ps: I'm using jquery mobile to build the pages (in the event of a possible solution with this framework)
I think you got it wrong. Even when you refresh, normally either doGet() / doPost() is activated. Your browser often asks you first if you're refreshing post requests.
What could be happening is your servlet is serving another request without form data, hence you get the impression it's not doing anything

applet->servlet->a record file(on the server) : how do i do this?

To make a poll form using an applet, i wanted to know how can my applet communicate with a servlet . That servlet is meant to write the result to the text file on the server. I have no idea how can i do this.
You could use java.net.URLConnection for this.
Assuming that your servlet is mapped on an URL pattern of /myservlet and your applet is been served from the context root, then this should do:
InputStream servletResponse = new URL(getCodeBase(), "myservlet").openStream();
// ...
That's all. The getCodeBase() is inherited from Applet class and dynamically returns the applet's code base URL (from where the applet was been downloaded). The servletResponse will contain whatever you wrote to response.getOutputStream() or response.getWriter() in the servlet. For example just an "ok" string or an easily parseable format like XML or JSON. You could pass request parameters as a query string in the GET request URL, or in the POST request body.
See also:
Using java.net.URLConnection to fire and handle HTTP requests
https://stackoverflow.com/questions/9361399/how-to-send-list-of-objects-from-servlet-to-applet
The applet and the servlet is separate. There is no easy way you can use magic to make this easier.
A servlet is a snippet inside a web server which gets executed when a HTTP request is being made to the correct URL on the web server. Hence you need to make a HTTP request to the correct URL on the web server where your servlet is running.
This is done in the same way you do any other HTTP request from an applet, which is done in the same way that you do a HTTP request from a self-standing application.
Well you have several options for the applet/servlet communication....
http requests. (This may be the easiest). For this you can use Apache HTTP Components
Remote Method Invocation RMI. This may be more complicated than http requests but it depends on what you want to achieve.
Sockets. (I think http requests is flexible enough for your use case but just in case)
javascript. You can call a javascript function from your applet and let the javascript function submit the information to the servlet through ajax, websockets, etc.
Of course there are many other options but these are some ideas and remember that you may need to sign your applet.
If your question is about how to write to a file there are many tutorials. Here is a good one

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.

Calling Servlet Post from another Servlet

I need to call a servlets POST method from another servlet and pass a blob in the servlets parameters. Is this posible, if so how can it be done. PS: I cant use Apache HttpClient
You need to create and send a HTTP request yourself. You cannot make use of forward/redirect/include because you want to change the method from GET to POST and you want to send a multipart/form-data request.
As HttpClient (and other 3rd party library?) is apparently not an option, your best bet is to use the standard Java SE API provided java.net.URLConnection. Long story short: Using java.net.URLConnection to fire and handle HTTP requests At the bottom you can find a multipart/form-data example.
Please note that this problem is not specific to servlets. In other words, you must be able to execute this code in a plain vanilla Java application with a main() method. This allows for easier testing and finetuning. Once you get it to work, just let the servlet execute the same piece of code.
Unrelated to the problem, I have the impression that there's a major design failure somewhere, certainly if the both servlets runs in the same webapplication context. The other servlet where you want to send the POST request to is apparently too tight coupled and should be refactored.
You can get a dispatcher to another servlet in your application and forward it or include it as #Ryan suggests. The code should be something like this inside your first servlet:
ServletContext context = this.getServletContext();
RequestDispatcher dispatcher = context.getRequestDispatcher("/otherurltoservlet");
// change your request and response accordingly
dispatcher.forward(request, response);
Do you mean call from your application to another web service? If so, then something like HttpClient is what you want. If you mean you want to programmatically invoke another servlet in your app, then you're looking to either forward to it or include it.

does Jsp runs under the Servlet code?

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

Categories

Resources