Introduction of Java server pages (JSP)

Introduction of JSP
JSP stands for Java server pages. It is a server-side technology like servlet which is used to develop server-side web components. It is designed as a presentation technology which allows you to render the dynamic response easily. Jsp is a combination of HTML and Java code. The extension of the file must be .jsp.

Case 1: Servlet for request process and presentation
Example Program.
Index.html

<html>
<body>
<h1> Xadmin <h1>
<h3> Xadmin Account Login <h3>
<form action=”test.xadmin” method=”post”>
<input type=”text” name=”fname”/>
<br/>
<input type=”submit”/>
</form>
</body>
</html>

Web.xml

<web-app>
<welcome-file-list>
<welcome-file>index.html</welcome.file>
</welcome-file-list>

<servlet>
<servlet-name>testServlet</servlet-name>
<servlet-class>com.xadmin.servlets.TestServlet
</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>testServlet<servlet-name>
<url-pattern>/ test.xadmin</url-pattern>
</servlet-mapping>
</web-app>

TestServlet.java

Package com.xadmin.servlets;
import java.io;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class TestServlet extends HttpServlet
{
protected void service(HttpServletRequest, HttpServletResponse response) throws servletException, IO Exception
{
String fnm=request.getParameter(“fname”);
Data dt= new Date();
If(fnm == null || fnm.trim().length()==0)
{
fnm=”Guest”;
}
String msg=”<h1>Hi +fnm+”<br/> you have sent
request on “+dt;
Response.setContextTypt(“text/html”);
Response.getWrite().write(msg);
}
}

Case 1: Servlet for request process and JSP for presentation

Example 2:
Index.html

<html>
<body>
<h1> Xadmin <h1>
<h3> Xadmin  Account Login <h3>
<form action=”test.xadmin” method=”post”>
<input type=”text” name=”fname”/>
<br/>
<input type=”submit”/>
</form>
</body>
</html>

Web.xml

<web-app>
<welcome-file-list>
<welcome-file>index.html</welcome.file>
</welcome-file-list>

<servlet>
<servlet-name>testServlet</servlet-name>
<servlet-class>com.xadmin.servlets.TestServlet
</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>testServlet<servlet-name>
<url-pattern>/ test.xadmin</url-pattern>
</servlet-mapping>
</web-app>

TestServlet.java

