Learn JSP for begginners Part 1




Image result for JSP



Java Server Pages (JSP) is a server-side programming innovation that empowers the formation of dynamic, stage free technique for building Web-based applications. JSP approach the whole group of Java APIs, including the JDBC API to get to big business databases. This instructional exercise will show you how to utilize Java Server Pages to build up your web applications in basic and simple advances



Java Server Pages (JSP) code is likely HTML with bits of Java code in it. Basically, keeping in mind the end goal to make a JSP code, you can take any current HTML page and change its expansion to ".jsp" rather than ".html". At that point you can put Java code in it with a few structures called Scriptlet, Directive, Expression. In the code beneath, the JSP record demonstrates the present time:



1<html>
2    <body>
3        The current time is <%= new java.util.Date() %>
4    </body>
5</html>



In the other code, we make some calculations:
01<html>
02    <%
03       int a = 5;
04       int b = 8;  
05    %>
06    <body>
07        The first number is : <%= a %> <br/>
08        The second number is : <%= b %> <br/>
09        The sum is : <%= ( a + b ) %> <br/>
10    </body>
11</html>


As you see, in a JSP record, HTML and Java code are blended. You can likewise access to the whole group of Java APIs, including the JDBC API to get to big business databases in the JSP record. The fundamental structure is the HTML. In any case, with Java in it, you can get to the colossal Java APIs and libraries. With this adaptable nature, Web Application Programmers can focus on the most proficient method to process the data in the introduction layer ( HTML, GUI part ). 

JSP is an expansion of Servlets and each JSP page initially gets changed over into servlet by JSP compartment before handling the customer's demand. The Servlet is more seasoned Java innovation than JSP. It comprises of unadulterated Java code and holds the abilities of the servers, HTML convention. The Servlet code empowers to have HTML codes in it. Yet, this procedure is lumbering and mistake inclined, with regards to composing an intricate HTML reaction. JSP helps in this circumstance and give us to compose ordinary HTML page and incorporate our java code just where it's required.


Now, let’s see the principal JSP elements and try to explain them briefly.


1.1 JSP Syntactic Elements

In a JSP file, the Java code is usually written in a Scriptlet tags with a format like below:

1<% Java code %>

A scriptlet can contain any number of Java statements, variable or method declarations that are accessible from anywhere within the JSP page.
Variable or method declarations can be also written between the Declaration tags ( <%! %> ):
1 <%! 
2    int a, b;
3   public int sum( int i1, int i2 ) { return i1 + i2; }
4%>
JSP Expression tag ( <%= %> ) contains Java statement that is evaluated, converted to a String and written to the output stream of the response. For example, to write the content of the variable “name” to the screen, we can use <%=name%>. The scriptlet equivalent of this: <% out.print( name ); %>. Please note that in the expression tag, you don’t have to put semicolon (;) at the end of the line, but in the scriptlet you do.
Following is the syntax of JSP comments:
1<%-- JSP comment. Ignored by the JSP engine. --%>

1.2 JSP Implicit Objects

JSP Implicit Objects are the useful coding objects that the JSP Container makes available to developers in every JSP page. We can call them directly in scriptlets without any declaration. There are 9 JSP implicit objects. We show them and their counterpart Servlet and Java objects below:
ObjectType
requestjavax.servlet.http.HttpServletRequest
responsejavax.servlet.http.HttpServletResponse
pageContextjavax.servlet.jsp.PageContext
sessionjavax.servlet.http.HttpSession
applicationjavax.servlet.ServletContext
outjavax.servlet.jsp.JspWriter
configjavax.servlet.ServletConfig
pagejava.lang.Object
exceptionjava.lang.Throwable
1<% out.print( "Hello " + request.getParameter( "username" ) ); %>
In this code, two implicit objects ( out, request ) are used. The “username” parameter is fetched from the request object and after concatenating the “Hello” word, printed to the client with the out implicit object.

1.3 JSP Directives

JSP directives are messages and instructions to the JSP container, telling it how to translate a JSP page into the corresponding Servlet. Directives have this syntax:
1<% @ directive { attr=”value” }* %>
There are three directives. Here is the list:
DirectiveSample SyntaxDescription
page<%@ page import=”java.util.*,java.text.*” %>
( Imports other Java libraries into the JSP page )
The page directive defines a number of page dependent properties and communicates
these to the JSP container. Page directive attribute list is: language, extends, import, session, buffer, autoFlush, isThreadSafe, info, errorPage, isErrorPage, contentType, pageEncoding, isELIgnored, deferredSyntaxAllowedAsLiteral, trimDirectiveWhitespaces.
include<%@ include file=”otherPage.jsp” %>
( Merge the content of the other jsp file )
The include directive is used to substitute text and/or code at JSP page translation-time. This directive tells the container to insert the content of other files with the current JSP.
taglib<%@ taglib uri=”/WEB-INF/c.tld” prefix=”c”%>
( Declares the external taglib. Tablib uri can be an url address or tld tag library file path )
The taglib directive in a JSP page declares that the page uses a tag library,
uniquely identifies the tag library using a URI and associates a tag prefix that will
distinguish usage of the actions in the library

1.4 JSP Actions

