0% found this document useful (0 votes)
97 views31 pages

Java Servlets for Web Development

This document discusses how servlets work in a client-server web application. It explains that servlets are Java classes that process requests and generate dynamic web page content. The document outlines how requests are mapped to servlets, how servlets communicate with each other, and how data can be passed between servlets using request dispatching, redirection, URL rewriting, sessions, and cookies.

Uploaded by

g maheswari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
97 views31 pages

Java Servlets for Web Development

This document discusses how servlets work in a client-server web application. It explains that servlets are Java classes that process requests and generate dynamic web page content. The document outlines how requests are mapped to servlets, how servlets communicate with each other, and how data can be passed between servlets using request dispatching, redirection, URL rewriting, sessions, and cookies.

Uploaded by

g maheswari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1.

In the web world, a client(a computer) makes a request to a server(another computer) for a
webpage, the server returns the asked webpage & the client’s browser displays the webpage.
Now this webpage that was asked by the client could either be a static webpage or a dynamic
webpage. By static webpage, we mean that the webpage would already be created & the server
would just have to return it. By dynamic webpage, we mean that the webpage would be built
during runtime. So the webpage is formed on-the-fly & returned.

2. Now when a server receives a dynamic webpage request, server sees that it doesn’t already
have this as a static webpage, so the server sends the request to a helper application i.e a web
container. A web container has many servlets. A servlet is simply a Java class(that extends
HttpServlet class in servlet-api.jar found in tomcat library) which takes the request, processes it,
builds the required webpage & returns it in form of .html to the client. Now which webpage
request is mapped to which servlet(i.e which servlet is responsible for creating a particular
dynamic webpage) is mapped in a file web.xml called as deployment descriptor. In later versions
of servlet, annotations were introduced to avoid having this web.xml file, so that we can directly
add a webpage request mapping to a servlet just by adding an annotation.

3. The data that is sent from client to server can be shown in the URL & this part of the URL which
has the data is called query string or query params. Highlighted part is the query param.

4. A servlet can have only particular method names as when the request comes from tomcat to the
servlet, the servlet looks for only specific method names like service(), doGet(), doPost(),
doPut(), doDelete() etc based on the type of request. So a servlet cannot have any user-
customized name.
The methods in a servlet receive (HttpServletRequest req, HttpServletResponse res) as
parameters. The objects that these parameters receive are sent by the tomcat. We can get the
request data using request.getParameter(“paramName”) where paramName is a key given at
frontend for each input data.
We use res.getWriter() to get an instance of PrintWriter. Then we use this instance to write into
the response object using println() or write() method. Finally this response object is returned to
the client.
PrintWriter out = res.getWriter();
out.write(“Output”) /*OR*/ out.println(“Output”);

5. The <servlet-class> tag in web.xml takes the fully qualified class name of the servlet so we have
to give the package name also like com.telusko.AddServlet If we don’t give fully qualified class
name we won’t get any error but the tomcat won’t be able to find the servlet.
Also, servlet name of each servlet should be unique in <servlet-name> tag in web.xml else we
get error.

6.

Form at frontend
So now what happens is when the above form is submitted through the button, since in the
form action we have mentioned “add”, the request goes to the tomcat for DemoApp/add then
the tomcat looks at the web.xml for /add mapping & goes to the mapped servlet and looks for
the specific method as per the request. service() method is the default method that is always
invoked if it exists, if service() does not exist then based on the request method, the specific
doGet() or doPost() method is invoked. Since in the above example, method is not mentioned,
by default it’s get. Then the method executes & returns the updated response which is then
displayed on the client’s browser.

web.xml residing at server


Servlet residing at server

Output received at frontend

