Monday, April 22, 2013

B.Sc. IT BT0083 (Semester 4, Server Side Programming) Assignment


Spring 2013
Bachelor of Science in Information Technology (BScIT) – Semester 4 BT0083 – Server Side Programming - Theory – 4 Credits
(Book ID: B1088)
Assignment Set (60 Marks)


1.What is HTTP? How does it works?
Ans.-   HTTP, the Hypertext Transfer Protocol, is the application-level protocol that is used to transfer data on the Web. HTTP comprises the rules by which Web browsers and Servers exchange information. Although most people think of HTTP only in the context of the World-Wide-Web, it can be, and is, used for other purposes, such as distributed object management systems.
            HTTP is a request-response protocol. For example, a web browser initiates a request to a server, typically by opening a TCP/IP connection. The request itself comprises
·        A request line,
·        A set of request headers, and
·        An entity
The server sends a response that comprises
·        A status line,
·        A set of resonse headers, and
·        An entity
The entity in the request or response can be though of simply as the payload, which may be binary data. The other items are readable ASCII characters. When the response has been completed, either the browser or the server may terminate the TCP/IP connection, or the browser can send another request.

2.Differentiate ServletContext and ServletConfig.
Ans.-   The Servlet context is rooted at a known path within a web container. For example, if we have a stores application, it could exist under the context /WebData. Therefore if the application contained an HTML file called First.thml if would be assessable at http://localhost:8080/WebData/First.html. All requests that begin with /WebData request path, known as the context path, are routed to the web application associated with the Servlet context.
The ServletConfig object is a parameter that can be passed into the init method of the Servlet used to provide initial configuration information for Servlets. Configuration information for a Servlet may consist of a string or a set of string values included in the <init-param> tag of web.xml declaration. The major benefit of this functionality is that it allows a Servlet to have initial parameters outside of the compiled code and changed without needing to recompile the Servlet.
The following table describes the differences between ServletContext and ServletConfig.

ServletContext
ServletConfig
It represent whole web application running on particular JVM and common for all the servlet
ServletConfig object represent single servlet
It’s like global parameter associated with whole application
It’s like local parameter associated with particular servlet
ServletContext has application wide scope so define outside of servleting in web.xml file
It’s a name value pair defined inside the servlet section of web.xml file so it has servlet wide scope
getServletContext() method is used to get the context object
getServletConfig() method is used to get the config object
To get the MIME type of a file or application session related information is stored using ServletContext object
For example shopping cart of a user is a specific to particular user so here we can use ServletConfig

3.What is Web Server? What are the various Web Servers?
Ans.-   Web Servers are computers that deliver (serves up) Web pages. Every web server has an IP address and possibly a domain name.

A.    Apache Web Server:- Free and the most popular web server in the world developed by the Apache Software Foundation. Apache Web Server is an open source software and can be installed and made to work on almost all operating systems including Linux, Unix, Windows, FreeBSD, Mac OS X and more.
B.     Apache Tomcat:- The Apache Tomcat has been developed to support servlets and JSP scripts. Though it can serve as a standalone server, Tomcat is generally used along with the popular Apache HTTP web server or any other web server. Apache Tomcat is free and open source and can run on different Oss like Linux, Unix, Windows, Mac OS X, Free BSD.
C.    Microsoft’s Internet Information Services(IIS) Windows Server:- IIS Windows Web Server has been developed by Microsoft Inc. It offers higher levels of performance and security than its predecessors. It also comes with a good support from the company and is the second most popular server on the web.
D.    Nginx Web Server:- Free open source popular web server including IMAP/POP3 proxy server. Hosting about 7.5% of all domains worldwide, Nginx is known for its high performance, stability, simple configuration and low resource usage. This web server doesn’t use threads to handle rewquests rather a much more scalable event-driven architecture which uses small and predictable amounts of memory upper load.
E.     lighttpd:- lighttpd, pronounces “lightly”, is a free web server distributed with the FreeBSD operating system. This open source web server is fast, secure and consumes much less CPU power. Lighttpd can also run on Windows, Mac OS X, Linux and Solaris operating systems.
F.     Jigsaw:- jigsaw comes from the World Wide Web Consortium. It’s open source and free and can run on various platforms like Linux, Unix, Windows, Mac OS X and FreeBSD, etc. Jigsaw has been written in Java and can run CGI scripts and PHP programs.
G.    Klone:- Klone, from KoanLogic Srl, includes a web srever and an SDK for crating static and dynamic web sites. It’s a web application development framework especially for embedded systems and appliances. No additional components are required when using Klone.
H.    Oracle Web Tier:- Includes two web server options with reverse proxy and caching solutions that lead to quick serving of web pages and easy handling of even the most demanding http traffic. The iPlanet Web Server, for example, is a high-performance server with enhanced security and multithreaded architecture that scales well on modern 64-bit multiprocessors.
I.       Zeus Web Server:- The Zeus web server runs on Linux and FreeBSD operating systems among others. It has been developed by Zeus technology Ltd. And is known for its speed, reliability, security and flexibility. The web server is used on some of the busiest web sites of the world. Zeus web server is not free and costs more than a thousand pounds.

