MARQUEE

this blog is only for the important notes for the paper solving systematic created by RANJEET TIWARI.

facebook page

Tuesday, 13 March 2018

Chapter 2

Unit -2     

Web Programming Model


JSP:

JSP technology is used to create web application just like Servlet technology. It can be thought of as an extension to servlet because it provides more functionality than servlet such as expression language, jstl etc.

A JSP page consists of HTML tags and JSP tags. The jsp pages are easier to maintain than servlet because we can separate designing and development. It provides some additional features such as Expression Language, Custom Tag etc.

Advantage of JSP over Servlet

There are many advantages of JSP over servlet. They are as follows:


1) Extension to Servlet


JSP technology is the extension to servlet technology. We can use all the features of servlet in JSP. In addition to, we can use implicit objects, predefined tags, expression language and Custom tags in JSP, that makes JSP development easy.

2) Easy to maintain

JSP can be easily managed because we can easily separate our business logic with presentation logic. In servlet technology, we mix our business logic with the presentation logic.

3) Fast Development: No need to recompile and redeploy

If JSP page is modified, we don't need to recompile and redeploy the project. The servlet code needs to be updated and recompiled if we have to change the look and feel of the application.

4) Less code than Servlet

In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that reduces the code. Moreover, we can use EL, implicit objects etc

Life cycle of a JSP Page

The JSP pages follows these phases:

o Translation of JSP Page

o Compilation of JSP Page

o Classloading (class file is loaded by the classloader)

o Instantiation (Object of the Generated Servlet is created).

o Initialization ( jspInit() method is invoked by the container).

o Reqeust processing ( _jspService() method is invoked by the container).

o Destroy ( jspDestroy() method is invoked by the container).


Note:

 jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.
As depicted in the above diagram, JSP page is translated into servlet by the help of JSP translator. The JSP translator is a part of webserver that is responsible to translate the JSP page into servlet. Afterthat Servlet page is compiled by the compiler and gets converted into the class file. Moreover, all the processes that happens in servlet is performed on JSP later like initialization, committing response to the browser and destroy.


Creating a simple JSP Page

To create the first jsp page, write some html code as given below, and save it by .jsp extension. We have save this file as index.jsp. Put it in a folder and paste the folder in the web-apps directory in apache tomcat to run the jsp page.

index.jsp

Let's see the simple example of JSP, here we are using the scriptlet tag to put java code in the JSP page. We will learn scriptlet tag later.

1.<html>
2.<body>
3.<% out.print(2*5); %>
4.</body>
5.</html>
It will print 10 on the browser.

How to run a simple JSP Page ?

Follow the following steps to execute this JSP page:

o Start the server
o put the jsp file in a folder and deploy on the server
o visit the browser by the url http://localhost:portno/contextRoot/jspfile e.g. http://localhost:8888/myapplication/index.jsp

Do I need to follow directory structure to run a simple JSP ?

No, there is no need of directory structure if you don't have class files or tld files. For example, put jsp files in a folder directly and deploy that folder.It will be running fine.But if you are using bean class, Servlet or tld file then directory structure is required.

Directory structure of JSP

The directory structure of JSP page is same as servlet. We contains the jsp page outside the WEB-INF folder or in any directory.

The JSP API
The JSP API consists of two packages:

1.javax.servlet.jsp

2.javax.servlet.jsp.tagext

javax.servlet.jsp package


The javax.servlet.jsp package has two interfaces and classes.The two interfaces are as follows:

1.JspPage

2.HttpJspPage


The classes are as follows:

o  JspWriter
o  PageContext
o JspFactory
o JspEngineInfo
o JspException
o  JspError

The JspPage interface

According to the JSP specification, all the generated servlet classes must implement the JspPage interface. It extends the Servlet interface. It provides two life cycle methods.


Methods of JspPage interface

1.public void jspInit(): It is invoked only once during the life cycle of the JSP when JSP page is requested firstly. It is used to perform initialization. It is same as the init() method of Servlet interface.

2.public void jspDestroy(): It is invoked only once during the life cycle of the JSP before the JSP page is destroyed. It can be used to perform some clean up operation.

The HttpJspPage interface

The HttpJspPage interface provides the one life cycle method of JSP. It extends the JspPage interface.
Method of HttpJspPage interface:

1.public void _jspService(): It is invoked each time when request for the JSP page comes to the container. It is used to process the request. The underscore _ signifies that you cannot override this method.

We will learn all other classes and interfaces later.