Package com.xadmin.servlets;
import java.io;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class TestServlet extends HttpServlet
{
protected void service(HttpServletRequest, HttpServletResponse response) throws servletException, IO Exception
{
String fnm=request.getParameter(“fname”);
Data dt= new Date();
If(fnm == null || fnm.trim().length()==0)
{
fnm=”Guest”;
Request.setAttribute(“NM”.fnm);
Request.setAttribute(“DT”,dt);
Request.getRequestDispatcher(“show.jsp”).forward(request, response);
}
}

Show.jsp

<html>
<body>
<h1>This is Show page</h1>
</body>
</html>

JSP LifeCycle

  • Whenever a client sends the first request to JSP the container will do the following task:
    • Translates JSP to Servlet (show.jsp > show jsp.java)
    • Compiles the translated Servlet( show jsp.java > show jsp.class)
    • Loads the translated servlet class
    • Creates the instance of a translated servlet class
    • Calls the lifecycle method jspService()
    • Invoke the lifecycle method jspService();
  • Whenever a client sends the forward request to JSP then jspService() will be called directly.
  • At container shutdown time, container calls the lifecycle method jspDestroy();

JSP life cycle methods

  • Following three are the life cycle method of JSP.

    • public void jspInit()

    • public void jspService(HttpServletRequest res, HttpServletResponse res)

    • public void jspDestroy()

JSP Implicit Objects

  • JSP implicit objects are the objects which are readly available in every JSP.

  • Every JSP you are writing will be translated servlet class is the web container.

  • Every translated servlet will have jspService() method which contains mainly 9 local variables to hold web container objects.

public void jspService(HttpServletsRequest request, HttpServletResponse response) throws java.op.IOException, servletException
{
pageContext PageContext=null;
HttpSession Session= null;
Servlet Context application=null;
ServletConfig config=null;
jspWriter out=null;
object page= this;
Throwable exception=null;
……
}

  • you can not define these objects your own in JSP page.

JSP Implicit Object type

JSP Implicit Object

HttpServletRequest

request

HttpServletResponse

response

pageContext

dpageContext

HttpSession

Session

servletConfig

Application

servletConfig

Config

jspWriter

Out

object

Page

Throwable

exception

JSP scripting Elements:-
JSP scripting elements are used to use java statements in JSP.

  1. Scriplets

  2. Expressions

  3. Declarations

Syntax:

                        Expressions:

Converted Servlet

<%
……
%>

<% int a= 33;
Out.println(a);
System.out.println(a);
%>

JspService()
{
……..
int a =33;
Out.println(a);
System.out.println(a);
……
}

  • Any valid java statements are allowed inside the scriplets.

  • All the statements inside the scriptlet will be placed inside the jspService() method of a translated servlet.

Expressions:

Syntax

                           Expression:

Converted Servlet

<%=exp

%>

<% string str=jtc%>
<%=str%>
<%=Hello%>

JspService()
{
…….
String str=”jtc”;
Out.println(str);
Out.println(Hello)
….
}

Declarations:

Syntax:

Expressions:

Converted Servlet

<%
…..
%>

<% !
String str=”jtc”;
Void m1()
{
}
%>

Class show jsp…
{
String str=”jtc”
void m1()
{
…..
jspService()
{
…….
}

  • Method definations, blocks, constructors, class level variables are allowed inside the declarations

  • All the code inside the declarations will be placed directly inside the translated servlet class and out side the jsp service() method.

In the example below, We can see the JSP file is converted to the Servlet file.

Show.jsp

<%!String str=”xadmin”;
void m1()
{
....
}
<h1>This IS SHOW JSP </h1>
<%INT A=33;
OUT.PRINTLN(A);
SYSTEM.OUT.PRINTLN(A)%>
<%=”hello”%>

Converted servlet file

package org.apache.jsp;
//default importpublic final class show jsp extends Httpjsp Base...
{
<string str=”xadmin”;
void m1()
{
...
}
public void jsp init()
{
.......
}
public void jsp destroy()
{
....
}
public void jsp service(HttpServletRequest request, HttpServletResponse response) throws java.io.IOexeception, Servletexception
{
pageContext pageContext=null;
HttpSession session=null;
servletContext application=null;
servletConfig config=null;
jspWriter out=null;
Object page=this;
Out.write(“<h1> This is show jsp page”);
....
int a =33;
Out.println(a);
System.out.println(a);
Out.print(“Hello”)
....
}
}

Comments in JSP page

we can use the following to define comments in the JSP page.

<!– This is HTML comment –>

<%– This is jsp comment / hidden comment –%>

Differences between Servlets and Jsp

Servlets

Jsp

You have to write the servlet class by extending

Http Servlet or Generic Servlet

Container writes or generates the Servlet class by extending HttpjspBase

You have to compile the Servlet class written by you

Container compiles the Translated servlet class.

Servlet lifecycle methods are:

public void init(Servletconfig)

publlic void service(HttpServletRequest req, HttpServletResponse res)

public void destroy()

Jsp lifecycle methods are:

public void jspInit()/jspinit()

public void jspservice(HttpServletRequest req, HttpServletResponse res)

public void jspDestroy()/jspDestroy()

Servlet will be initialized at container startup or at first request

JSP will be initialized at container startup or at first request

When you modify the servlet then you have to recompile, re-deploy and re-start the server.

When you modify the JSP, a container will do the automatic re-translation, re-compilation etc.

You can define any package for servlet

For the JSP, the Translated servlet will be placed in org.apache. JSP package.

JSP Directives

  • The directive is a special instruction to a container to perform the required task.

  • There are three directives in  JSP:

    • Include directive

    • Page directive

    • Taglib directive

1. Include directive:

  • Include directive is used to include one JSP or HTML in another JSP.

  • Include directive line will be placed with the content of included JSP or HTML at translation time

  • You can write one or more include directives inside the JSP.

Syntax:
<%@include file+”some.jsp or html”%>

For Example:

<%@include file=”header.html”%>

<%@include file=”login.jsp”%>

<%@include file=”footer.html”%>

Header.html

<h2>Xadmin website </h2>

Footer.html

<h3> All Reserved. Xadmin. 2019</h3>

Login.jsp

<h1> Account Login</h1>
<%!STATIC INT X=10;%>
<% int a =10

Index.jsp

<%@include file=”header.html”%>
<h2> THIS IS INDEX PAGE<%@include file=”login.jsp%>
<%@include file=”footer.html”%>

 

2) Page directive:

Syntax:

<%@pageLanguage=””
Session=””
Extends=isThreadSafe=””
errorPage=””
isErrorPage=””
isELIgnored=””%>

Language:

  • Language attributes are used to specify the language for the scriptlets and declarations

  • Currently, valid value is java and is the default value.

<%@page language=”java”%> valid<%@page language=”L”%> Invalid(Invalid Language Attribute)

Import:

  • import attribute is used to specify the packages to be imported for the translated Servlet.

  • You can specify one or more package with comma() separation using this attribute

<%@page session=”false”%>

Extends:

  • HttpJsBase is the default super class for the translated Servlet.

  • If you want to use other superclasses for the translated servlet instead of HttpJspBase, use extends attribute.

  • When you take Http Servlet as a superclass then you have to override any of the methods of HttpServlet

    <%@page extends=”Javax.servlet.http.Servlet”%>

Conclusion:

JSP and Servlets are gaining rapid acceptance as a means to provide dynamic content on the Internet. With full access to the Java platform, running from the server in a secure manner, the application possibilities are almost limitless. When JSPs are used with Enterprise JavaBeans technology, e-commerce and database resources can be further enhanced to meet an enterprise’s needs for web applications providing secure transactions in an open platform. Please feel free to drop a comment in the comment box below if you have any doubt about the topic or you want to share more information about the topic.

Leave a Reply

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