4.What are attributes? Explain tags with attributes.
Ans.-   Attributes are used to pass information into a custum tag to configure the behavior of the tag. Tag attributes are like XML or HTML attributes and are name/value pairs of data. The values must be quoted with single or double quotes.
            Tags with Attributes
Tag
description
Attribute
Introduces an attribute definition in the <tag> component of the TLD.
Name
Defines the attribute name.
Required
Followed by true if the attribute must be provided; otherwise, false.
Trexprvalue
Defines whether the attribute can be specified with a request time expression. Set this element to true to allow JSP scripting values to be used for the attribute; otherwise, the value must be a string literal.
Type
Defines the type of an attribute and defaults to java.lang.String. This element must be defined if the rtexprvalue is true and the attribute value is not a String.


5. What are the ways of handling exception? Explain any two in detail.
Ans.-   In a Java Servlet, an exception is represented by an instance of the class-----
Javax.servlet.ServletException

There are many ways of handling exceptions in a Servlet, which are------
            1.Using the web.xml file
            2.Using a RequestDispatcher
            3.Using sendError() method of HttpServletResponse.
            4.Using the Web Application Log

Here explaining two ways of handling exception
1.      Using the web.xml file:-
Handling errors can be defined declaratively using the sub tag of <error-page> in web.xml file. There are two ways in this declaration.
A.    <error-code> tag of <error-page>
If the servlet chooses to handle the error codes, <error-code> tag that is within <error-page> tag is used to identify the value.
Following is a code snippet that demonstrates handling of Forbidden error 403 in a servlet. Whenever this exception is encountered, the JSP, Servlet or HTML mapped in <location> tag is displayed.
The file Service.html can be a simple HTML page that displays a customized message for the exception.
The web.xml mapping for handling error-code:
Declaration in web.xml

<web-app>
.......
<error-page> <error-code>403</error-code>
<location>/Service.html</location>
</error-page>
........
</web-app>
Servlet code showing the use of 403
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class form extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException,ServletException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String uName = req.getParameter("name");
String password = req.getParameter("pw");
if(uName.equals("Raj") && password.equals("Pune"))
res.sendRedirect("/Sample/Menu.html");
out.close();
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException,ServletException {
doGet(req,res);
}
}
If you are not an authorized user, the statement will be executed showing the output as in following figure:

 Output if, there is error.

Service.html file
<html>
<body>
Internal Server Error 500
<br><br>
Possibilities :
Check variable/parameter
</body>
</html>

<exception-type> tag of <error-page>
If, however, the page chooses to handle an exception, <exception-type> tag that is within <error-page> tag is used.
In <exception-type> we specify the type of exception. Following snippet code shows how to use exception type.

Servlet Code ExceptionServlet.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class ExceptionServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws IOException,ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
ServletContext sc = getServletContext();
int n1= Integer.parseInt(request.getParameter("fnum"));
int n2 = Integer.parseInt(request.getParameter("snum"));
int result =0;
result = n1 / n2 ; // might throw exception
out.println("<h1> Dividion Result </h1>"+ result);
out.close();
}
}


Error tag in web.xml
<error-page>
<exception-type>java.lang.ArithmeticException</exception-type>
<location>/Error.html</location>
</error-page>

Error.html file
<html>
<body>
<h1> Check possibilities</h1>
<li> Arithmetic type of exception </li>
<li> Number Format type of exception </li></body>
</body>
</html>

User Input Screen

User Output

2.      Using sendError() method of HttpServletResponse:-
When sendError method is called, the servlet container sends an error page to the browser. This method uses Mnemonic Constant with respect to the status code as mentioned in the following table. The string message that can be set in sendError() is ignored if the error code has a mapping file configured in web.xml. Otherwise it will be displayed in the browser.
In the following example, the error 404 indicated by SC_NOT_FOUND is mapped to the file 404Error.html in the file web.xml