///////////////////

JSP Scriptlet tag (Scripting elements)

In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's see what are the scripting elements first.

JSP Scripting elements


The scripting elements provides the ability to insert java code inside the jsp. There are three types of scripting elements:

oscriptlet tag

oexpression tag

odeclaration tag

JSP scriptlet tag

A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:
1.<%  java source code %>
Example of JSP scriptlet tag

In this example, we are displaying a welcome message.
1.<html>
2.<body>
3.<% out.print("welcome to jsp"); %>
4.</body>
5.</html>

Example of JSP scriptlet tag that prints the user name

In this example, we have created two files index.html and welcome.jsp. The index.html file gets the username from the user and the welcome.jsp file prints the username with the welcome message.
File: index.html

1.<html>
2.<body>
3.<form action="welcome.jsp">
4.<input type="text" name="uname">
5.<input type="submit" value="go"><br/>
6.</form>
7.</body>
8.</html>
File: welcome.jsp
1.<html>
2.<body>
3.<%
4.String name=request.getParameter("uname");
5.out.print("welcome "+name);
6.%>
7.</form>
8.</body>
9.</html> 

JSP expression tag

The code placed within JSP expression tag is written to the output stream of the response. So you need not write out.print() to write data. It is mainly used to print the values of variable or method.
Syntax of JSP expression tag

1.<%=  statement %>


Example of JSP expression tag

In this example of jsp expression tag, we are simply displaying a welcome message.
1.<html>
2.<body>
3.<%= "welcome to jsp" %>
4.</body>
5.</html>

Note: Do not end your statement with semicolon in case of expression tag.

Example of JSP expression tag that prints current time

To display the current time, we have used the getTime() method of Calendar class. The getTime() is an instance method of Calendar class, so we have called it after getting the instance of Calendar class by the getInstance() method.

index.jsp
1.<html>
2.<body>
3.Current Time: <%= java.util.Calendar.getInstance().getTime() %>
4.</body>
5.</html>

Example of JSP expression tag that prints the user name


In this example, we are printing the username using the expression tag. The index.html file gets the username and sends the request to the welcome.jsp file, which displays the username.


File: index.jsp


1.<html>
2.<body>
3.<form action="welcome.jsp">
4.<input type="text" name="uname"><br/>
5.<input type="submit" value="go">
6.</form>
7.</body>
8.</html>

File: welcome.jsp


1.<html>
2.<body>
3.<%= "Welcome "+request.getParameter("uname") %>
4.</body>
5.</html>

JSP Declaration Tag


The JSP declaration tag is used to declare fields and methods.

The code written inside the jsp declaration tag is placed outside the service() method of auto generated servlet
.
So it doesn't get memory at each request.

Syntax of JSP declaration tag


The syntax of the declaration tag is as follows:

1.<%!  field or method declaration %>

Difference between JSP Scriptlet tag and Declaration tag

Jsp Scriptlet TagJsp Declaration Tag


The jsp scriptlet tag can only declare variables not methods.The jsp declaration tag can declare variables as well as methods.

The declaration of scriptlet tag is placed inside the _jspService() method.The declaration of jsp declaration tag is placed outside the _jspService() method.

Example of JSP declaration tag that declares field

In this example of JSP declaration tag, we are declaring the field and printing the value of the declared field using the jsp expression tag.

index.jsp

1.<html>
2.<body>
3.<%! int data=50; %>
4.<%= "Value of the variable is:"+data %>
5.</body>
6.</html> 


Example of JSP declaration tag that declares method


In this example of JSP declaration tag, we are defining the method which returns the cube of given number and calling this method from the jsp expression tag. But we can also use jsp scriptlet tag to call the declared method.

index.jsp

1.<html>
2.<body>
3.<%!
4.int cube(int n){
5.return n*n*n*;
6.}
7.%>
8.<%= "Cube of 3 is:"+cube(3) %>
9.</body>
10.</html>

JSP Implicit Objects

There are 9 jsp implicit objects. These objects are created by the web container that are available to all the jsp pages.

The available implicit objects are out, request, config, session, application etc.

A list of the 9 implicit objects is given below:

ObjectType

outJspWriter

requestHttpServletRequest

responseHttpServletResponse

configServletConfig

applicationServletContext

sessionHttpSession

pageContextPageContext

pageObject

exceptionThrowable

1) JSP out implicit object

For writing any data to the buffer, JSP provides an implicit object named out. It is the object of JspWriter. In case of servlet you need to write:

