Dev Notes – Servlet, JSP & MVC


Servlet

Servlet API (Application Programmable Interface)
Allows us to create dynamic web pages.
javax.servlet.http.HttpServlet
javax.servlet.http.HttpServletRequest
javax.servlet.http.HttpServletResponse

Questions & Answers

What is the difference between JSP and Servlets ?
JSP is used mainly for presentation only. A JSP can only be HttpServlet that means the only supported protocol in JSP is HTTP. But a servlet can support any protocol like HTTP, FTP, SMTP etc.

What is difference between custom JSP tags and beans?
Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. To use custom JSP tags, you need to define three separate components: the tag handler class that defines the tag’s behavior ,the tag library descriptor file that maps the XML element names to the tag implementations and the JSP file that uses the tag library

JavaBeans are Java utility classes you defined. Beans have a standard format for Java classes. You use tags

Custom tags and beans accomplish the same goals — encapsulating complex behavior into simple and accessible forms. There are several differences:

Custom tags can manipulate JSP content; beans cannot. Complex operations can be reduced to a significantly simpler form with custom tags than with beans. Custom tags require quite a bit more work to set up than do beans. Custom tags usually define relatively self-contained behavior, whereas beans are often defined in one servlet and used in a different servlet or JSP page. Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.

What are the different ways for session tracking?
Cookies, URL rewriting, HttpSession, Hidden form fields

What mechanisms are used by a Servlet Container to maintain session information?
Cookies, URL rewriting, and HTTPS protocol information are used to maintain session information

Difference between GET and POST
In GET your entire form submission can be encapsulated in one URL, like a hyperlink. query length is limited to 255 characters, not secure, faster, quick and easy. The data is submitted as part of URL.

In POST data is submitted inside body of the HTTP request. The data is not visible on the URL and it is more secure.

What is session?
The session is an object used by a servlet to track a user’s interaction with a Web application across multiple HTTP requests. The session is stored on the server.

What is servlet mapping?
The servlet mapping defines an association between a URL pattern and a servlet. The mapping is used to map requests to Servlets.

What is servlet context ?
The servlet context is an object that contains a information about the Web application and container. Using the context, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use.

What is a servlet ?
servlet is a java program that runs inside a web container.

Can we use the constructor, instead of init(), to initialize servlet?
Yes. But you will not get the servlet specific things from constructor. The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructor a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have access to a ServletConfig or ServletContext.

How many JSP scripting elements are there and what are they?
There are three scripting language elements: declarations, scriptlets, expressions.

How do I include static files within a JSP page?
Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase.

How can I implement a thread-safe JSP page?
You can make your JSPs thread-safe adding the directive <%@ page isThreadSafe=”false” % > within your JSP page.

What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?
In request.getRequestDispatcher(path) in order to create it we need to give the relative path of the resource. But in resourcecontext.getRequestDispatcher(path) in order to create it we need to give the absolute path of the resource.

What are the lifecycle of JSP?
When presented with JSP page the JSP engine does the following 7 phases.

 Page translation: -page is parsed, and a java file which is a servlet is created.
 Page compilation: page is compiled into a class file
 Page loading : This class file is loaded.
 Create an instance :- Instance of servlet is created
 jspInit() method is called
 _jspService is called to handle service calls
 _jspDestroy is called to destroy it when the servlet is not required.

What are context initialization parameters?
Context initialization parameters are specified by the <context-param> in the web.xml file, these are initialization parameter for the whole application.

What is a Expression?
Expressions are act as place holders for language expression, expression is evaluated each time the page is accessed. This will be included in the service method of the generated servlet.

What is a Declaration?
It declares one or more variables or methods for use later in the JSP source file. A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as semicolons separate them. The declaration must be valid in the scripting language used in the JSP file. This will be included in the declaration section of the generated servlet.

What is a Scriptlet?
A scriptlet can contain any number of language statements, variable or expressions that are valid in the page scripting language. Within scriptlet tags, you can declare variables to use later in the file, write expressions valid in the page scripting language, use any of the JSP implicit objects or any object declared with a <jsp:useBean>. Generally a scriptlet can contain any java code that are valid inside a normal java method. This will become the part of generated servlet’s service method.

There are three scripting language elements:
–declarations
–scriptlets
–expressions

Why are JSP pages the preferred API for creating a web-based client program?
Because no plug-ins or security policy files are needed on the client systems(applet does). Also, JSP pages enable cleaner and more module application design because they provide a way to separate applications programming from web page design. This means personnel involved in web page design do not need to understand Java programming language syntax to do their jobs.

Is JSP technology extensible?
YES. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.

Can we use the constructor, instead of init(), to initialize servlet?
Yes , of course you can use the constructor instead of init(). There’s nothing to stop you. But you shouldn’t. The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have access to a ServletConfig or ServletContext.

How can a servlet refresh automatically if some new data has entered the database?
You can use a client-side Refresh or Server Push.

The code in a finally clause will never fail to execute, right?
Using System.exit(1); in try block will not allow finally code to execute.

How many messaging models do JMS provide for and what are they?
JMS provide for two messaging models, publish-and-subscribe and point-to-point queuing.