7. By default, a request is a get request if at frontend it’s not mentioned the method of request.
method can be get, post, put, delete, options etc In a get method, the input data goes in the
query params. In a post method it doesn’t. So when we want to fetch any data from database,
we can use get method, when we want to submit any data into database, we can use post
method coz we don’t want our personal data like username, pw to show in the URL. No matter
what method we use, the input data is always received by the servlet in HttpServletRequest req
object.
Going even deeper, when a server receives a dynamic webpage request, it goes to the mapped
servlet to that request, and invokes the service() method on that servlet object. Now if the
servlet class contains service() method, that is always invoked & executed & the response is
returned, if servlet class doesn’t contain service() method then the HttpServlet class contains a
service() method, that checks the method of the request. If it’s a get method then doGet() is
invoked on servlet object, if it’s a post method then doPost() is invoked.

8. RequestDispatcher & sendRedirect - Now if we want we can call a servlet from a servlet. To do
this we use a RequestDispatcher. RequestDispatcher is an interface & we get an instance of
RequestDispatcher from req. Using this object, we forward the request to another servlet. We
can also add some data from current servlet into req using req.setAttribute(“attributeName”,
data) & send it to the other servlet which will receive the data using the same attribute name.
Servlet1(AddServlet)
req.getRequestDispatcher(string) method takes in a string as an argument where this string is
the mapping mapped with the other servlet. In web.xml, SqServlet is mapped to /sq so from
AddServlet, req.getRequestDispatcher(“sq”) will be sent.

Web.xml

Servlet2(SqServlet)
Output at frontend
Now in such case, the client(browser) doesn’t know that if the response is coming from servlet1
or servlet2 as in the URL the path is of servlet1 only. Now this approach would work if servlet1 &
servlet2 belong to the same website. But if suppose servlet2 belongs to some other website,
then the client(browser) needs to be redirected to that website & we cannot use this approach
as here the client won’t know what’s going behind the scenes so how will it redirect.
So if servlet1 & servlet2 belong to two different websites, then we use a concept called
sendRedirect.

 One thing to note while using RequestDispatcher is that, if we write