PrintWriter out=response.getWriter();
JSP request implicit object

The JSP request is an implicit object of type HttpServletRequest i.e. created for each jsp request by the web container. It can be used to get request information such as parameter, header information, remote address, server name, server port, content type, character encoding etc.

It can also be used to set, get and remove attributes from the jsp request scope.

Example of JSP request implicit object

index.html
1.<form action="welcome.jsp">
2.<input type="text" name="uname">
3.<input type="submit" value="go"><br/>
4.</form>

welcome.jsp

1.<%
2.String name=request.getParameter("uname");
3.out.print("welcome "+name);
4.%>


JSP response implicit object


In JSP, response is an implicit object of type HttpServletResponse. The instance of HttpServletResponse is created by the web container for each jsp request.

It can be used to add or manipulate response such as redirect response to another resource, send error etc.

Example of response implicit object

index.html
1.<form action="welcome.jsp">
2.<input type="text" name="uname">
3.<input type="submit" value="go"><br/>
4.</form>

welcome.jsp
1.<%
2.response.sendRedirect("http://www.google.com");
3.%>

JSP config implicit object


In JSP, config is an implicit object of type ServletConfig. This object can be used to get initialization parameter for a particular JSP page. The config object is created by the web container for each jsp page.

Generally, it is used to get initialization parameter from the web.xml file.


JSP application implicit object

In JSP, application is an implicit object of type ServletContext.

The instance of ServletContext is created only once by the web container when application or project is deployed on the server.

This object can be used to get initialization parameter from configuaration file (web.xml). It can also be used to get, set or remove attribute from the application scope.

session implicit object


In JSP, session is an implicit object of type HttpSession.The Java developer can use this object to set,get or remove attribute or to get session information.


pageContext implicit object

In JSP, pageContext is an implicit object of type PageContext class.The pageContext object can be used to set,get or remove attribute from one of the following scopes:

o page
o request
o session
o application

In JSP, page scope is the default scope.

page implicit object:

In JSP, page is an implicit object of type Object class.This object is assigned to the reference of auto generated servlet class. It is written as:

Object page=this;

For using this object it must be cast to Servlet type.For example:
<% (HttpServlet)page.log("message"); %>

Since, it is of type Object it is less used because you can use this object directly in jsp.For example:
<% this.log("message"); %>


exception implicit object

In JSP, exception is an implicit object of type java.lang.Throwable class. This object can be used to print the exception. But it can only be used in error pages.It is better to learn it after page directive. Let's see a simple example:

Example of exception implicit object:

error.jsp

1.<%@ page isErrorPage="true" %>
2.<html>
3.<body>
4.
5.Sorry following exception occured:<%= exception %>
6.
7.</body>
8.</html> 

JSP directives//////

The jsp directives are messages that tells the web container how to translate a JSP page into the corresponding servlet.

There are three types of directives:

o page directive
o include directive
o taglib directive

Syntax of JSP Directive

1.<%@ directive attribute="value" %>

JSP page directive

The page directive defines attributes that apply to an entire JSP page.
Syntax of JSP page directive
<%@ page attribute="value" %>

Jsp Include Directive

The include directive is used to include the contents of any resource it may be jsp file, html file or text file. The include directive includes the original content of the included resource at page translation time (the jsp page is translated only once so it will be better to include static resource).
Advantage of Include directive

Code Reusability

Syntax of include directive

1.<%@ include file="resourceName" %>
Example of include directive

In this example, we are including the content of the header.html file. To run this example you must create an header.html file.

1.<html>
2.<body>
3.
4.<%@ include file="header.html" %>
5.
6.Today is: <%= java.util.Calendar.getInstance().getTime() %>
7.
8.</body>
9.</html>

JSP Taglib directive

The JSP taglib directive is used to define a tag library that defines many tags. We use the TLD (Tag Library Descriptor) file to define the tags. In the custom tag section we will use this tag so it will be better to learn it in custom tag.

Syntax JSP Taglib directive

1.<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>
Example:
1.<html>
2.<body>
3.
4.<%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag" %>
5.
6.<mytag:currentDate/>
7.
8.</body>
9.</html>


JSP Action Tags

There are many JSP action tags or elements. Each JSP action tag is used to perform some specific tasks.

The action tags are used to control the flow between pages and to use Java Bean. The Jsp action tags are given below.

JSP Action Tags Description

jsp:forwardforwards the request and response to another resource.

jsp:includeincludes another resource.