What information is needed to create a TCP Socket?
The Local Systems IP Address and Port Number. And the Remote System’s IPAddress and Port Number.

What Class.forName will do while loading drivers?

It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS.

How to Retrieve Warnings?
SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object
SQLWarning warning = stmt.getWarnings();
if (warning != null)
{
while (warning != null)
{
System.out.println(“Message: ” + warning.getMessage());
System.out.println(“SQLState: ” + warning.getSQLState());
System.out.print(“Vendor error code: “); System.out.println(warning.getErrorCode());
warning = warning.getNextWarning();
}
}

How many JSP scripting elements are there and what are they?
There are three scripting language elements: declarations, scriptlets, expressions.

In the Servlet 2.4 specification SingleThreadModel has been deprecated, why?
Because it is not practical to have such model. Whether you set isThreadSafe to true or false, you should take care of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the page level.

What are stored procedures? How is it useful?
A stored procedure is a set of statements/commands which reside in the database. The stored procedure is pre-compiled and saves the database the effort of parsing and compiling sql statements everytime a query is run. Each database has its own stored procedure language, usually a variant of C with a SQL preproceesor. Newer versions of db’s support writing stored procedures in Java and Perl too. Before the advent of 3-tier/n-tier architecture it was pretty common for stored procs to implement the business logic( A lot of systems still do it). The biggest advantage is of course speed. Also certain kind of data manipulations are not achieved in SQL. Stored procs provide a mechanism to do these manipulations. Stored procs are also useful when you want to do Batch updates/exports/houseKeeping kind of stuff on the db. The overhead of a JDBC Connection may be significant in these cases.

How do I include static files within a JSP page?
Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. Do note that you should always supply a relative URL for the file attribute. Although you can also include static resources using the action, this is not advisable as the inclusion is then performed for each and every request.

Why does JComponent have add() and remove() methods but Component does not?

because JComponent is a subclass of Container, and can contain other components and jcomponents. How can I implement a thread-safe JSP page? – You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe=”false” % > within your JSP page.

How can I enable session tracking for JSP pages if the browser has disabled cookies?

We know that session tracking uses cookies by default to associate a session identifier with a unique user. If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking using URL rewriting. URL rewriting essentially includes the session ID within the link itself as a name/value pair.
However, for this to be effective, you need to append the session ID for each and every link that is part of your servlet response. Adding the session ID to a link is greatly simplified by means of of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if you are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input.

Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the browser; if so, the input URL is returned unchanged since the session ID will be persisted as a cookie. Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp, interact with each other.

Basically, we create a new session within hello1.jsp and place an object within this session. The user can then traverse to hello2.jsp by clicking on the link present within the page.Within hello2.jsp, we simply extract the object that was earlier placed in the session and display its contents. Notice that we invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is automatically appended to the URL, allowing hello2.jsp to still retrieve the session object. Try this example first with cookies enabled. Then disable cookie support, restart the brower, and try again. Each time you should see the maintenance of the session across pages.

Do note that to get this example to work with cookies disabled at the browser, your JSP engine has to support URL rewriting.
hello1.jsp
hello2.jsp
hello2.jsp
<%
Integer i= (Integer )session.getValue(“num”);
out.println(“Num value in session is “+i.intValue());

Servlets

Mechanisms that are built into the HTTP specification are Basic & Digest
Which is the first step before authorization? authentication
data integrity : It guarantees that the information is not altered during transmission between the client and the server.
A value of 0 or less ensures that the sessions are never invalidated.
Authorization : user has access to a particular resource. authentication : process of indentifying user.
For unauthenticated user : HttpServletRequest.getUserPrincipal() returns null or HttpServletRequest.isUserInRole() returns false.
public void doFilter(ServletRequest req, ServletResponse res,FilterChain chain)throws ServletException, IOException .
is the correct method signature.
Which method will be invoked when a ServletContext is destroyed? contextDestroyed of javax.servlet.ServletContextListner.

In which situations will a session be invalidated? request is not received from the client for longer than the session timeout period mentioned in web.xml. The servlet explicitly invalidates the session using invalidate method.
The session associated with a user can only be retrieved using the HttpServletRequest.getSession() method.
Which method is used to retrieve an attribute from a ServletContext? getAttribute() method returns an object. You can then cast the returned object.
If a Class implements HttpSessionBindingListener and that class is in session object.
If you invalidate the session object. Which method of that class invoked? • When a session is invalidated, all the session attributes are unbound from the session.
• if any attribute implements HttpSessionBindingListener,the valueUnbound() method will be called on the attribute.

• contextInitialized method will be invoked when ServletContext is created.

The following is the definition of the security-constraint element: <!ELEMENT security-constraint (display-name?, web-resource-collection+, auth-constraint?, user-data-constraint?)>
Which is a requirement of a distributable web application? Each JVM has a separate instance of a servlet context for each web application. So If you set attribute in ServletContext of one JVM , It is not visible in other JVM.


Published by:  mike    October 27th, 2015    Java  

Leave a Reply

Your email address will not be published. Required fields are marked *