Example:
response.sendError (response. SC_NOT_FOUND, ”Resource Not Found”);
Mnemonic Constant
Code
Default Message
Meaning
SC_OK
200
OK
This is the default status code which indicates successful request
SC_NO_CONTENT
204
No Content
This code returns body without content and used to avoid the “Document contains no data” error message.
SC_MOVED_PERMANENTLY
301
Moved Permanently
This code is used when the requested resource has permanently moved to a new location. Most browsers automatically access the new location.
SC_MOVED_TEMPORARILY
302
Moved Temporarily
The requested resource has temporarily moved to another location, but future references should still use the original URL to access the resource. The new location is given by the Location Header.
SC_UNAUTHORIZED
401
Unauthorized
The request lacked proper authentication. Used in conjunction with the WWW-Authenticate and Authorization headers.
SC_NOT_FOUND
404
Not Found
The requested resource was not found or is not available.
SC_INTERNAL_SERVER_ERROR
500
Internal Server Error
An unexpected error occurred inside the server that prevented it from fulfilling the request.
SC_NOT_IMPLEMENTED
501
Not Implemented
The server does not support the functionality needed to fulfill the request.
SC_SERVICES_UNAVAILABLE
503
Service Unavailable
The service (server) is temporarily unavailable but should be restored in the future. If the server knows when it will be available again, a Retry-After header may also be supplied.

The status codes fall into five general categories:
            1. 100-199 Informational
            2. 200-299 Successful
            3. 300-399 Redirection
            4. 400-499 Incomplete.
            5. 500-599 Server Error

6. Explain the need for Model View Controller (MVC).
Ans.-   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 flexibly and efficiently. But, generating HTML with Servlets can be tedious and can yield a result that is hard to modify.
That’s where JSP comes in: as illustrated in Figure 14.1, JSP lets you separate much of the presentation from the dynamic content. That way, you can write the HTML 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.



Simple application or
small development team

Complex application or large development team.

Ø  Call Java Code Directly. Place all Java code in JSP page. Appropriate only for very small amounts of code.
Ø  Call Java Code Indirectly. Develop separate utility classes. Insert into JSP page only the Java code needed to invoke the utility classes.
Ø  Use Beans. Develop separate utility classes structured as beans. Use jsp:useBean, jsp:get roperty, and jsp:setProperty to invoke the code.
Ø  Use the MVC Architecture. Have a Servlet respond to original request, look up data, and store results in beans. Forward to a JSP page to present results. JSP page uses beans.
Ø  Use the JSP Expression Language. Use shorthand syntax to access and output object properties. Usually used in conjunction with beans and MVC.
Ø  Use Custom Tags. Develop tag handler classes. Invoke the tag handlers with XML-like custom tags.


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, don’t overcome the limitation that the JSP page defines a relatively fixed, top-level page appearance.
Similarly, what if you need complex reasoning just to determine 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 Java Server Pages. 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’s the model). Then, the Servlet decides which JSP page is appropriate to present those particular results and forwards the request there (the JSP 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).

MVC Frameworks
The key motivation 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 and are the topic of this unit.
However, in very complex applications, a more elaborate MVC framework is sometimes beneficial. The most popular of these frameworks is Apache Struts. 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 Request Dispatcher is straightforward and flexible. Do not be intimidated: go ahead and start with the basic approach.
In many situations, you will stick with the basic approach for the entire life of your application. Even if you decide to use Struts or another MVC framework later, you will recoup much of your investment because most of your work will also apply to the elaborate frameworks.

Architecture or Approach?
The term “architecture” often connotes “overall system design.” Although many systems are indeed designed with MVC at their core, it is not necessary to redesign your overall system just to make use of the MVC approach. It is quite common for applications to handle some requests with Servlets, other requests with JSP pages, and still others with Servlets and JSP acting in conjunction as described in this unit. Do not feel that you have to rework your entire system architecture just to use the MVC approach: go ahead and start applying it in the parts of your application where it fits best.

For More Assignments Click Here

1 comment:

  1. SEGA GENESIS - GAN-GAMING
    SEGA GENESIS. GENESIS-HANDS. kadangpintar Genesis https://octcasino.com/ (JP-EU). NA. NA. NA. 바카라 사이트 SEGA GENESIS-HANDS. NA. apr casino SEGA GENESIS. https://sol.edu.kg/ NA. GENESIS-HANDS. NA.

    ReplyDelete