Servlet jsp interview question: We have compiled most frequently asked Java J2EE Interview Questions which will help you with different expertise levels.
Java J2EE Interview Questions on Servlets & Jsp
Question 1.
What are servlets? And, what purpose do they serve?
Answer:
Servlets are Java programs run on Web or application servers, acting as the middle layer between requests coming from web browsers or other HTTP clients and databases or applications on the HTTP server. As illustrated in Figure 6, their job is to perform the following tasks:-
(1) Read the explicit data sent by the client: The end-user normally enters this data in an HTML form on a Web page. However, the data could also come from an applet or a custom HTTP client program.
(2) Read the implicit HTTP request data sent by the browser: The HTTP information includes cookies, information about media types, and compression schemes the browser understands, and so on.
(3) Generate the results: This process may require talking to a database, executing an RMI or EJB call, invoking a Web service, or computing the response directly.
(4) Send the explicit data (i.e. the document): This document can be sent in a variety of formats such as text (HTML or XML), binary (GIF images), or even a compressed format like gzip that is layered on top of some other underlying format.
(5) Send the implicit HTTP response data: Sending the implicit HTTP response data (besides the explicit document itself) involves telling the browser or other client what type of document is being returned (e.g. HTML), setting cookies, and caching parameters, and other such tasks.
Question 2.
What is the underlying need to build web pages dynamically?
Answer:
Servlets and JSP technology has become the technology of choice for developing online stores, interactive Web applications, and other dynamic Web sites. There are a number of reasons why Web pages need to be built on the fly:-
(1) The Web page is based on data sent by the client: For instance, the results page from search engines and order confirmation pages at online stores are specific to particular user requests. You never know what to display until you read the data that the user submits.
(2) The Web page is derived from data that changes frequently: If the page changes for every request, then you certainly need to build the response at request time, e.g. a weather report or a news headlines site might build the pages dynamically, perhaps returning a previously built page if that page is still up to date.
(3) The Web page uses information from corporate databases or other server-side sources: If the information is in a database, you need server-side processing even if the client is using dynamic Web content such as an applet. Going from the client to the Web tier to the database (a three-tier approach) instead of from an applet directly to the database (a two-tier approach) provides increased flexibility and security with little or no performance penalty. In fact, a three-tier approach is often faster because the middle tier can perform caching and connection pooling.
Question 3.
Give a sample servlet code and point out its main features.
Answer:
A sample servlet code that results in displaying – WELCOME – is the following:-
import java.io.*; import javax.servlet. *; import javax.servlet.http. *; public class WELCOMEServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, lOExccption { response.setContentTypeC'text/html"); PrintWriter out = response.get Writerf); String docType = "<!DOCTYPE HTML PUBLIC \" - // W3C // DTD HTML 4.0 “ + "Transitional // EN\ ">\n”; out.princln!docType + “<HTML>\n" + " /<HEAD><TITLE>WELCOME</TITLEx/HEAD>\n'' + "<BODY BGCOLOR= \ "FDF5E6\ "In" + "<H1>WELC0ME< lHl>\n” + “ </BODYx/HTML>"); } }
There are essentially four points to note in the above servlet code:-
- It is regular java code: There are new API’s but no new syntax.
- It has unfamiliar import statements: The servlet and JSP API’s are not part of the Java 2 Platform, Standard Edition (J2SE); they are a separate specifications and are also a part erf the Java 2 Platform, Enterprise Edition (J2EE).
- It extends a standard class (HttpServlet): Servlets provide a rich infrastructure for dealing with HTTP.
- It overrides the doGet method: Servlets have different methods to respond to different types of HTTP commands.
Question 4.
What are the advantages of servlets over traditional CGI?
Answer:
Java servlets are more efficient, easier to use, more powerful, more portable, safer, and cheaper than traditional CGI and many alternative CGI-like technologies.
Question 5.
Why is HTTP referred to as a stateless protocol?
Answer:
HTTP is called a stateless protocol since every request is independent of the previous request. The server doesn’t keep track of whether the same user is making repeated requests.
Question 6.
What is the order in which the life cycle methods are called in a Servlet/HttpServlet and which are the ones that can be overridden?
Answer:
The order of the life cycle methods in a Servlet/HttpServlet is enumerated as under:-
(1) init( ): Called only once during the initialization of the Servlet.
(2) destroy( ): Called only once when a Servlet instance is about to be destroyed.
(3) service( ): Do not override this method.
(4) doGet( ), doPostO, doPutO, doDeleteO, doOptionsO, do trace!): These methods are called according to the type of HTTP request received. Override them to generate your own response.
(5) log( ): Writes messages to the Servlet’s log files.
(6) get the last modified( ): Override this method to return your Servlet’s last modified date.
(7) getServletlnfo( ): Override this method to provide a String of general information about your Servlet such as author, version, copyright, etc.
(8) getServletName( ): Override this method to return name of the Servlet.
(9) getlnitParameter( ), getlnitParameterNames( ): The first one returns the value of the given initialization parameter, the second one returns an Enumeration object containing the names of all initialization parameters provided.
Question 7.
Bring out the difference between GET and POST requests.
Answer:
The HTML specifications technically define the difference between “GET” and “POST” so that the former means that form data is encoded (by a browser) into a URL while the latter means that the form data is to appear within a message body. Thus, we can say that “GET is basically for just getting/retrieving data while “POST” may involve anything such as storing/ updating data, ordering a product or sending an E-mail, etc.
Question 8.
Bring out the difference between ServletContext and HttpSession.
Answer:
The interface ServletContext defines a set of methods that a servlet uses to communicate with its servlet container, e.g. to get the MIME type of a file, dispatch requests, or write to a log file. There is one context per “web application” per JVM that can be used as a location to share global information.
The interface HttpSession provides a way to identify a user across more than one-page requests or visit a website and to store information about that user. The servlet container uses this interface to create a session between an HTTP client and an HTTP server. This interface alloivs servlets to:-
- View and manipulate information about a session such as the session identifier, creation time and last accessed time, etc.
- Bind objects to sessions, allowing user information to persist across multiple user connections.
Question 9.
Bring out the difference between forward!) and sendRedirect( ) methods.
Answer:
forward( ): It finds the Servlet on the local server, and calls its service (request, response) method, passing the same request and response that was used by the current page. The parameters stored in the request object are available to the called request when we forward a request, and the URL in the address bar will not change.
sendRedirect( ): It sends a response to the client with a meta-refresh that makes the client send a new request to the page specified. We can also make requests to pages other than those on the local server as well. The parameters stored in the request object are lost when we redirect . and the url in the address bar will change.
Question 10.
Are variables declared at the class level in a servlet thread-safe? Explain in brief.
Answer:
There is only one copy of the instance variables per instance of the servlet and all of the threads share this copy. In case of the multithreaded model, multiple threads may access an instance variable simultaneously, which makes it unsafe. In the case of a single-threaded model, only one thread executes the methods of a servlet instance at a tiirie. Whence, an instance variable is thread-safe in this case.
By wrapping non-thread-safe code in a synchronized block, you can force the requesting thread to acquire the instance lock in order to gain access to the code block, thus making it safe, e.g.
synchronized this) { ctr++; }
Question 11.
How many instances of a servlet are created?
Answer:
Only one instance of a servlet gets created. And, this instance is accessed by all the requests hitting the server.
Question 12.
How can you make a servlet Single-threaded and how many instances are created in this case?
Answer:
A servlet can be made thread-safe by implementing the SingleThreadedModel interface. The number of instances created depends upon what the Servlet container decides to do. It may just create one instance; it might create more.
Question 13.
What is the argument of the init( ) method? What is ServIetConfig and what does it contain? Elaborate.
Answer:
An object of type ServIetConfig is passed. ServIetConfig is an interface. A servlet configuration object is used by a servlet container to pass information to a servlet during initialization. Two of the methods available are:-
- getServletName( )
- getServletContext( )
Question 14.
What are the exceptions thrown by the service method?
Answer:
The exceptions thrown are:-
ServletException and lOException.
ServletException is thrown to report any problems encountered in the servlet engine trying to service the HTTP request while an lOException can be thrown when using the PrintWriter object to stream web resources back to the client browser.
Question 15.
What will happen if the service method in HttpServlet is overridden?
Answer:
If we override the service method in an HttpServlet, we have to take care of calling the default service method. In some cases, it does make sound sense to override the service method, e.g. when you have a lot of Servlets that need to perform the same checks (like, is the session authenticated?) before processing the request.
Rather than having to copy the logic into each Servlet you write, you can develop a common base class which extends HttpServlet. The logic inside the method is effectively as follows:-
service(...) { common processing logic .... super.service(...); }
Another option is to write the logic in a helper method and call it at the beginning of both the doGet and doPost methods. . .
Question 16.
How can you keep track of the sessions created in a servlet container? Elaborate.
Answer:
The session can be kept track of using the following two objects:-
(1) HttpSessionListener: Implementations of this interface are notified of changes to the list of active sessions in a web application. To receive notification events, the implementation class must be configured in the deployment descriptor for the web application.
(2) HttpSessionEvent: This is the class representing event notifications for changes to sessions within a web application.
Question 17.
How does an object know when it is put in session?
Answer:
An object can know when it is put in session by means of the following two events:-
(1) HttpSessionBindingListener: This causes an object to be notified when it is bound to or unbound from a session. The object is notified by an HttpSessionBindingEvent object:
(a) The method valueBound(HttpSes$ionBindingEvent event) – notifies the object that is being bound to a session and identifies the session.
(b) The method valueUnbound(ElttpSessionBindingEvent event) – notifies the object that is being unbound from a session and identifies the session.
(2) HttpSessionBindingEvent: It has methods like getName which returns the name with which the object is bound to or unbound from the session.getSession which returns the session to or from which the object is bound/unbound.
Question 18.
How do you set the session time out for a session? Can you make it infinite; if yes, how?
Answer:
The method setMaxInactivelnterval in HttpSession can be used to set the timeout.
public void setMaxInactivelntervaldnt interval)
where interval specifies the time in seconds between client requests before the servlet container will invalidate this session. A negative time indicates that the session should never timeout (infinite timeout).
Question 19.
What are the methods available in HttpSessionListener?
Answer:
sessions created and session destroyed are the two methods available in HttpSessionListener. An HttpSessionEvent object is passed to these methods by the container when a new session is created or when an existing session is destroyed.
Question 20.
How do you carry out session management?
Answer:
Since HTTP is a stateless protocol, we use a variety of methods to maintain information on the history of actions performed during a session. There are four ways in which we can do session management, enumerated as under:-
(1) Cookies: A cookie is a piece of information stored on the client machine by the browser. Cookies are widely used by various server-side programming techniques for the purpose of implementing session tracking. The cookie is a text file that is stored on the client machine. These cookies are sent to the server whenever a user makes a request to the same server from which the cookies were created. The Java API provides us various classes and methods designed to allow us to use cookies in servlets. Some of the places where a cookie can be used are storing user preferences, shopping cart applications, etc.
(2) URL Rewriting: In this method, the data is appended to the URL over successive requests. In addition to the current data, the values of the previous data with which the user invoked the servlet are retrieved from the incoming URL and appended to the new URL. In other words, the parameter values for each successive URL that is generated match those of the previous URL. In addition, new parameter values are added which represent the current data.
(3) Hidden Fields: IN HTML, we have a type of field called HIDDEN. This type of field is not visible on the browser but gets passed to the application server. Every time the client makes a request to the server, an HTML form is created and sent back to the client. Hidden fields are added to the form each time it is created. The hidden fields contain the data from the previous request that would be required in the future. requests. Using this approach, the historical data is saved by embedding it in the new
HTML database or in the server’s file system.
(4) HttpSessiomThe HttpSession object is created and maintained by the application server. We can get hold of the session object using request.getSession(true) where the request is of type HttpServletRequest. Once we have a handle on this object, we can store data in this object, and this data is shared between the various requests coming from the same user in one session, i.e. from one browser window. Sessions are used to maintain state i and user identity across multiple page requests. The session persists for a specified time period. We can add and retrieve objects from a session using the following two methods:
- void setAttribute(java.lang.String name, java. lang.Object value);
- java.lang.Object getAttribute!java.lang.String name);
Question 21.
Give a sample JSP code and point out its main features.
Answer:
A sample JSP code that uses a request parameter to display the title of a book is the following:-
<!DOCTYPE HTML PUBLIC “ - // W3C // DTD HTML 4.0 Transitional // EN"> <HTML> <HEAD> <TITLE>WELCOME</TITLE> <LINK REL=STYLESHEET HREF-"JSP-Styles.css" TYPE-"text / css"> </HEAD> <BODY> <H2>Order Confirmation</ H2> Thank you for the order <lx%=request.getParameter("title") %>< /!>! </BODYx/HTML>
There are essentially two points to note in the above JSP code:-
- It is mostly standard HTML.
- The dynamic code consists entirely of the half-line depicted in bold in the code.
Question 22.
Compare and contrast the role of JSP vis-a-vis servlets.
Answer:
A somewhat oversimplified view of servlets is that they are Java programs with HTML embedded inside of them. A somewhat oversimplified view of JSP documents is that they are HTML pages with Java code embedded inside of them. Thus, servlets look mostly like a regular Java class whereas a JSP document looks mostly like a normal HTML page. Despite the huge differences, the interesting thing is that behind the scenes, both are the same. In fact, a JSP document is just another way of writing a servlet. JSP pages get translated into servlets, the servlets get compiled and it is the servlets that run at request time.
So, the question is, if JSP technology and servlet technology are essentially equivalent in power, docs u matter, which you use? Of course, yes! The issue is not power, but convenience, ease of use, and maintainability. JSP is focused on simplifying the creation and maintenance of HTML whereas servlets are best at invoking business logic and performing complicated operations. A quick rule of the thumb is that servlets are best for tasks oriented towards processing while JSP is best for tasks oriented towards presentation. For some requests, servlets are the right choice; for other requests, JSP is a better option; for still others, neither JSP nor servlets alone are best and a combination of the two is best (as in MVC – Model View Controller architecture).
But, the point is that you need both JSP and servlets in your project. Almost no project mill consists entirely of servlets or entirely of JSP; you want both!
Question 23.
What are the benefits and needs of JSP? Elucidate.
Answer:
As we have already pointed out, although JSP and servlets are equivalent behind the scenes, servlets are not so good when it comes to presentation; they excel in tasks related to programming or data processing. Servlets suffer from the following deficiencies when it comes to generating the output:-
- It is hard to write and maintain the HTML;
- You cannot use standard HTML tools;
- The HTML is inaccessible to non-Java developers.
JSP technology offers the following benefits in this context:-
- It is easier to write and maintain the HTML;
- You can use standard website development tools;
- You can divide up your development team so that the Java programmers can Work on the dynamic code while the Web developers can concentrate and focus on the presentation layer/aspect.
Question 24.
What are the common misconceptions about JSP?
Answer:
Some of the common misunderstandings involving JSP are the following:-
- Forgetting that JSP is server-side technology;
- Confusing translation time with request time;
- Thinking JSP alone is sufficient;
- Thinking servlets alone is sufficient.
Question 25.
Explain in brief how a JSP is processed.
Answer:
A JSP is converted into a Servlet by the application server and then the request is serviced. Once compiled, the Servlet object created from the JSP remains in memory just like any other Servlet. When a change is made to the JSP then the servlet object gets re-created. This could very well vary depending upon the server.
Question 26.
What is an ‘include’? Enumerate the types of ‘includes’.
Answer:
We can use the <jsp: include an element to include either a static or dynamic resource in a JSP page. If the resource is static, its content is included in the calling JSP page as it is. If the resource is dynamic, it acts on a request and sends back a result that is included in the JSP page. When the include action is finished, the JSP container continues processing of the remainder of the JSP page. If the included resource is dynamic, we can use a <jsp: param> clause to pass the name and value of the parameter to the resource, e.g. we can pass the user and a value to a login form that is coded in a JSP page.
Question 27.
Can you use Tag Libraries in a JSP; if yes, how?
Answer:
A tag library is a set of actions that encapsulate functionality. These tags are then used within JSP pages. This helps us to reuse common functionality like connecting to a database.
<%@ taglib prefix=”sql” url=http://java.sun.com/jstl/sql %>
For JSP pages that do not have a default database, <sql:setDataSource> can prepare a database for use.
The code snippet below shows how to create a data source.
<sql:setDataSource var="example" driver="oracle.jdbc.driver. OracleDriver " url=''jdbc:oracle:thin:@<OracleServerName>:1521:OraclelnstanceName>” user=" scott” Password^” tiger” />
Question 28.
Can you explain how exception handling is done in JSP?
Answer:
You can specify the error page in the ‘page’ directive. Then, if an exception is thrown, the control will be transferred to that error page where you can display a useful message to the user about what happened and also inform your sysadmin about this exception depending, of course, on how important it is.
<%@ page errorPage=”ExceptionHandler.jsp” %>
<%@ page isErrorPage= “true” import=”java.io.*” %>
Question 29.
Enumerate the implicit objects in JSP.
Answer:
There are nine implicit objects that are available in a JSP enumerated as under:-
(1) Application is the broadcast context state available. It is equivalent to ServletContext. It allows the JSP page’s servlet and any Web components contained in the same application to share information.
(2) Config allows initialization data to be passed to a JSP page’s servlet. This is equivalent to the ServletConfig object passed to the init method in the Servlet.
(3) Exception houses exception data to be accessed only by designated JSP “error pages”.
(4) Out provides access to the servlet’s output stream.
(5) Page is the instance of the JSP page’s servlet processing the current request. Not typically used by JSP page authors.
(6) PageContext is the context for the JSP page itself. It provides a single API to manage the various scoped attributes. This API is used extensively when implementing JSP custom tag handlers.
(7) Request provides access to HTTP request data, as well as providing a context for associating request-specific data.
(8) Response enables direct access to the HTTPServletResponse object and is very rarely used by JSP authors.
(9) Session is perhaps the most commonly used of the state management contexts. It is useful in starting a user’s information when he accesses the web application over several requests.
Question 30.
Can you prevent caching of the page; if yes, how?
Answer:
You can use Microsoft Internet Information Server (IIS) to easily mark highly volatile or sensitive pages using the following script at the extreme beginning of the specific Active Server Pages (ASP) pages:-
<% Response.CacheControl = “no-cache” %>
<% Response.AddHeader “Pragma”, “no-cache” %>
<% Response.Expires = -1 %>
Question 31.
Why should we use beans?
Answer:
Although it is true that beans are merely Java classes that are written in a standard format, there are several advantages to their use. With beans in general, visual manipulation tools and other programs can automatically discover information about classes that follow this format and can create and manipulate the classes without the user having to explicitly write any code. In JSP in particular, the use of JavaBeans components provides three advantages over scriptlets and JSP expressions that refer to normal Java classes:-
(1) No Java syntax: By using beans, page authors can manipulate Java objects using only XML-compatible syntax, that is to say, no parentheses, semicolons, or curly braces.
(2) Simpler Object Sharing: When you use the JSP bean constructs, you can much more easily share objects among multiple pages or between requests than if you use the equivalent explicit Java code.
(3) Convenient correspondence between request parameters and object properties: The JSP bean constructs greatly simplify the process of reading request parameters, converting from strings, and putting the results inside objects.
Question 32.
Enumerate the various ‘scopes’ in a JSP.
Answer:
The various scopes in a JSP are enumerated below for your reference:-
(1) PageScope (<jsp:useBean … scope=”page” />: This is the default value, i.e., you get the same behavior even if you omit the scope attribute entirely. This default scope implies that in addition to being bound to a local variable, the bean object should be placed in the PageContext object for the duration of the current request. Storing the object like this ensures that the servlet code can access it by calling the getAttribute method on the predefined pageContext variable. Since every page and every request has a different PageContext object, using scope=”page” or omitting scope implies that the bean is not shared and thus a new bean will be created for each request.
(2) RequestScope (<jsp:useBean … scope=” request” />): This value implies that in addition to being bound to a local variable, the bean object should be placed in the HttpServletRequest object for the duration of the current request where it is retrievable through the getAttribute method.
(3) SessionScope (<jsp:useBean … scopes” session” />): This value implies that in addition to being bound to a local variable, the bean will be stored in the HttpSession object associated with the current request where it can be retrieved through the getAttribute method. Thus, this scope lets JSP pages easily perform session tracking.
(4) ApplicationScope (<jsp:useBean … scope-”application” />): This value implies that in addition to being bound to a local variable, the bean will be stored in the ServletContext available through the predefined application variable or by a call to getServletContext. The ServletContext is shared by all servlets and JSP pages in the Web application. Values in the ServletContext. can be retrieved through the getAttribute method.
Question 33.
Bring out the need for the MVC (Model View Controller) architecture.
Answer:
Servlets are great when your application requires a lot of real programming to accomplish its task. Servlets can manipulate HTTP status codes and headers, use cookies, track sessions, save information between requests, compress pages, access databases, generate JPEG images on the fly, and perform many other tasks efficiently and flexibly. But, generating HTML with servlets can be tedious and can yield a result that is hard to modify. That’s where JSP comes in. It allows you to write the HTML code in the normal manner, even using HTML-specific tools and putting your Web content developers to work on your JSP documents. JSP expressions, scriptlets, and declarations let you insert simple Java code into the servlet that results from the
JSP page and directives let you control the overall layout of the page. For more complex requirements, you can wrap Java code inside beans or even define your own JSP tags.
This all looks great. We seem to have everything. But, still, something is amiss. The assumption behind a JSP document is that it provides a single overall presentation. What if you want to give totally different results depending on the data that you receive? Scripting expressions, beans, and custom tags, although extremely powerful and flexible, do not overcome the limitation that the JSP page defines a relatively fixed, top-level page appearance. Similarly, what if you need complex reasoning just to find out the type of data that applies to the current situation? JSP is poor at this type of business logic.
The solution is to use both servlets and JSP. In this approach, known as the Model view controller (MVC) or Model 2 architecture, you let each technology concentrate on what it excels at. The original request is handled by a servlet. The servlet invokes the business logic and data access code and creates beans to represent the results (that is to say, the model). Then, the servlet decides what JavaServer Page is appropriate to present the particular results and forwards the request there (the JavaServer Page is the view). The servlet decides what business logic code applies and which JSP page should present the results (the servlet is the controller).
Question 34.
Elucidate the MVC (Model View Controller) Frameworks.
Answer:
The key desire behind the MVC approach is the desire to separate the code that creates and manipulates the data from the code that presents the data. The basic tools needed to implement this presentation-layer separation are standard in the servlet API. However, in very complex applications, a more elaborate MVC framework is sometimes beneficial. The most popular of these frameworks is Apache Struts discussed at length in one of the following chapters.
Although Struts is useful and widely used, you should not feel that you must use Struts in order to apply the MVC approach. For simple and moderately complex applications, implementing MVC from scratch with RequestDispatcher is straightforward and flexible. There is no need to get intimidated; in many situations, the basic approach is the best for the entire lifetime of your application. Even if you decide to use Struts or another MVC framework later, you will recoup much of your investment since most of your work will also apply to the elaborate frameworks.
Question 35.
How do you go about implementing MVC with RequestDispatcher?
Answer:
The most important point about MVC is the idea of separating the business logic and data access layers from the presentation layer. The syntax is quite simple and the steps required to implement MVC with RequestDispatcher are brought out succinctly below for your reference:-
(1) Define beans to represent the data: Beans are just Java objects that follow a few simple
conventions. The first step is to define beans to represent the results that will be presented to the user.
(2) Use a servlet to handle requests: In most cases, the servlet reads request parameters.
(3) Populate the beans: The servlet invokes business logic (application-specific code) or data-access code to obtain the results. These results are placed in the beans defined in step 1.
(4) Store the bean in the request, session, or servlet context: The servlet calls setAttribute on the request, session, or servlet context objects to store a reference to the beans that represent the results of the request.
(5) Forward the request to a JSP page: The servlet determines which JSP page is appropriate ” to the situation and uses the forward method of RequestDispatcher to transfer control to that JSP page.
(6) Extract the data from the beans: The JSP page accesses beans with jspniseBean and a scope matching the location of step 4. The page then uses jsp:getProperty to output the bean properties. The JSP page doesn’t create/modify the bean. It just extracts and displays data that the servlet created.
Question 36.
How do you go about securing Web applications?
Answer:
There are two major aspects to securing Web applications:-
(1) Preventing unauthorized users from accessing sensitive data: This process involves ‘act ess restriction’, that is, identifying which resources need protection and who should have access to them, and ‘authentication’, that is, identifying users to determine if they are one of the authorized ones. Simple authentication involves the user entering a username and password in an HTML form or dialog box while stronger authentication involves the use of X.509 certificates sent by the client to the server. This first aspect of Web security applies to virtually all secure applications. Even intranets at locations with physical access control usually require some sort of user authentication.
(2) Preventing attackers from stealing network data while it is in transit: This process involves the use of Secure Sockets Layer (SSL) to encrypt the traffic between the browser and the server. This capability is generally reserved for particularly sensitive applications or for particularly sensitive pages within a larger application. After all, unless the attackers are on your local subnet, it is exceedingly difficult for them to gain access to your network traffic.
These two security aspects are mostly independent. The approaches to access restriction are the same regardless of whether or not you use SSL. With the exception of client certificates (which apply only to SSL), the approaches to authentication are also identical whether or not you use SSL.
Within the Web application framework, there are two general approaches to this type of security:-
(1) Declarative Security. With declarative security, none of the individual servlets or JSP pages need any security-aware code. Instead, both of the major security aspects are handled by the server.
To prevent unauthorized access, you use the Web application deployment descriptor ‘ (web.xml) to declare that certain URLs need protection, and which categories of users should have access to them. You also designate the authentication method that the server should use to identify users. At request time, the server automatically prompts users for usernames and passwords when they try to access restricted resources,
automatically checks the results against a predefined set of usernames and passwords, and automatically keeps track of which users have been authenticated previously.
This process is completely transparent to the servlets and JSP pages. To safeguard network data, you use the deployment descriptor to stipulate that certain URLs should only be accessible with SSL. If users try to use a regular HTTP connection ‘
1 to access one of these URLs, the server automatically redirects them to the HTTPS (SSL) equivalent.
(2) Programmatic Security: With programmatic security, protected servlets and JSP pages ^ at least partially manage their own security. To prevent unauthorized access, each servlet or JSP page must either authenticate the user or verify that the user has been authenticated previously. To safeguard network data, each servlet or JSP page has to check the network protocol used to access it. If users try to use a regular HTTP connection to access some of these URLs, the servlet or JSP page must manually redirect them to the HTTPS (SSL) equivalent.
Question 37.
Outline the steps involved in Form-based authentication.
Answer:
Eight basic steps are involved in Form-based authentication:-
(1) Set up usernames, passwords, and roles: In this step, you designate a list of users and associate each with a password and one or more abstract roles (e.g., the normal user or ‘ administrator). This is a completely server-specific process. ;
(2) Tell the server that you are using form-based authentication; designate the locations of the login and login-failure page: This process uses the web.xml login-config element with an auth-method subelement of FORM and a form -login-config subelement that gives the location of the two pages. :
(3) Create a login page: This page must have a form with an ACTION of j_security_check, a ‘ METHOD of POST, a text field named j_username, and a password field named; j_password. ;
(4) Create a page to report failed login attempts: This page can simply say something like: “username and password not found” and perhaps give a link back to the login page.
(5) Specify which URLs should be password protected: For this step, you use the security constraint element of web.xml. This element, in turn, uses web-resource-collection and auth-constraint subelements. The first of these (web-resource-collection) designates the URL patterns to which access should be restricted, and the second (auth-constraint) specifies the abstract roles that should have access to the resources at the given URLs.
(6) List all possible abstract roles (types of users) that will be granted access to any resource: Each abstract role is declared using the security-role element. The security-role element contains the required role-name element, which contains the name of the abstract role.
(7) Specify which URLs Should be available only with SSL: If your server supports SSL, you can stipulate that certain resources are available only through encrypted LITTPS (SSL) connections. You use the user-data-constraint subelement of security-constraint for this j purpose.
(8) Turn off the invoker servlet: Security settings are based on URLs; so, you protect servlets by listing their URLs within web-resource-collection element. The servlet URLs, in turn, are normally defined with the url-pattern element of servlet-mapping. However, many servers also have a default servlet URL of the form http://host/webAppPrefix/ servIet/ServletName. If you have this capability enabled, there are now two URLs that can invoke each servlet: the URL registered in servlet-mapping and the default (invoker servlet) URL. Remembering to protect both addresses is too hard. Instead, disable the invoker servlet, either globally for your server, or by mapping the / servlet/ * pattern within your Web application.
Question 38.
Giv$ a brief description of the steps involved in creating servlet and JSP filters.
Answer:
Creating a basic servlet and JSP filter involves five steps:-
(1) Create a class that implements the Filter interface: Your class will need three methods: doFilter, init, and destroy. The doFilter method contains the main filtering code (step 2), the init method performs setup operations, and the destroy method does the cleanup operations.
(2) Put the filtering behavior in the doFilter method: The first argument to the doFilter method is a ServletRequest object. This object gives your filter full access to the incoming information, including form data, cookies, and HTTP request headers. The second argument is a ServletResponse-, it is mostly ignored in simple filters. The final argument is a FilterChain; it is used to invoke the servlet, JSP page, or the next filter in the chain as described in the next step.
(3) Call the doFilter method of the FilterChain object: The doFilter method of the Filter interface takes a FilterChain object as one of its arguments. When you call the doFilter method of that object, the next associated filter is invoked. If no other filter is associated with the servlet or JSP page, then the servlet or JSP page itself is invoked.
(4) Register the filter with the appropriate servlets and JSP pages: Use the filter and filter-mapping elements in the deployment descriptor (web.xml).
(5) Disable the invoker servlet: Prevent users from bypassing filter settings by using default servlet URLs.
Question 39.
List the event listeners that respond to Web application life-cycle events.
Answer:
There are eight kinds of event listeners that respond to Web application life-cycle events:-
(1) Servlet context listeners: These listeners are notified when the servlet context (i.e., the Web Application) is initialized and destroyed.
(2) Servlet context attribute listeners: These listeners are notified when attributes are added to, removed from, or replaced in the servlet context.
(3) Session listeners: These listeners are notified when session objects are created, invalidated, or timed out.
(4) Session attribute listeners: These listeners are notified when attributes are added to, removed from, or replaced in any session.
(5) Session migration listeners: These listeners are notified when the session objects are serialized and deserialized by the container. Usually, the serialization and deserialization of session objects occur when the container migrates the session objects from one machine to another.
(6) Session object binding listeners: These listeners are notified when the implementing object is added or removed from the session object.
(7) Request listeners: These listeners are notified when request objects are initialized and destroyed.
(8) Request attribute listeners: These listeners are notified when attributes are added to, removed from, or replaced in any request.
Question 40.
Give the full form of EL as related to JSP.
Answer:
Expression Language.
Question 41.
What do you understand by JSTL. Describe it briefly.
Answer:
JSTL is the JSP Standard Tag Library. It provides many useful tag libraries and has been universally accepted by the Java community. The most commonly used JSTL tag library is the core library, which contains the following tags: out, if,forEach,foretokens, choose, when, otherwise, set, remove, import, url, param, redirect, and catch.
Question 42.
Discuss any one of the JSTL tags briefly.
Answer:
Although any of the aforementioned tags can be discussed, here we shall only elucidate the c:set tag.
The c:set tag is used either for setting a scoped attribute or updating and creating bean properties and map values. The following are some of the common forms in which the c:set tag is used:-
<c:set var= “attributeName” valuer “someValue” />
<c:set target= “map” property= “clementKey” value= “elementValue” />
<c:set target= “bean” property= “name”>Arunesh Goyal</ c:set>
You may note that the c:set tag doesn’t specify the value attribute.
Question 43.
What areas does the JSTL cover?
ANS.
A particular set of tags has been collected into the JSP Standard Tag Library (JSTL) which is distributed along with the JSP framework. It covers the following areas:-
- Assigning to variables;
- Writing to the output stream;
- Catching exceptions;
- Conditionals;
- Iterations;
- URL construction;
- String formatting;
- SQL queries; and,
- XML manipulation.