Server side programming bt0083
- 1. Subject Name and Code: Server Side Programming-Theory and BT0083
Roll No.:1408005884
1. Describe java servlets and compare it with CGI.
Answer: Java servlets are small programs that run on server. As applets
dynamically extend the functionality of a web browser, Java servlets extend
the functionality of a web server. It is a web component managed by web
container, which generates dynamic content in web pages. Servlets are
protocol and platform independent server side components, written in java,
which dynamically extend Java-enabled Web servers. A servletin simple terms,
is a Java program under a Web server taking a ‘request’ object as an input and
responding back by a ‘response’ object.
The javax.servlet and javax.servlet.http packages provide interfaces and
classes for writing Servlets. All Servlets must implement the Servlet interface,
which defines the life cycle methods.
When implementing a generic service, you can use or extend the Generic
Servlet class provided with the Java Servlet API. The HttpServlet class provides
methods, such as do Get and do Post, for handling HTTP-specific services.
Servlets were designed to solve the problems with CGI and to create robust
server-side environments for Web developers. Like CGI, servlets also take
request from client, process those requests and give appropriate responses.
Servlets support multithreading that share resource among various requests.
So there is a need for creating a new process for every request.
Advantages of Servlets over CGI
Servlets
Support multithreading
Easy context switching between invocations
Faster to run when loaded
- 2. Share open DB connection using Connection Pooling with successive
invocations
Store state information in static variables.
Share access to state data each time the Servlet is run
Control concurrent address space to share states
CGI programs
Have to renew database connection each time they are run
Lack common address space to share states
Disadvantages of servlets over CGI processes
Slower only when being initially loaded
Cruder model of concurrency
Less robust- share common address space in JVM process
More complex to write, handle and configure
Because java Servlets are Java classes, you do not end up with huge
mess of Java, HTML and Java Script
The servlet engine does not always automatically reload Servlets.
2. Explain how to handle the form elements to retrieve data from form,
using servlet API. Give some examples.
Answer: HTML forms are used to create good GUI for user interaction. Here
you can create Textbox, checkboxes, radio buttons, combo box, and various
kinds of GUIs on the forms. After creating forms and GUI, the important step is
to consider is the methods to retrieve on form of these forms in servlet.
This data can be retrieved either by GET or POST method. In GET method data
will be appended in URL, while POST data will be send with the best solution.
It is very easy to retrieve data from form using Servlet API. One of the nioce
features of JAVA servlets is that all of this form parsing is handled by
automatically which was not available in CGI.
- 3. Example 1. Save this file in Get ParaDemo.html
<html>
<body> <form action = “/SIS/GetParaDemo” method = POST>
<table border = “1”>
<tr><td>Enter First name :</td>
<td> <input type = “input” name = “fname”/></td>
</tr>
<td>Enter Last name : </td>
<td><”input” name = “Iname”/></td>
</tr> <tr> <td>Enter Cell No: </td>
</tr> <tr> <td>
<input type = “submit”name = “btn”value = “Submit”/> </td> </tr>
</form> </body>
</html>
2. Save this file in GetParaDemo.java
Import javax.servlet.http.*;
Import javax.servlet.*;
Import java.io.*;
Public class GetParaDemo extends HttpServlet
{ public void doPost(HttpSevletRequestreq.HttpSevletResponseres) throws
ServletException.IOException
{ res.setContentType(“text/html”);
- 4. PrintWriter out = res.getWriter();
String first Name, lastName, cell;
firstName = req.getParameter(“fname”);
lastName = req.getParameter(“lname”);
cell = req.getParameter(“cell”);
out.println(“<html>”);
out.println(“<head> Getting Parameter Demo </head><br>”);
out.println((“<body>”);
out.println((“Wel-come Mr.”+firstName+” “+lastName + “<br>”);
out.println((“Your cell No : “+cell);
out.println((“</body>”);
out.println((“</html>”);
} }
User Input:
Enter First Name : Anil
Enter Last Name : Dudhe
Enter Cell NO : 9922558490
Output:
Getting Parameter Demo
Wel-come Mr.Anil Dudhe
Your cell No : 9922558490
Submit Reset
- 5. 3. Write a note on tracking the sessions using cookies Give advantages and
disadvantages of cookies.
Answer: Cookies are pieces of data that web server adds in the client browser
and later in the web server for tracking.
Cookies are useful for identifying clients as they return to the server.
Whenever a client requests a page, it sends along with the request any cookies
that it was previously asked to associate with that request. Each cookie has a
name and a value. In cookies enabled browser each server domain allows top
add up to 20 cookies of upto 4k per cookie.
To create a cookie, first you need to create an instance of Cookie class using its
constructor.
Cookie object-name = new Cookie(String name, String value);
This constructor allow user to pass cookie data in name/value pair. After that,
to add this cookie on the browser, you need to call addCookie(object-name)
method of HttpServletResponse.
For example:
HttpSession session = request.getSession(true);
String id = session.getId();
Cookie cookies = new Cookie(“SessionID”, id);
Response.addCookie(cookies);
getID()
This method gives session id, which is unique for every instance of the browser.
setMaxAge() method
This method specify the maximum age of cookie.
- 6. Advantages of Cookies
1. Cookies are stored on the client computer and can be read by the server
after a request for a page is posted. Therefore, no server resource is
involved in maintaining the cookie.
2. The cookies are the best way to customize your navigation on internet.
3. The best example of cookie is their usage by advertising companies. They
can download a cookie onto your computer to keep track of your surfing
habits and can then tell you about the products that will be in relevance to
your taste.
4. Cookies are non-executable, so they will not spread viruses.
5. Cookies are light weighted, because they are simple text files storing key-
value pairs and consume less memory space.
Disadvantages of cookies
1. Cookies have a limited size i.e., upto 4kb, so yopu can’t store large amount
of data in cookie.
2. Some sites or some malicious hackers can misuse cookies.
3. Because cookies are stored as plain text on to a computer that means that
they can be edited and read by anyone unless and until the site thinks of
your privacy and encrypts the data.
4. Cookies can be stolen via some cross site scripting; the Hacker exploits a
vulnerable Web application and simply applies a JavaScript code to use
your details for his own malicious purposes.
5. If you delete cookies from your hard drive, it will be difficult for servers to
trace your surfing or spending habits.
4. Explain the two JSP architectures.
Answer: Thereare two general approaches you can take when developing web
applications using JSP.
I. Page-centric (Model 1) and
II. Servlet-centric architecture or N-tier architecture (Model 2)
- 7. I. Model-1 Architecture (Page-centric)
Page-centric architecture is the most common and easiest methodology for
developing dynamic Web applications. User can access JSP pages directly,
which means the user request is handled by JSP pages. This is also called as
Model-1 architecture.
The JSP contains embedded code and tags to access the model JavaBeans.
Here also JSP separates presentation from business logic, because all data
access is performed using beans.
The JavaBeans contain logic to connect to the middle tier or directly to the
database using JDBC. The JSP is then rendered as HTML using the data in the
Model JavaBeans and other Helper classes and tags and replies back to
browser as an output.
Disadvantages:
1. Even if there is separation between presentation and business logic, it is
only good for small application.
2. JSP allows Java code which is difficult to maintain, if the application is
extended.
3. Application control is decentralized in Model 1 architecture since the next
page to be displayed is determined by the logic embedded in the current
page.
All this lead us to use Model 2 architecture for designing JSP pages.
ii. Model-2 Architecture (Servlet-Centric)
Model-2 architecture is based on Model-View-Controller (MVC) pattern, which
separates business logic from home presentation. In MVC business logic is
handled by controller and presentation is handled by JSP. This is also Called as
Servlet-Centric, because every request is handled or controlled by Servlet
which acts as Controller and is responsible for request processing and the
creation of object used by the JSP, as well as deciding, depending on the user’s
actions, which JSP page to forward the request to. JavaBeans manages
- 8. information and notify view when there is update in the information. It
contains only data and functionality that are related by a Common purpose. So
the user can create manageable code and layer in Web application. The main
advantage of this approach is clear separation between business logic and
presentation.
Advantages:
1. Creates manageable code and layer architecture in Web application by
separating business logic and presentation.
2. Creates reusable code.
3. Provides scalability.
5. Draw and explain the diagram of custom tag life cycle.
Answer:
{SKIP_BODY} [EVAL_BODY_INCLUDE]
[SKIP_BODY] [EVAL_BODY_AGAIN]
The doStartTag() Method
This method is called once the start tag is processed. This method must return an
int value that tells the JSP how to process the tag body. The returned value must
is one of the following:
Tag. SKIP_BODY the tag body must be ignored. The TLD should define the
<body-content> tag as empty.
doStartTag()
doInitBody()
doAfterBody()
doendTag()
release()
- 9. Tag. EVAL_BODY_INCLUDE the body tag must be evaluated and included in
the JSP page.
The TLD should define <body-content> tag as JSP for tags that extemnd Tag
support, or JSP or tagdependent for tags that extend BodyTagSupport.
The doEndTag() Method
This method is called once when the end tag is processed. This method must
return an int value indicating how the remainder of the HSP page should be
processed:
Tag. EVAL-PAGE Evaluates the rest of the page
Tag. SKIP_PAGE Stop processing the page after this tag.
Where a tag has an empty body, the doEndTag() method is still called the
doStartTag() method.
The release() Method
This method is called once when the JSP has finished using the tag and is used to
allow the tag to release any resources it may have acquired. This method’s return
type is valid.
The doAfterBody() Method
This method is called after the tag body has been processed and before the
doEndTag() method is called. This method is only called for classes that
implement iteration Tag or Body Tag. Itmust return one of the following values to
the JSP page indicating how the tag body should be processed:
IterationTag. EVAL_BODY_AGAIN This value is used to inform the page that
the tag body should be processed once more. The JSP processing will read
and process the tag body and call the doAfterBody () method once more
after tha body has been processed again.
- 10. 6. Describe the process of deactivating individual expression language
statement with an example.
Answer: Value to page directive attribute of isEnabled is given as false in order
to disable EL evaluation in an individual page
<%@page isEnabled = “false”%>
is ELEnabled is a new attribute in JSP 2.0 and employing this in server that
supports only JSP 1.2 will lead to an error. So, you cannot use this method to
let the same JSP page to run in both new and old servers unmodified. As a
result jsp property group element is generally superior option than is
ELEnabled attribute.
Deactivating Individual Expression Language Statements:
Assume that JSP 1.2 page enclosing ${ and you need this page to be used in
multiple places to be exact in this page is to be used in both JSP 1.2 web
applications and in that web application that encloses EL pages. User should be
capable enough to put this page in any web application without any
modification to web.xml file. Even though it is a doubtful situation, it could
happen. In such a situation simply substitute $ with HTML character entity
equivalent to ISO 8859 1 value of $(36).
$(blah) So, user can substitute ${with ${throughout the page.
For an instance, ${blah} will display ${blah}
Though character entity is decoded to $ by browser not by server so this
method will only has affect when you are outputting HTML to web browser.
Lastly, assume that you have JSP2.0 page enclosing either literal ${string and
EL statements in such scenario use in front of $.
For an instance,
$(1+1) is $(1+1)
Result = $(1+1) is 2