Professional Documents
Culture Documents
SESSION(2017-2018)
ASSIGNMENT OF J2EE
SUBMITTED BY-
Enrollment no.-01615124416
Assignment -1
Q.1 Differentiate between two tier, three tier and n-tier architecture.
Ans- The J2EE platform is a multi-tiered system. A tier is a logical or functional partitioning of a system.
1) 2-Tier Architecture
User Interface/Display is Client --> Data Base, Data and Business Logic is Database
Def:The 2-tier is based on Client Server architecture. The two-tier architecture is like client server
application. The direct communication takes place between client and server. There is no intermediate
between client and server. Because of tight coupling a 2 tiered application will run faster.
Architecture:
The above figure shows the architecture of two-tier. Here the direct communication between client and
server, there is no intermediate between client and server.
On client application side the code is written for saving the data in the SQL server database. Client sends
the request to server and it process the request & send back with data. The main problem of two tier
architecture is the server cannot respond multiple request same time, as a result it cause a data integrity
issue.
Advantages:
1. In two tier architecture application performance will be degrade upon increasing the users.
2. Cost-ineffective
2) 3-Tier Architecture
User Interface/Display is Client -->Business or Database Logic --> Data Base, Data is Database
Def:3-tier architecture typically comprises a presentation tier, a business or data access tier, and
a data tier.
Architecture:
1) Client layer
2) Business layer
3) Data layer
1) Client layer:
It is also called as Presentation layer which contains UI part of our application. This layer is used for the
design purpose where data is presented to the user or input is taken from the user. For example
designing registration form which contains text box, label, button etc.
2) Business layer:
In this layer all business logic written likes validation of data, calculations, data insertion etc. This acts as
a interface between Client layer and Data Access Layer. This layer is also called the intermediary layer
helps to make communication faster between client and data layer.
3) Data layer:
In this layer actual database is comes in the picture. Data Access Layer contains methods to connect
with database and to perform insert, update, delete, get data from database based on our input data.
Advantages
Disadvantages
1. Increase Complexity/Effort
User Interface/Display is Client -->Business or Database Logic --> Data Base, Data is Database
Client:
Middle Tier:
a) HTML, CSS, GIF Files etc (static content) available in Web Server
Databases like RDBMS, XML, EXCEL, ERP &CRM systems, Legacy Systems etc
Advantages:
c. It is possible to make changes on the presentation level without affecting the other two (business or
data access layer)
e. Since the client doesn’t have direct access to the database business logic is more secure
f. When one tier fails there is no data loss, because you are always secure by accessing the other tier.
Disadvantages:
c. The physical separation of the tiers may affect the performance between the three
Ans-
J2EE Architecture
J2EE multi-tiered applications are generally considered to be three tiered applications because they are
distributed over three different locations:
client machines
the J2EE server machine
the database or legacy machines at the back end
Three-tiered applications that run in this way extend the standard two-tiered client and server
model by placing a multithreaded application server between the client application and back-
end storage.
J2EE Containers
The application server maintains control and provides services through an interface or
framework known as a container.
There are five defined container types in the J2EE specification.
Three of these are server-side containers:
1. The server itself, which provides the J2EE runtime environment and the other two
containers.
2. An EJB container to manage EJB components.
3. A Web container to manage servlets and JSP pages.
J2EE Components
Model The model represents the state (data) and business logic of the application.
View The view module is responsible to display data i.e. it represents the presentation.
Controller The controller module acts as an interface between view and model. It intercepts all the
requests i.e. receives input and commands to Model / View to change accordingly.
Ans-
Def: Servlets came into the Java world to help develop Web Applications. Web applications run over the
web and are consumed by end user. It should not be confused with Web Services, which are consumed
by a program as opposed to end user. A typical example of Web Application would be a Shopping Kart
Application, which can be accessed over HTTP protocol from a web browser.
1. A Servlet is a Java program that runs on a Web Container. The Web Container is capable of
handling HTTP requests and responses.
2. Servlets act as an inter-mediatory interface between HTTP requests originated from Web
Browsers (IE, Chrome etc) and Java Applications hosted on Application Servers.
3. Servlet runs as a light-weight thread instead of a separate OS process. This is opposed to a CGI
script in which a new OS process is created for each request, making it heavy-weight and
impacting performance.
4. Servlets can be used to collect form inputs from a page
5. Servlet specification is released by Oracle, which vendors implement to create their own Web
Containers.
6. Most popular Open Source Web Containers are: Apache Tomcat, Jetty and Glassfish.
7. A Servlet can run on any web container as it is developed using a common Servlet-API.
8. We must import javax.servlet.*; javax.servlet.http.*; in order to create a servlet.
Servlet Container
1. The most popular Servlet Container today is Tomcat. It is very light-weight and easy to develop
and deploy applications on Tomcat.
2. Originally Tomcat was built by Sun MicroSystems, and later was handed over to the Apache
Software Foundation in October 1999.
3. It can be easily integrated with all popular IDE's (like Eclipse, NetBeans etc) and promotes ease
of development.
1. init() method:-
2. service()method:-
The servlet container calls the service() method to handle requests coming from the client or
browsers and to write the formatted response back to the client.
The service() method checks the HTTP request type such as GET ,POST etc and calls doGet,
doPost etc.
public void service (ServletRequest request,
doGet() Method:-
GET is HTTP method. it works to tell server to get a resource and send it server.
it should be handled by doGet() method.
doPost() Method:-
POST ,you can request something and at same time send form data to server.
it should be handled by doPost() method.
3. destroy() method :-
The destroy() method is called only one time at the end of the life cycle of a servlet.
It gives opportunity to clean up any resource such as Memory,thread etc.
Ans-Generic servlet
Des:
It is abstract class.
GenericServlet implements the Servlet, ServletConfig, Serializable interfaces.
It implements some lifecycle methods.
GenericServlet may be directly extended by a servlet, Even though it's more common to extend
a protocol-specific subclass such as HttpServlet.
Method Description
void log(String s, It writes an explanatory message and a stack trace for a given Throwable exception
Throwable e) to the servlet log file.
HTTP servlet
Des:
It is an abstract class and extends the Generic Servlet.
To create your own Servlet, you need to subclass HttpServlet.
A subclass of HttpServlet must override at least one methods listed below:
Method Description
protected void doGet( Called by the server through service() to allow a servlet to handle a GET request.
HttpServletRequest req, Parameters: Object HttpServletRequest(req) that contains the request the client has
HttpServletResponse made of the servlet. Object of HttpServletResponse(resp) that contains the response
resp) the servlet sends to the client
throws
ServletException,
IOException
protected void doPost( Called by the server through service() to allow a servlet to handle a POST request.
HttpServletRequest req, Parameters: Object of HttpServletRequest(req) that contains the request the client has
HttpServletResponse made of the servlet. Object of HttpServletResponse that contains the response the
resp) servlet sends to the client.
throws ServletException,
IOException
Method Description
protected void doPut( Called by the server to allow a servlet to handle a PUT requests. Parametrs: Object of
HttpServletRequest req, HttpServletRequest(req)that contains the request the client made of the servlet.
HttpServletResponse Object of HttpServletResponse(resp) that contains the response the servlet returns to
resp) the client.
throws ServletException,
IOException.
protected void doTrace( Called by the server to allow a servlet to handle a TRACE request.
HttpServletRequest req,
HttpServletResponse
resp)
throws ServletException,
IOException
protected void service( Receives standard HTTP and responds by calling doXXX() method defined in the
HttpServletRequest req, servlet.
HttpServletResponse
resp)
throws ServletException,
IOException
doOptions protected Called by the server to allow a servlet to handle a OPTIONS request.
void doOptions(
HttpServletRequest req,
HttpServletResponse
resp)
throws ServletException,
IOException
HttpServlet GenericServlet
HttpServlet defines a HTTP protocol specific GenericServlet defines a generic, protocol-independent
servlet. servlet.
Ans-Des:
HTTP is a stateless protocol ,where each request and response both is independent of other web
interactions.
it is necessary to save state information so that information can be collected from several
interactions between a browser and a server. Sessions provide such a mechanism.
A new session is created if one does not already exist.
It is required to implement session management capabilities that link both the authentication
and access control modules commonly available in web applications.
Approaches to Session-Tracking:-
1. Session API
2. URL -rewriting
3. Cookies
4. Hidden Form Field
Method Description
HttpSession This method is use to reterive the current the HttpSession that is associated with
s=request.getSession() user. if session does not exist,then a session can be created by using getSession(true)
boolean b=s.IsNew(); returns the Value true If the new Session ID has been created and has not been sent
the client.
long l=s.getCreationTime(); This function returns the time when the session was created in miliseconds.
long This function returns the previous time a request was made with same sessionId.
l=s.getLastAccessedTime();
Method Description
1. It times out.
2. You call invalidate() on the session object.
3. The application goes down (Crashes or is undeployed).
2. URL-rewritting
If Client Cookie is disable so Session API fails .
If client won't take cookies, you can use URL rewriting as a back up.
URL rewriting is a better way to maintain sessions when the browsers don't support cookie So
URL rewriting is a better way to maintain sessions
Now put the session ID with URL.
It likes http://abc.com/email.do; jsessionid="0AAB678C99D1E415",
What is Cookie?
Cookies are small text files that are used by a Web server to keep track of users.
A cookie has value in the form of key-value pairs.
They are created by the server and sent to the client with the HTTP response headers.
javax.servlet.http.Cookie class is used to represent a cookie.
To get cookie:
Cookie ck[]=request.getCookies();
A server can send one or more cookies to the client.
A web-browser, which is the client software, is expected to support 20 cookies per host and the
size of each cookie can be a maximum of 4 bytes each.
c.setMaxAge(int); This method is used to specify the maximum amount of time for which the
client browser retain the cookie value.
Ans-
Def:The jsp directives are messages that tell the web container how to translate a JSP page into the
corresponding servlet.
page directive
include directive
taglib directive
The page directive defines attributes that apply to an entire JSP page.
1)import
The import attribute is used to import class,interface or all the members of a package.It is similar to
import keyword in java class or interface.
Example of import attribute
<html>
<body>
</body>
</html>
2)contentType
The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type of the HTTP
response.The default value is "text/html;charset=ISO-8859-1".
</body>
</html>
3)extends
The extends attribute defines the parent class that will be inherited by the generated servlet.It is rarely
used.
4)info
This attribute simply sets the information of the JSP page which is retrieved later by using
getServletInfo() method of Servlet interface.
</body>
</html>
The web container will create a method getServletInfo() in the resulting servlet.For example:
public String getServletInfo() {
return "composed by Sonoo Jaiswal";
}
5)buffer
The buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP page.The
default size of the buffer is 8Kb.
</body>
</html>
6)language
The language attribute specifies the scripting language used in the JSP page. The default value is "java".
7)isELIgnored
We can ignore the Expression Language (EL) in jsp by the isELIgnored attribute. By default its value is
false i.e. Expression Language is enabled by default. We see Expression Language later.
8)isThreadSafe
Servlet and JSP both are multithreaded.If you want to control this behaviour of JSP page, you can use
isThreadSafe attribute of page directive.The value of isThreadSafe value is true.If you make it false,
the web container will serialize the multiple requests, i.e. it will wait until the JSP finishes responding
to a request before passing another request to it.If you make the value of isThreadSafe attribute like:
The web container in such a case, will generate the servlet as:
The errorPage attribute is used to define the error page, if exception occurs in the current page, it will
be redirected to the error page.
</body>
</html>
10)isErrorPage
The isErrorPage attribute is used to declare that the current page is the error page.
Note: The exception object can only be used in the error page.
</body>
</html>
Q.7 what are the design strategies of JSP.
Ans-Design Strategies
Des-
• Many dozens of design strategies have been developed for web applications.
2. Dispatcher : Requests are sent to JSPs or servlets that then forward the requests to another JSP or
servlet.
In both cases, the goal is to separate logic from presentation and to separate as many concerns in the
logic as possible.
• Two variants :
– Page-View
– Page-View with a Bean.
• Does not scale up very well to large web sites.
• Three versions
– Mediator-View
– Mediator
-Composite View
–Service to Workers
(2-A) Mediator-View Design
• The Mediating JSP sends requests to a JSP.
• The JSP sets and gets beans and creates a response page.
Ans-Des:
In this example, we are creating the struts 2 example without IDE. We can simply create the struts 2
application by following these simple steps:
The directory structure of struts 2 is same as servlet/JSP. Here, struts.xml file must be located in the
classes folder.
2) Create input page (index.jsp)
This jsp page creates a form using struts UI tags. To use the struts UI tags, you need to specify uri /struts-
tags. Here, we have used s:form to create a form, s:textfield to create a text field, s:submit to create a
submit button.
index.jsp
In struts 2, StrutsPrepareAndExecuteFilter class works as the controller. As we know well, struts 2 uses
filter for the controller. It is implicitly provided by the struts framework.
web.xml
This is simple bean class. In struts 2, action is POJO (Plain Old Java Object). It has one extra
method execute i.e. invoked by struts framework by default.
Product.java
1. package com.javatpoint;
2.
3. public class Product {
4. private int id;
5. private String name;
6. private float price;
7. public int getId() {
8. return id;
9. }
10. public void setId(int id) {
11. this.id = id;
12. }
13. public String getName() {
14. return name;
15. }
16. public void setName(String name) {
17. this.name = name;
18. }
19. public float getPrice() {
20. return price;
21. }
22. public void setPrice(float price) {
23. this.price = price;
24. }
25.
26. public String execute(){
27. return "success";
28. }
29. }
1. package com.javatpoint;
2.
3. public class Product {
4. private int id;
5. private String name;
6. private float price;
7. public int getId() {
8. return id;
9. }
10. public void setId(int id) {
11. this.id = id;
12. }
13. public String getName() {
14. return name;
15. }
16. public void setName(String name) {
17. this.name = name;
18. }
19. public float getPrice() {
20. return price;
21. }
22. public void setPrice(float price) {
23. this.price = price;
24. }
25.
26. public String execute(){
27. return "success";
28. }
29. }
5) Map the request in (struts.xml) file and define the view components
It is the important file from where struts framework gets information about the action and decides
which result to be invoked. Here, we have used many elements such as struts, package, action and
result.
package element is the sub element of struts. It represents a module of the application. It generally
extends the struts-defaultpackage where many interceptors and result types are defined.
action element is the sub element of package. It represents an action to be invoked for the incoming
request. It has name, class and method attributes. If you don't specify name attribute by default
execute() method will be invoked for the specified action class.
result element is the sub element of action. It represents an view (result) that will be invoked. Struts
framework checks the string returned by the action class, if it returns success, result page for the action
is invoked whose name is success or has no name. It has name and type attributes. Both are optional. If
you don't specify the result name, by default success is assumed as the result name. If you don't specify
the type attribute, by default dispatcher is considered as the default result type. We will learn about
result types later.
struts.xml
It is the view component the displays information of the action. Here, we are using struts tags to get the
information.
The s:property tag returns the value for the given name, stored in the action object.
welcome.jsp
To run this application, you need to have the struts 2 jar files. Here, we are providing all the necessary
jar files for struts 2. Download it and put these jar files in the lib folder of your project.
Finally, start the server and deploy the project and access it.