req.getRequestDispatcher("abc"); in a servlet having @WebAnnotation(“/sq/*”) and if
we hit the url http://localhost:8080/DemoApp/sq then sq will be replaced by abc and it
will forward to http://localhost:8080/DemoApp/abc but if we hit the url
http://localhost:8080/DemoApp/sq/xyz/pqr then pqr will be replaced by abc and it will
try to forward to http://localhost:8080/DemoApp/sq/xyz/abc which wouldn’t exist.
 Also, if we write req.getRequestDispatcher("/abc"); in a servlet having
@WebAnnotation(“/sq/*”) then no matter what url we hit(as long as it starts with
/DemoApp/sq), it will always forward to http://localhost:8080/DemoApp/abc
 Also, if we write req.getRequestDispatcher(“/DemoApp/abc”) then it will try to forward
to http://localhost:8080/DemoApp/DemoApp/abc

In SendRedirect, when the client sends a request to Servlet1 with req1, res1 and then Servlet1
wants to send request to Servlet2 which is on a different website, then we use sendRedirect.
Using this, first Servlet1 will return req1, res1 to client(browser) and tell the browser to redirect
to Servlet2. Now the browser will make a new request with new request & response objects
req2, res2 to Servlet2. sendRedirect is invoked on the response object. sendRedirect can be used
to redirect to a servlet within the same website also.
Using sendRedirect in servlet1 i.e AddServlet to redirect to SqServlet(/sq)

SqServlet loaded since we don’t have anything it’s empty but it’s loading

To redirect to a different website we just need to mention the full URL of the website where
need it to be redirected like – res.sendRedirect(https://google.com);
 One thing to note is, if we write res.sendRedirect(“sq”); then it will redirect to
http://localhost:8080/DemoApp/sq but if we write res.sendRedirect(“/sq”); then it will try
to redirect to http://localhost:8080/sq and will give page not found error. So if we want to
use forward slash(/) then we should give full path like res.sendRedirect(“/DemoApp/sq”);
so that it redirects to http://localhost:8080/DemoApp/sq
 Also, if we write res.sendRedirect(“abc”); inside a Servlet with @WebAnnotation(“/sq/*”)
and if we hit the url http://localhost:8080/DemoApp/sq then sq will be replaced by abc
and it will redirect to http://localhost:8080/DemoApp/abc But if we hit the url
http://localhost:8080/DemoApp/sq/xyz then xyz will be replaced by abc, or if we hit the
url http://localhost:8080/DemoApp/sq/ and it will try to redirect to
http://localhost:8080/DemoApp/sq/abc and it might not find the required servlet as only
a servlet with @WebAnnotation(“/abc”) would be existing and not with
@WebAnnotation(“/sq/abc”).

9. Now suppose, when using sendRedirect(), if from Servlet1 we wanted some Servlet1 data to be
passed to Servlet2 then we cannot use setAttribute as new objects are passed to Servlet2. So we
have three ways to achieve this-
i. URL Rewriting
ii. Session Management
iii. Cookies

i. URL Rewriting – In Servlet2, we can receive any value from req using,
req.getParameter(“param”); Now we have not set anything in this param parameter
anywhere, so it’ll be null.

But if we go to the address bar and manually set something as a request parameter in
param, we’ll get that as output. Generally whatever input we send in a request comes as a
parameter in request object.
So now what if while redirecting from Servlet1 to Servlet2, we give the param with the URL
to redirect. We can give this param while redirecting to a different website too like
res.sendRedirect(https://google.com?param= + s);

ii. Session Management – Now whenever we access any web application, throughout the time
we are accessing that application until we logout or close the application, a session is
maintained by the server. Session will have all our data, any data that the server can store
that could be useful. A session would have the data from all the requests that we would
make while accessing that application. So now when we want to send some data from one
servlet to other servlet, we can store the data in session & get from the same session when
needed.
We get an instance of session from the request object & then using this instance we store in
the session whatever data we want mapping to a unique attribute. We can even remove the
attribute if needed in which case the data will no longer be available.
would remove the data in attribute “k”.

iii. Cookies – A cookie is a small piece of information that is persisted between the multiple
client requests. By default, each request is considered as a new request. In cookies
technique, we add cookie with response from the servlet. So cookie is stored in the cache of
the browser. After that if request is sent by the user, cookie is added with request by
default. Thus, we recognize the user as the old user.
So we can add any data needed from seervlet1 in a cookie & add it to the response sent
from servlet1. Then when a new request will be made to any servlet2, this cookie will be
added to that request by default.

Here we area creating a new cookie object and setting the cookie name to “k” & adding the
data i.e int k. A cookie takes the data in String format so we are concatenating it with an
empty String to form a String.
Then we are adding this cookie in the response using res.addCookie(cookie);
In Servlet2, we are getting the cookie from the request object. Now we actually get an array
of cookies with all the cookies that would be there in the request. Now we need to loop
over this array to find our required cookie with name “k” & then get the value associated
with it.

10. ServletContext & ServletConfig – If we want to define any initial values for our application like
filepath, username, password etc then we define in our web.xml file & then use that value in our
servlet as per the need.
Now, if we define any key-value in ServletContext then for that key, that value will be same for
all the servlets. But if we want key-value servlet wise then we can define under ServletConfig.

Now the objects of ServletConfig & ServletContext are provided by the tomcat, we just need to
get the objects by invoking getServletContext() for ServletContext object & getServletConfig()
for ServletConfig object. Using these objects we can get the parameters defined in web.xml
using getInitiParameter(“parameterName”);
11. Using Annotations to map instead of web.xml – We can directly use annotations to map any
incoming request directly to the servlet. This way we won’t need to map separately in web.xml
& would reduce a lot of coding time & lines. Usually in web.xml we map an incoming request
URL like /add to a servlet name & the required servlet would be mapped to this name to form
the connection. When using annotation, we will directly mention the request URL above the
servlet definition like-

Here we are using the @WebServlet annotation & inside this we are mentioning “/add” request
URL. Same way we can do for Servlet2 as well and then we can delete all the mapping code in
web.xml. It would work the same way as it was working previously.

Some rules to keep in mind regarding url-pattern & annotations-


i. When using @WebServlet(“String”) annotation, the String must start with a forward
slash(/). If we just write @WebServlet(add) for Servlet1, then the server will fail to start.
ii. Now, if we map /sq using @WebServlet annotation to Servlet2 and /sqst in web.xml also
to Servlet2, then Servlet2 will be accessible by both the URLs i.e /sq and /sqst both will
redirect to Servlet2.
iii. If two servlets have the exact same request mapping(doesn’t matter if using Annotation
or web.xml), then we will get an IllegalArgumentException
iv. Request mapping /sq and /sq/ are two different mappings.
v. If Servlet1 has request mapping /sq and Servlet2 has request mapping /* then if a /sq
request is made then Servlet1 will be called, else for any other request Servlet2 will be
called.
vi. If Servlet1 has request mapping /sq and Servlet2 has request mapping /sq/* then if a /sq
request is made then Servlet1 will be called, else for any other /sq/abc or /sq/xyz/pqr
etc, Servlet2 will be called.
vii.

viii.

ix. We can add multiple request mappings to the same servlet like-

Using web.xml

Using annotation
12. JSP – Now when a servlet sends a response to the client(via server), it sends in the form of .html
page. But till now we saw that we do not add any html tags in the response that is being sent,
just the output data required. That’s why the response that we were seeing in the browser just
had a line with our output. If we want we can customize the view of the page by adding html
tags with the output that is being sent in the response object.

This would change the background colour of the webpage to cyan. But if we want to have many
customizations in the webpage, then we have to add write each html tag using PrintWriter
object which would be very tedious & error prone. Also, this way we are mixing the backend
code with the design code which is not comfortable neither for backend developers nor for
frontend.
That’s why we have JSPs. JSP stands for Java Server Pages. In JSPs, we mostly have the frontend
code but we can include the Java code as well where needed. So in a Servlet we write HTML
code inside Java code but in a JSP we write Java code in HTML code.

In a JSP, we write any Java code in between <% these delimiters %> (called as Scriptlets). Else
it’ll be treated as normal html body & would get directly printed on the webpage. Also, here
we don’t need to write any method, the request & response objects can directly be accessed
using request & response. Also to write the output we can directly use PrintWriter object out
instead of creating it. So we get all these objects by default & no need to create or get these
objects using any method. These are called implicit objects. The above code would take two
integers from index.html & display the output.
This is first webpage of the app, index.html. Here, we need to change the action from
add(earlier) to add.jsp(now) to redirect to add.jsp page upon click of Submit.

So now if writing code in JSPs is easier than writing code in Servlets, why do we need Servlets?
Why can’t we achieve the same things using JSPs? This is because our server(Tomcat) is a Servlet
Container. So our servlets are contained & run on this server. And this server can only run
servlets and not JSPs. But we saw in the above code, that it’s working and giving the output
using just JSP. So how is that possible if server cannot run JSPs. This is because internally even a
JSP gets converted to a servlet & then that is run on the server.
Now even though JSPs get converted to Servlets & writing code is easier in JSP, that doesn’t
mean we will only use JSPs. This is because, this conversion of JSP to a Servlet would take some
amount of time right, so that much time is being wasted just to convert a JSP into a servlet when
we can directly write a servlet. Also, we should never write any business logic inside a JSP as JSP
should just be responsible for the view(frontend) part of the response. All the business logic
should go into the servlet coz that’s where all the processing happens.

Now when we already have HTML for the frontend part, why do we need JSP?
This is because HTML can be used to only form static webpages, not dynamic. So if we want to
populate the webpage with some dynamic data as per the user, we cannot achieve that using
HTML, we have to use JSP.
In the above image, it’s shown how the code in JSP gets changed to the corresponding code of a
servlet internally.
Whatever is written under Directive tag, gets converted to import statement in a servlet.
Whatever is written under Declaration tag, gets converted to member fields, & methods other
than the service(), doPost(), doGet() etc
Whatever is written under Scriptlet tag, gets converted to service() method definition.
Whatever is written under Expression tag, gets converted to a print statement.
The jsp file name gets converted to the class name of the servlet with “_jsp” as suffix.
We can have any number of each type of tags & anywhere in the whole jsp page.

Now Directive tag is of three types-


i. @page – Whatever we want to define above the whole page goes here. It has many
attributes, some of the common ones are-

language is java by default


extends is for making our servlet extending any class
import is for importing packages. Only this attribute can be used multiple times in different
directive tags, else other attributes should be mentioned only once
If we want to disable session we can set session as false
autoFlush is for buffering, if it’s true then when the buffer will be full only then the response
will be sent to client
contentType is the type of response sent to client i.e usually it’s “text/html”
errorPage is used to give any other page that would be used to handle our exceptions
isErrorPage tells if the current page itself is the errorPage
info is for information about page
isELIgnored is for ignoring Expression Language or not
isThreadSafe is for making our JSP page thread safe or not

ii. @include – If we want to include code of some other jsp in our jsp then we can use this tag
like-

This will add the code in header.jsp in our current_file.jsp

iii. @taglib – This is to use any custom library tags in our jsp page other than normal html tags.
We have to mention the uri of the external tag library in uri attribute
prefix takes any character, string etc. This tells that whenever we want to use any tag in this
custom library, we have to start it with this prefix like <fx:book> where book is a custom tag
with some functionality defined in this custom tag library.

13. These are the built in objects that JSP provides us that we can directly use in the Java code in a
JSP without declaring them.

We have already seen the functionality of all the above objects except pageContext.
Now, just like we can set & get values using a session or a cookie or a request attribute,
similarly, we can set & get value using pageContext. The default scope of a pageContext is within
the same page. So if we want to set any key-value & later use that value in the same page, we
use pageContext.
pageContext.setAttribute(“name”,”Shivang”);
//many lines of code
String s= pageContext.getAttribute(“name”);
The scope is within the same page only so cannot use the same key-value in some other page.
But we can set this scope if we want like-
pageContext.setAttribute(“mobile”,”Samsung”, PageContext.SESSION_SCOPE);
PageContext.SESSION_SCOPE will set the scope of pageContext to whole session. There are a
few more scopes possible that we can use.

14. Exception Handling in JSP – We can even handle exceptions in JSP using try catch block. If we
want we can have a whole different JSP page just to show the errors. For this we have to use the
errorPage attribute of page Directive tag like-
<%@ page errorPage = “error.jsp” %>
We can even use in-built exception object to print the error message but this object can only be
used in an errorPage jsp, for this we have to mention that this particular jsp is an errorPage by
doing - <%@ page isErrorPage=”true” %>
Using the exception object to print the error message

15. JDBC in JSP – We can use a driver to connect our JSP with a database. We will be using the same
7 steps that we used for connecting a java code with a database like MySQL using JDBC.

At the top we need to mention <%@ page import=”java.sql.*%> to import java.sql package.

16. MVC using Servlet & JSP –


i. Now when a client sends a request to the server, the server redirects the request to the
appropriate servlet. Now this servlet is nothing but the Controller.
ii. Now whatever response would be sent to the client, it would have some static layout(that
would be displayed on the frontend & would be same for everyone) and some dynamic
data. Now in the JSP, the static layout would be hardcoded and fields would exist to
populate the dynamic data as per the user. Now to get this dynamic data, Controller will first
contact Model.
iii.
a) This Model is nothing but another layer that has Manager classes & DAO classes.
The controller will invoke a method in the manager class. The manager class would
invoke a method in DAO layer(DAO class) & in DAO layer the code to connect with
the database is written. So DAO layer will fetch the data from the database & return
to the Manager class in form of a POJO(Plain Old Java Object). A POJO is nothing but
a simple Java object that would hold the required data & this object would be
returned from DAO to Manager. This POJO object would be of the class whose data
we are dealing with i.e the class representing the table in database. Eg: If we are
dealing with Student ID, marks etc then the POJO will be of Student class having
fields ID, marks, name etc
b) Manager classes have all the business logic responsible for any actions to be
performed on the data so the POJO returned would be manipulated to
add/delete/modify the format etc as per the need. Then this POJO would be
returned to the Controller
iv. The controller would then send this POJO to the View & the view would then fill the data in
it’s fields left out for dynamic data. The finally created JSP page would then be returned in
the form of .html to the client.

Each table in database should be having a corresponding class to represent that table and a
corresponding DAO class to interact with that table.

17. We can forward a request from a servlet to a JSP using request dispatcher or even
sendRedirect()(need to set data in session or cookie) & also send any data required. If we use
requestDispatcher then in the address bar, the URL will be shown of servlet only but the view
will be of JSP. If we use sendRedirect(), then the URL & view both will be of JSP.

Sending name from Servlet


Receiving name in JSP

18. JSTL – JSP Standard Tag Library. Now in JSP, we write Java code inside HTML, which is still not
really comfortable for designers(frontend developers). So JSTL were introduced to convert Java
code into HTML like syntax.
Now there is something called as Expression Language using which the above example can be
reduced to just this-

Getting the name using just ${label}

If we give ${abc} even though we never put anything in abc, we won’t get any error or
exception, it just won’t print anything.
We can even use session to put & receive data just like above i.e we can do-
HttpSession session = req.getSession();
session.setAttribute("label2", "Session"); //This code in the servlet

${label2} //This code in the jsp to get the session value of “label”
If session & request attribute are of same name i.e if we set in request in “label” key & in session
in “label” key, then the request attribute value would be printed.
If we have a request parameter “label” and we try to print ${label} in JSP, it won’t print anything
as ${label} doesn’t check for “label” in request parameters. To print a request parameter key,
we have to do ${param.label}.

Now, we can have customized tags using JSTL. To use a customized tag, first we have to add the
libraries i.e .jar files of the tags in /Project/src/main/webapp/WEB-INF/lib folder and then in the
.jsp file we have to include the taglib tag to include the tag library. Also, we need to mention a
prefix which means that whenever we need to use any customized tag of this library, we will be
using by adding this prefix at the start-

Output
Here, uri in taglib tag is the location of the tag that we would use
prefix is any string that we can mention that would tell that this is a customized tag
We are using customized <out> tag to print on the screen and we have mentioned prefix c
before that. We can also use ${label} with JSTL tags to get the data set in a servlet.

<c:import url=”https://google.com”> can be used to display google webpage in our webpage.


<c:set> can be used to set value in an element
<c:remove> can be used to remove an element

Now, let’s say we have a Student class like-

Now, from a servlet we can create a Student object and pass it to the request in form of a
param(attribute) or in a session etc. like-

Now if in display.jsp, we do ${student}, we will get the hashcode of the student object. To get
the values we need to have toString() in Student class(like how normal
System.out.println(student) in java works).
But if we try to do ${student.name} we will get an exception-
We need to have getters & setters in Student class for this to work otherwise {student.name}
would give exception as the EL won’t be able to access the fields in Student class without
getters.
Now, if we pass an ArrayList containing a few students and try to print the object, then we will
get all the students in one line like-

But if we want all the students in separate-separate line then we can use customized forEach
JSTL tag like how we use normal forEach in Java-

items attribute of forEach tag takes the list to be iterated and var is the variable in which each
element gets stored just like for(Student s : students){}
We can even print just the name or the rollNo using ${s.name} or ${s.rollNo} in the out tag.

19. SQL in JSTL – We can connect our JSP code with a database using JSTL tags like-

For using SQL JSTL tags, we need to add mysql-connector jar in /Project/src/main/webapp/WEB-
INF/lib folder. The prefix given here is sql for sql tags. Also, we need to add the sql taglib by
adding uri http://java.sun.com/jsp/jstl/sql.
Here, in setDataSource tag, var takes the name of the db that we want to give for the usage in
code, driver takes the name of the driver for our database, url takes the url of the database we
want to connect with, user is the username & password is the pw of the database.
setDataSource will establish the connection with mario database.
Then in query tag, var takes the variable in which the result returned by the query will be stored,
dataSources takes the name of the database that we are writing the query for. Then we can
write the query in between <query> </query>. (gadgets is the table name)
Then we are using forEach tag to print the data of every row. In forEach, we are doing items =
“${rs.rows}” Now this rs.rows will give all the rows as a list in items
attribute([row1,row2,row3…]) & we are iterating over this list so in each iteration, var gadget
will store one whole row. Then we can get each column using gadget.columnName.

20. Functions in JSTL – JSTL offers in-built functions like to print length of string, splitting the string
etc. Some of the common String functions are-
21. Servlet Filter – Now let’s say we have an index.html where we are taking ID and Name as input.
Now we want that the ID entered should be a positive integer and not a negative one. So in our
servlet we can add a check that if ID<=0 then return the request. But a more proper way would
be to use Filter. A Servlet Filter is just a class that implements Filter interface. It needs to define
these three methods – init(), destroy(), doFilter()(where we define the functionality of the filter).
Servlet Filters are used to filter the request based on whatever criteria/functionality is written
inside the filter. These filters would allow the request to move forward only if the criteria is met
else they can return the request.
We can have multiple filters for a servlet, in which case the request would go through each &
every filter one by one and any filter can return the request if the criteria is not met. This is
called as Filter Chaining. The order in which the filters will be invoked will be the order in which
we define the filter-mappings in web.xml.
These filters are independent of each other and one filter doesn’t know about the existence of
other filter for the same servlet i.e one filter doesn’t know if the request is being forwarded to
any other filter or to the servlet.
Also, the servlet is not aware that the request is coming passing through these filters.
It's not mandatory that only a condition should be defined inside a filter, we can have any kind
of requirement/functionality inside a filter. Eg: If we want that whichever request is directed
towards a particular servlet, it should be logged so we can add a logging filter which would log
the request when it would pass through the filter before reaching the servlet.
Now if we have multiple filters then the last filter would forward the request to the servlet.
Advantage of using a filter over having condition separately in the servlet is, that we can add the
functionality of a filter in as many servlets as we want by just adding the servlets request
mappings in our filter-mapping.

In doFilter (ServletRequest request, ServletResponse response, FilterChain chain) method we


will define our filter functionality. Notice the parameters type are ServletRequest &
ServletResponse and in any servlet method, the parameters type are
HttpServletRequest(subinterface of ServletReqquest) & HttpServletResponse(subinterface of
ServletResponse) but we don’t need to explicitly type cast request & response when forwarding
the request from filter to servlet.
chain.doFilter(request, response); is responsible for forwarding the request from one filter to
the other filter/or the servlet if it’s the last filter.
We can define the request mapping of a filter either in web.xml or using annotation-

Using Annotation

In web.xml file
FilterExample filter is a filter for /sq request-mapping so any /sq request would pass through this
filter then would go to the required servlet.
We can also have multiple request mappings to the same filter by-

If we have multiple filters for the same servlet, then the order in which the filters will be invoked
depends on the order in which the <filter-mapping> tag is defined for filters in web.xml file.
If we are using just annotations then the order is undefined and so the filters will be called at
random.
If we are using annotation for some filters and web.xml mapping for some filters, then the filters
in web.xml will be called first then the filters having annotations.
However, if we want to use annotations & still define the order, we can do so by just adding the
<filter-mapping> for the filters in web.xml-

22. When a user logs into our application, we want that the user should stay logged in until he logs
out so that he doesn’t have to log in for each & every secure page of our application. He just
needs to log in once & the other secure pages will check if the user is logged in or not. This will
be achieved by using sessions. When a user logs in, we will put an attribute in the session, and
when navigating to other secure pages, those pages will check if that attribute is there in the
session or not, if it’s there then that means that the user has already logged in, else if it’s not
then that means that the user never logged in so the user should be asked to log in again.

Login.jsp page where the user will input his username & password

Once the login is successful, we are putting “username” attribute with the input username as
value, into the session

In other secure pages like welcome.jsp we are checking if the “username” attribute exists in
session or not, if it does not then the user will be redirected to login page & be asked to login
again, else “Welcome username” is printed
If the user clicks on “logout” button and logs out, then we need to remove the “username”
attribute from the session. Also, session.invalidate() will remove any stored user data.

23. Now if we are logged-in in our application and are accessing all the secure pages, we will be able
to access. Now let’s say we navigate from welcome.jsp to videos.jsp and both these pages are
secure i.e a user can only access these pages if he/she is logged in as we are checking the
session if the user is logged in or not. Now from videos.jsp if we press back button, we will go
back to welcome.jsp coz we are logged in. Now if again go to videos.jsp and click on “logout” so
it’ll delete the attribute from the session responsible for the login-check and now if we go to any
page it’ll ask for login. But after logging out from videos.jsp, if we click on back button, we’ll be
able to see welcome.jsp even though we are logged out. This is because the welcome.jsp page
was cached by the browser for quicker access & when we pressed the back button even after
logging out, it displayed the cached logged-in welcome.jsp page. So this is a security flaw.
To avoid this, we can tell the browser not to cache our security pages. Now browsers read
“headers” from our jsp file and headers are a way of communicating with the browsers. So in all
our secure jsp pages, we can set a header to tell the browser not to cache/store the page.
We do this by using response object & set the header-
Now here, this is the standard hardcoded format and browser would understand these exact
keys & values.
Now if the HTTP that is being used is HTTP 1.1 then the first statement would work, if the HTTP
is 1.0 then the second statement would work and if proxy servers are being used then third
statement would work, so we need to write our code for all three variations and thus adding all
three above statements. “must-revalidate” in the first statement means that the browser should
revalidate the session-login check every time welcome.jsp is visited even if it’s through back
button.

24. When a user tries to log-in by entering some username & password, our code should check the
input username & password with the username & password stored in our database. If it
matches then the user should be allowed to proceed else not. To do so we can get the
username & password stored in our database for that particular input username & password. If
the database returns a row then that means the exact username & password exist in the
database and so the user has entered correct credentials. If the database doesn’t return
anything then that means the input credentials are invalid and thus the user would be asked
again to login.
Dao layer where we have a check() method that checks if the input username & password exist
in the database or not. If exist then a row will be returned else, no rows will be returned.
If(rs.next()) check ensures that if a row is there in the returned table or not.

doPost method in the Controller(Servlet) from where we are invoking the check() method in Dao
layer with the input username and password.

25. File Upload in Java Servlet – We can have an option in our web app where the user can upload
one or multiple files, which will get stored in the server or database.
In the frontend part, we will specify the input type as “file” to have a file upload option in the UI.
Now if we just write multiple(an attribute) in the input tag, then it means the user can upload
multiple files. Now when we send files to the server, we also need to mention the encoding type
and that we do by writing enctype=”multipart/form-data”. It sends the form data to server in
multiple parts because of large size of file.

UI will look like this, it has an option to upload files

We need a “Apache Commons FileUpload” jar when we are working with uploading files. We
can separately download the jar and add it to the lib folder of our project, or if we have a maven
project then we can just add this dependency in pom.xml-

Now this was client side, let’s go to server side to handle received files. Now whatever file/s the
user has uploaded, those files will be sent in the request object. But we cannot directly extract
the files from request object, we need to use ServletFileUpload object to parse the request &
get a list of files and here each file will be of type FileItem. Now ServletFileUpload & FileItem are
classes(type) in Apache Commons FileUpload jar and that’s why we need that jar.
Now, once we have the List of the files, we need to iterate over the list, and for each file, we
need to store the file on the disk. We will use the write method of the FileItem class to store the
file on the disk.
We create an object of ServletFileUpload as shown above.
Using that object we are parsing the request and getting a List of input files and storing in
List<FileItem> object as each file is of type FileItem.
Then we are iterating over the List and for each file we are invoking the write method on the
file. This write method takes the File where the uploaded item should be stored so above we are
creating a new File object which is taking the path where the file will be stored + with what
name it’ll get stored.
The uploaded files got stored on the disk in the specified location-

You might also like