jsp:useBeancreates or locates bean object.

jsp:setPropertysets the value of property in bean object.

jsp:getPropertyprints the value of property of the bean
.
jsp:pluginembeds another components such as applet.

jsp:paramsets the parameter value. It is used in forward and include mostly.

jsp:fallbackcan be used to print the message if plugin is working. It is used in jsp:plugin.
Model 1 and Model 2 (MVC) Architecture

Before developing the web applications, we need to have idea about design models. There are two types of programming models (design models)

1.Model 1 Architecture

2.Model 2 (MVC) Architecture

Model 1 Architecture

Servlet and JSP are the main technologies to develop the web applications.
Servlet was considered superior to CGI. Servlet technology doesn't create process, rather it creates thread to handle request. The advantage of creating thread over process is that it doesn't allocate separate memory area. Thus many subsequent requests can be easily handled by servlet.

Problem in Servlet technology Servlet needs to recompile if any designing code is modified. It doesn't provide separation of concern. Presentation and Business logic are mixed up.
JSP overcomes almost all the problems of Servlet. It provides better separation of concern, now presentation and business logic can be easily separated. You don't need to redeploy the application if JSP page is modified. JSP provides support to develop web application using JavaBean, custom tags and JSTL so that we can put the business logic separate from our JSP that will be easier to test and debug.

As you can see in the above figure, there is picture which show the flow of the model1 architecture.

1.Browser sends request for the JSP page

2.JSP accesses Java Bean and invokes business logic

3.Java Bean connects to the database and get/save data

4.Response is sent to the browser which is generated by JSP

Advantage of Model 1 Architecture

o Easy and Quick to develop web application
Disadvantage of Model 1 Architecture
o Navigation control is decentralized since every page contains the logic to determine the next page. If JSP page name is changed that is referred by other pages, we need to change it in all the pages that leads to the maintenance problem.
o Time consuming You need to spend more time to develop custom tags in JSP. So that we don't need to use scriptlet tag.
o Hard to extend It is better for small applications but not for large applications.

Model 2 (MVC) Architecture

Model 2 is based on the MVC (Model View Controller) design pattern. The MVC design pattern consists of three modules model, view and controller.

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.


Advantage of Model 2 (MVC) Architecture

o Navigation control is centralized Now only controller contains the logic to determine the next page.
o Easy to maintain
o Easy to extend
o Easy to test
o Better separation of concerns

Disadvantage of Model 2 (MVC) Architecture

o We need to write the controller code self. If we change the controller code, we need to recompile the class and redeploy the application.

Solution of Model 2 Architecture: Configurable MVC Components

It uses the declarative approach for defining view components, request mapping etc. It resolves the problem of Model 2 architecture. The Struts framework provides the configurable MVC support. In struts 2, we define all the action classes and view components in struts.xml file.

1) What are the life-cycle methods for a jsp?

MethodDescription

public void jspInit()It is invoked only once, same as init method of servlet.
public void _jspService(ServletRequest request,ServletResponse)throws ServletException,IOExceptionIt is invoked at each request, same as service() method of servlet.
public void jspDestroy()It is invoked only once, same as destroy() method of servlet.

3)What is difference between hide comment and output comment?

The jsp comment is called hide comment whereas html comment is called output comment. If user views the source of the page, the jsp comment will not be shown whereas html comment will be shown.


4)What are the JSP implicit objects ?

JSP provides 9 implicit objects by default. They are as follows:

ObjectType

1) outJspWriter

2) requestHttpServletRequest

3) responseHttpServletResponse

4) configServletConfig

5) sessionHttpSession

6) applicationServletContext

7) pageContextPageContext

8) pageObject

9) exceptionThrowable

5)What is difference between include directive and include action?

include directive include action
1) The include directive includes the content at page translation time.1) The include action includes the content at request time.

2) The include directive includes the original content of the page so page size increases at runtime.2) The include action doesn't include the original content rather invokes the include() method of Vendor provided class.

3) It's better for static pages.3) It's better for dynamic pages.


6) Is JSP technology extensible?

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

7) How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it?

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.


8) How can I prevent the output of my JSP or Servlet pages from being cached by the browser?

1.<%
2.response.setHeader("Cache-Control","no-store");
3.response.setHeader("Pragma","no-cache");
4.response.setHeader ("Expires", "0"); //prevents caching at the proxy server
5.%>  

No comments:

Chapter 5 dccn

                                           Transport layer In computer networking, the transport layer is a conceptual division of metho...