JSP actions are the basically predefined functions based on XML syntax. They get the JSP container to do some behaviours, actions. They may affect the current out stream and use, modify and/or create objects.
The syntax for an Action element is:
1<jsp:action_name attribute="value" />
Here is the list of the some JSP Actions:
ActionDescriptionSample Code
jsp:useBeanAssociates an instance of a Java programming language object. Try to find an existing java object. If the object is not found it will attempt to create the object using attributes.<jsp:useBean id=”connection” class=”com.myapp.Connection”/>
jsp:setPropertySets the values of properties in a bean. Properties in a Bean can be set from one or more parameters in the request object, from a String constant, or from a computed request-time expression.<jsp:setProperty name=”user” property=”userobj” param=”username” />
jsp:getPropertyPlaces the value of a bean instance property, converted to a String, and print it. This simply means inserting it into the implicit “out” object.<jsp:getProperty name=”user” property=”name” />
jsp:includeProvides for the inclusion of static and dynamic
resources in the same context as the current page.
<jsp:include page=”/static/copyright.html”/>
jsp:forwardAllows the runtime dispatch of the current
request to a static resource, a JSP page or a Java servlet class in the same context
as the current page.
<jsp:forward page='<%= whereTo %>’ />
jsp:paramThis action element is used to provide key/value information. This element
is used in the jsp:include, jsp:forward, and jsp:params elements.
<jsp:param name=”name” value=”value” />
jsp:pluginThis tag is replaced by either an <object> or <embed> tag, as
appropriate for the requesting user agent, and emitted into the output stream of the
response.
<jsp:plugin type=”applet” code=”Molecule.class” codebase=”/html”><jsp:params>…</jsp:params></jsp:plugin>
jsp:attributeDefines an attribute value for another JSP action element instead of in
the value of an XML attribute.
<jsp:attribute name=”even”>
jsp:textThis action can be used to enclose template data in a JSP page, a JSP document,
or a tag file.
<jsp:text>This is some content</jsp:text>
jsp:outputThis action is used to modify some properties of the output of a JSP document
or a tag file.
<jsp:output xmlns:jsp=”http://java.sun.com/JSP/Page” omit-xml-declaration=”true”/>

1.5 JSP – Standard Tag Library (JSTL)

JSP Standard Tag Library (JSTL) is a set of useful tags to simplify the JSP development. It provides tags to control the JSP page behavior, iteration and control statements, internationalization tags, and SQL tags. JSTL is part of the Java EE API and included in most servlet containers. There are five groups of JSTL: core tags, sql tags, xml tags, internationalization tags and functions tags.
In the code snippet below, there is a simple loop coded with JSTL. Without any tag library or tags, we can write the counterpart code with scriptlets that contain Java code in it. But external tag libraries provide more simple and useful capabilities to us. We can do more with writing less.
1<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 
2<c:forEach var="number" begin="5" end="10"
3   <c:out value="${number}"></c:out
4</c:forEach

1.6 JSP – Expression Language (EL)

JSP Expression Language (EL) improves to get to application information put away in JavaBeans properties. EL likewise incorporates number juggling, social and legitimate administrators. There are two builds to speak to EL articulations: ${expr} and #{expr}. EL additionally has its own particular administrators, catchphrases and verifiable items. 

The "param" understood question holds ask for parameters as strings. In the code beneath, EL proclamation ${param.name} recovers the "name" parameter of the demand. In the second line, you see the in addition to administrator assesses the expansion figurings.
1<h1>Welcome ${param.name}</h1>
2<p>The result is ${a + b}</p>

Overview

In our example, you see a simple issue tracking management web application with a single JSP page that contains the issue list and a form to insert a new issue. When you submit a new issue, this issue is appended to the list below with ‘OPEN’ status and ‘current time’ created date by default. In the list, the status of the each issue item can be changed by the buttons in its row. ‘CLOSE’ status issues are not listed and when you click on the close, the item you close is removed from the list. The background colors of the rows depend on their status. The rows of the ‘OPEN’ status issues are pink, ‘FIX’ status issues are green.

Our preferred IDE is Eclipse. We use ‘Maven’ for the dependency management. We create a dynamic web application and deploy it into the Tomcat server. Before, I have explained how to create a Maven dynamic web application in the Eclipse, how to define a “Tomcat” server and add the application to it in my other example. You can examine: Logback Mapped Diagnostic Contexts (MDC) Example
We add three dependencies to the Maven “pom.xml” file:
Dependencies in the pom.xml
01<dependencies>
02    <dependency>
03        <groupId>javax.servlet</groupId>
04        <artifactId>javax.servlet-api</artifactId>
05        <version>3.1.0</version>
06        <scope>provided</scope>
07    </dependency>    
08    <dependency>
09     <groupId>jstl</groupId>
10     <artifactId>jstl</artifactId>
11     <version>1.2</version>
12    </dependency>
13    <dependency>
14        <groupId>com.h2database</groupId>
15        <artifactId>h2</artifactId>
16        <version>1.4.187</version>
17    </dependency>                
18</dependencies>
We keep the issue records in a H2 memory database. We add “Standard Tag Library (JSTL)” jar file to the classpath. Because we use it in somewhere in the JSP code. We create two Servlets classes, so in order to compile it in our environment, we add servlet-api as provided. Anyway jsp-api and servlet-api jar files are already exist in the Jsp Container ( Tomcat Server ). So after compilation, you do not need to put these files in your project package ( war, ear ). If you put different version of the jsp/servlet jar files in the project package, probably you will get errors while deploying. For example, I executed this example in Tomcat 8. Apache Tomcat version 8.0 implements the Servlet 3.1 and JavaServer Pages 2.3 specifications from the Java Community Process. So I deliberately add the Servlet “3.1” version to the pom.xml file.

 video tutorial




Thank you !!!!



.

7 comments:

  1. Great work!! Looking forward for the next.

    ReplyDelete
  2. Great work!! Looking forward for the next.

    ReplyDelete
    Replies
    1. thank you for your support!! next tutorials on the process ..

      Delete
  3. Good Job it's very helpful for me thank you so much

    ReplyDelete