JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

JSP Implicit Objects

January 17, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • JSP Tutorials
  • Recommended Books for Java Server Pages (JSP)

Implicit objects are java objects that are created by container when JSP page is being translated to servlet and are accessible to Java scriptlets or expressions in JSP pages based on scope of particular object type.

There are 9 implicit objects which are listed below:

  1. out
  2. request
  3. response
  4. session
  5. application
  6. config
  7. pageContext
  8. page
  9. exception

out

It is used to send content or output to the client.It is instance of javax.servlet.jsp.JspWriter object.

Following example demonstrates use of this attribute:
Listing 1: example.jsp

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body><h2>Testing out Implicit object</h2>
<% out.println("today’s date is:"+new java.util.Date());
%>
</body>
</html>
[/code]

Output
Execute the above example.jsp in Eclipse by selecting Run As > Run On Server, output as below would be seen:
jsp_outobject_demo

request

It is an instance of javax.servlet.http.HttpServletRequest object. Whenever a client requests a page, JSP engine creates new object to that request.

Following example demonstrates use of this attribute:
Listing 2: example.html

[code lang=”html”]
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="hello.jsp">
<input type="text" name="username"/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
[/code]

Now create jsp file as hello.jsp. This is file which is defined in the action attribute in the form element of above html file.

Listing 3: hello.jsp

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body><h2>Testing request Implicit object</h2>
<%
String name=request.getParameter("username");
out.println("Welcome "+ name);
%>
</body>
</html>
[/code]

Output
Execute the above example.html in Eclipse by selecting Run As > Run On Server, output as below would be seen:
jsp_requestobject1_demo

Now enter some text. I entered “Javabeat” and clicked on submit button, the output is:
jsp_requestobject2_demo

response

It is an instance of javax.servlet.http.HttpServletResponse object. Server creates an object to response as it creates a request object. Through this object user can add new cookies or date stamps, HTTP status codes etc to your JSP programme.
Following example demonstrates use of this attribute:
Listing 4: example.html

[code lang=”html”]
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="response.jsp">
<input type="text" name="username"/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
[/code]

Create jsp file as response.jsp.
Listing 5: response.jsp

[code lang=”html”]
<html>
<body>
<%
response.sendRedirect("http://www.yahoo.com");
%>
</body>
</html>
[/code]

Output
Execute the above example.html in Eclipse by selecting Run As > Run On Server, output as below would be seen:
jsp_requestobject1_demo

Now enter some text. I entered “Javabeat” and clicked on submit button, the browser is redirected to yahoo.com page.

session

It is an instance of javax.servlet.http.HttpSession. It is used to set or get session information. Whenever we request for jsp page, container will create session for that jsp.

Following example demonstrates use of this attribute:
Listing 6: example.jsp

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body><h2>Testing session Implicit object</h2>
<%=session.getId()%>
</body>
</html>
[/code]

Output
Execute the above example.html in Eclipse by selecting Run As > Run On Server, output as below would be seen:
jsp_session_demo

application

The application object is direct wrapper around the ServletContext object. It is used to get information and attributes in JSP. It is also used to forward the request to another resource or to include the response from another resource.
Following example demonstrates use of this attribute:
Listing 7: example.jsp

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body><h2>Testing application Implicit object</h2>
<%
String driver=application.getInitParameter("dbname");
out.print("driver name is="+driver);

%>
</body>
</html>
[/code]

Define this parameter in web.xml as below:
Listing 8: web.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>HelloWorldJSP</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>

</welcome-file-list>
<context-param>
<param-name>dbname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>
</web-app>
[/code]

Output
Execute the above example.html in Eclipse by selecting Run As > Run On Server, output as below would be seen:
jsp_application_demo

config

This object is an instance of javax.servlet.ServletConfig and is a direct wrapper around the ServletConfig object for the generated servlet. It is used to get configuaration message for jsp page. Also it is used to get the init parameter present in deployment descriptor.

pagecontext

It is an instance of a javax.servlet.jsp.PageContext object. It represents entire JSP page. It store references to reuqests and repsonses. You can derive application, config, session, and out objects from pagecontext object. pagecontext object consist of four scope fields amongst other fields:

  • PAGE_SCOPE
  • REQUEST_SCOPE
  • SESSION_SCOPE
  • APPLICATION_SCOPE

Following example demonstrates use of this attribute:
Listing 10: example.jsp

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body><h2>Testing pagecontext Implicit object</h2>
<% pageContext.setAttribute("param1", "Javabeat"); %>
PageContext attribute:{Name="someName",Value="<%=pageContext.getAttribute("param1") %>"}

</body>
</html>
[/code]

Output
Execute the above example.html in Eclipse by selecting Run As > Run On Server, output as below would be seen:

jsp_pagecontext_demo

page

This object can be thoguht of repreenting an etire JSP page. It is rarely used.
Following example demonstrates use of this attribute:
Listing 11: example.jsp

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body><h2>Testing page Implicit object</h2>
<%=page.getClass().getName() %>

</body>
</html>
[/code]

Output
Execute the above example.html in Eclipse by selecting Run As > Run On Server, output as below would be seen:
jsp_page_demo

exception

It is used to display exception in jsp error pages. This object is a wrapper containing the exception thrown from the previous page. Youc an an example for this in the Exception Handling in JSP chapter.

Previous Tutorial :  JSP Directives   ||  Next Tutorial :  JSP Redirect

Filed Under: Java EE Tagged With: JSP Tutorials

JSP Directives

January 17, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • JSP Tutorials
  • Recommended Books for Java Server Pages (JSP)

Directives specifies translation time instruction to JSP engine. There are three types of directives:

  • page directive
  • include directive
  • taglib directive

JSP Page Directive

This directive can be used to specify any of a number of page-dependent attributes such as scripting language to use, class to extend, page to be imported and more. Syntax of JSP page directive is as follows:

[code lang=”html”]
<%@ page attribute="value"%>
[/code]

Where attribute can be any of the following:

  • import– It is used to import classes, interface of a package similar to import statement in Java.
  • contentType – It defines MIME(Multipurpose Internet Mail Extension) type of response. You can specify any of these values:text/xml, text/html, application/msword, or text/html:charset=ISO-8859-1. Default value is ” “text/html;charset=ISO-8859-1″.”.
  • extends – It defines parent class of generated servlet class.
  • info – Defines information about jsp page which can later be retrieved by using getServletInfo() method of Servlet interface.
  • buffer – Defines size of the buffer used to handle output stream.Default buffer size is 8kb or greater.
  • language – It defines programming langauge used in jsp page.default value is “java”.
  • isELIgnored – It specifies whether EL(Expression Langauge) elements are ignored on the page.The value is either true or false.The value is false by default.
  • isThreadSafe – Defines the threading model for the generated servlet. The default value is true.If make it false,it will wait until the JSP finishes responding to a request before passing another request to it.
  • errorPage – It is used to define the error page. If an error occurs on current page then it will be redirected to the error page defined by this attribute.
  • isErrorPage – It declares that current page is the error page.
  • autoFlush – It defines whether output should be flushed automatically when buffer is filled.The default is true.
  • pageEncoding – It defines character encoding of output stream.The default is ISO-8859-1.
  • session – It defines whether JSP page is participating in HTTP session.

Example – import attribute

Listing 1 – example.jsp

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%@ page import="java.util.Date" %>
Today is: <%= new java.util.Date() %>
</body>
</html>
[/code]

Output
Execute the above example.jsp in Eclipse by selecting Run As > Run On Server, output as below would be seen:
jsp_importattr_demo

Example – contentType attribute

Listing 2 – example.jsp

[code lang=”html”]
<html>
<body>

<%@ page contentType="text/xml" %>
Today is: <%= new java.util.Date() %>

</body>
</html>
[/code]

Output
Execute the above example.jsp in Eclipse by selecting Run As > Run On Server, output as below would be seen:
jsp_contenttypeattr_demo

Example – info

Listing 3 – example.jsp

[code lang=”html”]
<html>
<body>
<%@ page info="This page is by Javabeat…" %>
</body>
</html>
[/code]

The web container creates a method as below:

[code lang=”html”]
public String getServletInfo() {
return "This page is by Javabeat…";
}
[/code]

Example – buffer

Listing 4 – example.jsp

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%@ page buffer="10kb" %>
Today is: <%= new java.util.Date() %>
</body>
</html>
[/code]

Example – errorPage and isErrorPage attribute

Listing 5 – example.jsp

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%@ page errorPage="errorpage.jsp"%>
<%=10/0 %>
</body>
</html>
[/code]

Listing 6 -errorpage.jsp

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%@ page isErrorPage="true" %>
Exception occured..The exception is: <%= exception %>
</body>
</html>
[/code]

Output
Execute the above example.jsp in Eclipse by selecting Run As > Run On Server, output as below would be seen:
jsp_errorpage_demo

JSP Include Directive

It is used to include any contents of files such as jsp file, html file or text file. Syntax of JSP include directive:

[code lang=”html”]
<%@ include file="file name" %>
[/code]

Let us write an example.jsp as below. This will include a file called welcome.jsp:
Listing 7 -errorpage.jsp

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%@ include file="welcome.jsp" %>
Today is: <%= new java.util.Date() %>
</body>
</html>
[/code]

Listing 8 -welcome.jsp

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>Welcome to Javabeat</h2>

</body>
</html>
[/code]

Output
Execute the above example.jsp in Eclipse by selecting Run As > Run On Server, output as below would be seen:
jsp_includedirective_demo

JSP Taglib Directive

It is used to define tag library that defines custom tags. This directive includes URI and custom tag prefix. Syntax of JSP include directive:

[code lang=”html”]
<%@ taglib uri="uri" prefix="prefix_to_the_Tag" >
[/code]

where

  • uri is the resolved to the location the container understands
  • prefix attribute informs a container what bits of markup are custom actions.

Let us see an example below which demonstrates use of taglib directive:
Listing 9 -example.jsp

[code lang=”html”]
<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>JSP is Easy</title>
</head>
<body bgcolor="white">
<h1>JSP is as easy as …</h1>
<%– Calculate the sum of 1 + 2 + 3 dynamically –%>
1 + 2 + 3 = <c:out value="${1 + 2 + 3}" />
</body>
</html>

[/code]

Previous Tutorial :  JSP Actions   ||  Next Tutorial : JSP Implicit Objects

Filed Under: Java EE Tagged With: JSP Tutorials

JSP Actions

January 16, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • JSP Tutorials
  • Recommended Books for Java Server Pages (JSP)

JSP actions are XML syntax tags used to control servlet engine.The Action tags are used to control the flow between pages and to use Java Bean. We can insert file, forward one page to another page or we can create HTML page for java plugin. Jsp action tags are listed in the table below:

  • <jsp:plugin>Generates HTML code that contains the appropriate client browser-dependent elements (OBJECT or EMBED) needed to execute an applet with the Java plugin software.
JSP Action Tag Description
<jsp:forward> It is used to forward request to another resource or page .It may be html page,jsp page or other resource.
<jsp:include> Used to include the relative URL at the execution time (not at compile time).
<jsp:usebean> Makes a Javabean component available in a page.
<jsp:setProperty> sets s Javabeans property value.
<jsp:getProperty> It is used to retrieve value of given property from Javabeans component and add it to response.

Now let us write examples for each of the above tags in the following sections.

jsp:forward

It is used to forward request to another page. For example, we will forward request from mainpage.jsp to welcome.jsp page as demonstrated in the example below:

Listing 1:mainpage.jsp

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<% out.print("This the main page");%>
<jsp:forward page="welcome.jsp"/>
</body>
</html>
[/code]

Listing 2:welcome.jsp

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>Welcome to Javabeat</h2>
<% out.print("This is page where control is forwarded to");%>
<p>Today’s date: <%= (new java.util.Date())%></p>
</body>
</html>
[/code]

Output
Execute the above mainpage.jsp in Eclipse by selecting Run As > Run On Server, output as below would be seen:

jsp_fowardaction_demo

As you can see the contents of the main page i.e mainpage.jsp is discarded and only the content from welcome.jsp is displayed.

jsp:include

This tag is used to include files such as jsp, html or servlet. For example,we will take above file welcome.jsp to be include in includeexample.jsp

Listing 3:includeexample.jsp

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>welcome.jsp is included on this page.</h2>
<jsp:include page="welcome.jsp"/>
</body>
</html>
[/code]

Listing 4:welcome.jsp

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>Welcome to Javabeat</h2>
<% out.print("This is page where control is forwarded to");%>
<p>Today’s date: <%= (new java.util.Date())%></p>
</body>
</html>
[/code]

Output
Execute the above includeexample.jsp in Eclipse by selecting Run As > Run On Server, output as below would be seen:
jsp_includeaction_demo

jsp:usebean

It is used to initialize bean class. If object is not created then it creates specified object. Syntax of jsp:usebean tag is as follows:

[code lang=”html”]
<jsp:useBean id="name">.. </jsp:usebean>
[/code]

Where

  • id: It is used to identify bean name
  • class: Creates object of bean class

Following example demonstrates use of this tag:

Listing 5: SampleBean.java

[code lang=”java”]
package javabeat.net.jsp.actions;

public class SampleBean {
public int square(int n){return n*n;}
}

[/code]

Listing 6: usebeanexample.jsp

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<jsp:useBean id="obj"/>

<%
int m=obj.square(10);
out.print("cube of 10 is "+m);
%>
</body>
</html>
[/code]

Output
Execute the above usebeanexample.jsp in Eclipse by selecting Run As > Run On Server, output as below would be seen:

jsp_usebeanaction_demo

jsp:setProperty

It is used to set property value in bean. Syntax is as follows:

[code lang=”html”]
<jsp:useBean id="someName" … >
…
<jsp:setProperty name="someName" property="someProperty" …/>
</jsp:useBean>
[/code]

Following is the list of attributes associated with setProperty action:

  • name- The name of the bean whose property will be set.
  • property-Indicates the property you want to set.
  • value- This is the value that will be assigned to the property.
  • param- It is the name of the request parameter whose value the property is to receive.

jsp:getProperty

It is used to get value of property. Syntax is as follows:

[code lang=”html”]
<jsp:useBean id="someName" … >
…
<jsp:getProperty name="someName" property="someProperty" …/>
</jsp:useBean>
[/code]

Following is the list of attributes associated with getProperty action:

  • name- The bean name whose property value is to be retrived.
  • property- The name os property whose value is to be retrieved.

Now let us see an example which uses both the action tags jsp:setProperty and jsp:getProperty:
create on java file. Save it as SampleBean.java

Listing 7: SampleBean.java

[code lang=”java”]
package javabeat.net.jsp.actions;

public class SampleBean {
String someMessage;

public String getSomeMessage() {
return someMessage;
}

public void setSomeMessage(String someMessage) {
this.someMessage = someMessage;
}
}

[/code]

Now create one jsp file and save it as gettersetterexample.jsp

Listing 8:gettersetterexample.jsp

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<jsp:useBean id="testtag" />

<jsp:setProperty name="testtag" property="someMessage" value="Hello Javabeat" />

<jsp:getProperty name="testtag" property="someMessage" />

</body>
</html>
[/code]

Output
Execute the above gettersetterexample.jsp in Eclipse by selecting Run As > Run On Server, output as below would be seen:
jsp_getsetaction_demo

<jsp:plugin> can tried by using it in some applet.

Previous Tutorial :  JSP Syntax   ||  Next Tutorial : JSP Directives

Filed Under: Java EE Tagged With: JSP Tutorials

JSP Syntax

January 16, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • JSP Tutorials
  • Recommended Books for Java Server Pages (JSP)

This tutorial explains the basic elements used in the JSP pages. Following table lists these JSP elements with syntax.

JSP Tag Description Syntax
Directive Specifies translation time instruction to JSP engine. There are there types of directives: page,include and taglib directives. <%@Directives%>, <%@page..%>, <%@include..%>, <%@taglib..%>
Declaration It is used to declare and define variables and methods. Variables or methods must be declared before you use it in the JSP file. <%!some java code>
Scriptlets Tags are used to embed java code in JSP page. Allows to write free-form java code in JSP page. <%count++%>
Expression Used to print value in the output html file. The value of expression element is converted to String. The expression element can contain any expression that is valid according to the Java Language Specification but you cannot use a semicolon to end an expression. <%=an expression%>
Action Provides request time instructions to the JSP engine. <jsp:actionname/>
Comment Used for documentation and contains texts or statements that JSP container ignores. <%–Any text–%>

The following example shows use of Declaration,Comment,Expression,Scriptlets tags at one place:

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%!int fontSize=10;%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%—- addition Program –%><br>
<% int a = 5;
int b = 3;

int result = a+b;%><br>
<font color="green" size="<%= fontSize %>"><br>

<% out.print(" Total=" +result); %><br>
</font>
</body>
</html>
[/code]

Details of the above code:

  1. <%!int fontSize=10;%> is a declaration of variable fontSize
  2. <%—- addition Program –%> is a comment
  3. <% int a = 5;int b = 3; int result = a+b;%> is a Scriptlet.
  4. <%= fontSize %> is an Expression.

Execute the above code in Eclipse and the output would be:

jsp_syntaxexample_demo

Previous Tutorial :  Create JSP Page in Eclipse   ||  Next Tutorial :  JSP Actions

Filed Under: Java EE Tagged With: JSP Tutorials

Create JSP Page in Eclipse

January 16, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • JSP Tutorials
  • Recommended Books for Java Server Pages (JSP)

Simple JSP Example using Eclipse

Let us write a simple JSP code using Eclipse IDE and execute it using a web application server (Tomcat).

Tools Used

We are using the following tools to write and execute our JSP code:

  • Java 7
  • Eclipse IDE
  • Tomcat 7

Here we are assuming that the reader is well aware of the above mentioned tools and has knowledge of installation of these tools.

Once all the above mentioned tools are installed and configured, open the Eclipse IDE. Follow the below steps to create a simple JSP file using Eclipse.

Step 1: Create a Dynamic project as shown in the image below:

jsp_dynamicproject
Figure 1: Dynamic Project Creation

Step 2: Type the project name as “HelloWorldJSP” and click Next.

jsp_projectnameFigure 2: Name the project

Step 3: Now select the checkbox “Generate web.xml deployment descriptor” and click on Finish button.

jsp_createprojectFigure 3:Finish

Step 4: Once the project is created, you can see the project structure as in the screen below:

jsp_projectstructureFigure 4:Project Structure

Step 5: Now create a JSP file under the WebContent folder as shown below:

jsp_createjspfileFigure 5:Create JSP file

Step 6: Name the file as hellojavabeat.jsp and click on Finish button.

jsp_filenameFigure 6:Give JSP file name

Step 7: Now open the file hellojavabeat.jsp and paste the below contents in it:

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<body>
<% out.print("hello to Javabeat");%>
<p>Today’s date: <%= (new java.util.Date())%></p>

</body>
</html>
[/code]

Here we are printing a message “hello to Javabeat” and current time using the tags which are called scriptlets. More about scriptlet will be discussed in next chapter.

Step 8: Now to execute this JSP, we need to configure a web server (in our case it is Tomcat 7). Now select the file hellojavabeat.jsp and select Run As > Run on Server as shown below:

jsp_executejspfileFigure 7:Execute JSP file

Step 9: Choose the Tomcat version on your system. In our case it is “Tomcat v7.0 Server” and click Next.

jsp_configserver1Figure 8:Configure Tomcat

Step 10:Set the Tomcat path (installed path) and click Next.

jsp_settomcatpathFigure 9: Set Tomcat Path

Step 11: Click Finish

jsp_configserver2

Step 12: Now that you have configured web server with Eclipse, now run the JSP file by selecting Run As > Run on Server. The server will be started and output as shown in the screen below opens up:

jsp_output
Figure 10: Output

Previous Tutorial : JSP Architecture and Lifecycle   ||  Next Tutorial :  JSP Syntax

Filed Under: Java EE Tagged With: Eclipse, JSP Tutorials

JSP Architecture + Lifecycle

January 15, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • JSP Tutorials
  • Recommended Books for Java Server Pages (JSP)

Java Server Pages are part of a 3-tier architecture. A server(generally referred to as application or web server) supports the Java Server Pages. This server will act as a mediator between the client browser and a database. The following diagram shows the JSP architecture.

JSP architectureFigure 1: JSP Architecture

JSP Architecture Flow

  1. The user goes to a JSP page and makes the request via internet in user’s web browser.
  2. The JSP request is sent to the Web Server.
  3. Web server accepts the requested .jsp file and passes the JSP file to the JSP Servlet Engine.
  4. If the JSP file has been called the first time then the JSP file is parsed otherwise servlet is instantiated. The next step is to generate a servlet from the JSP file. The generated servlet output is sent via the Internet form web server to users web browser.
  5. Now in last step, HTML results are displayed on the users web browser.

JSP page in a way is just another way to write a servlet without having to be a Java programming expert. Except for the translation phase, a JSP page is handled exactly like a regular servlet. Now that we saw a big picture in JSP architecture section, lets dive a more deeper and understand how a JSP file is treated in a container and what phases it passes through.

JSP Lifecycle

In this section we will discuss about each phase of a JSP execution cycle. A JSP life cycle is similar to a servlet life cycle with an added step wherein you need to compile a JSP into a servlet. JSP pages are usually managed by a web container which normally contains a servlet container and a JSP container.

JSP LifeCycleFigure 2: JSP Life Cycle

The following table lists each phase of JSP life cycle with a description:

Phase Description
Translation JSP container parses the JSP pages. It then translate the JSP pages to generate corresponding servlet source code. If JSP file name is hello.jsp, usually it is named as hello_jsp.java by the container.
Page Compilation If the translation is successful, the generated java file is then compiled by the container.
Class Loading Once JSP is compiled as servlet class, its lifecycle is similar to servlet. The compiled class is then loaded into the memory.
Instance Creation Once JSP class is loaded into memory, its object is instantiated by the container.
Call jspInit() or Initialization During this phase the JSP class is initialized transformed from a normal class to servlet. Once initialization is over, ServletConfig and ServletContext objects become accessible to JSP class. Method jspInit() is called only once in JSP lifecycle. It initializes config params.
Call _jspService or Request Processing This method is called for each client request.
Call jspDestroy or Destroy This is the last phase and this method is called when the container decides to unload JSP from memory.

Previous Tutorial : Introduction to JSP   ||  Next Tutorial : JSP Example using Eclipse

Filed Under: Java EE Tagged With: JSP Tutorials

Java EE Books

January 14, 2014 by Krishna Srinivasan Leave a Comment

Head First Servlets And JSP by Bryan Basham, Kathy Sierra, Bert Bates

This book will get you way up to speed on the technology you’ll know it so well, in fact, that you can pass the brand new J2EE 1.5 exam. If that’s what you want to do, that is. Maybe you don’t care about the exam, but need to use servlets and JSPs in your next project. You’re working on a deadline. You’re over the legal limit for caffeine. You can’t waste your time with a book that makes sense only AFTER you’re an expert (or worse, one that puts you to sleep).

Learn how to write servlets and JSPs, what makes a web container tick (and what ticks it off), how to use JSP’s Expression Language (EL for short), and how to write deployment descriptors for your web applications. Master the c:out tag, and get a handle on exactly what’s changed since the older J2EE 1.4 exam. You don’t just pass the new J2EE 1.5 SCWCD exam, you’ll understand this stuff and put it to work immediately.

Head First Servlets and JSP doesn’t just give you a bunch of facts to memorize; it drives knowledge straight into your brain. You’ll interact with servlets and JSPs in ways that help you learn quickly and deeply. And when you’re through with the book, you can take a brand-new mock exam, created specifically to simulate the real test-taking experience.
[Read more…]

Filed Under: Java EE Tagged With: Books

Introduction to JSP

January 13, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • JSP Tutorials
  • Recommended Books for Java Server Pages (JSP)

What is JSP?

  • Java Server Pages or as is normally called JSP is a Java based technology that simplifies the developing of dynamic web sites.
  • It is a technology developed by Sun Microsystems, back in 1999.
  • JSP pages are HTML pages with embedded code that allows to access data from Java code running on the server.
  • JSP contains an extension of .jsp
  • JSP provides separation of HTML presentation logic from the application logic.

Advantages of JSP

  • JSP Provides an extensive infrastructure for:
    • Tracking sessions.
    • Managing cookies.
    • Reading and sending HTML headers.
    • Parsing and decoding HTML form data.
  • JSP is Efficient: Every request for a JSP is handled by a simple Java thread
  • JSP is Scalable: Easy integration with other backend services
  • Seperation of roles
    • Developers
    • Content Authors/Graphic Designers/Web Masters
Technology Advantage of JSP
ASP JSP is written in Java hence easier to use compared to ASP which is written in Microsoft specific language.JSP can connect to anydatabase loading the appropriate driver when needed.
Servlets The advantage of JSP programming over servlets is that we can build custom tags which can directly call Java beans.
Javascript Javascript is a client orientated and run, in order to provide support for dynamic websites.JSP is a sophisticated Java servlet.
HTML HTML is client side and provides a means to describe the structure of text-based information in a document.It cannot contain dyamic content.

Next Tutorial : Architecture of JSP

Filed Under: Java EE Tagged With: JSP Tutorials

JPA 2 Criteria API

December 28, 2013 by Krishna Srinivasan Leave a Comment

One of the important feature in JPA 2.0 is using the Criteria API for forming the SQL queries. If you would have worked with the JPA 1.0 version, you must be familiar with the Java Persistence Query Language (JQL) which is similar to writing the SQL queries. This approach is good for the developers who are much familiar with SQL syntax and programming, for the Java developers who are not comfortable with SQL will leads to lot of syntax error. One of the dis-advantage with JQL is, it can not capture the grammar errors at the compile time. If you have errors at SQL, it is thrown errors at the run time. Criteria API solves this problem by providing he strongly typed metamodel objects (Read : Generate MetaModel Using Eclipse or Ant) for writing the queries.

For the beginners who are not familiar with the JPA concepts, please read our article on Introduction to JPA before start reading this tutorial.

JPA Criteria API vs JPQL

JPQL queries are defined as the SQL strings. The only difference with the normal SQL is that JPQL has its own grammar for querying the datbase. For simple static queries, using JPQL is preferred. It will be easy for you to write a query instead of forming it using the CriteriaBuilder. When you build query at run time, writing plain SQL query would have unnecessary string concatenation operations which will leads to lot of syntax issues which can not be detected at the compile time.

String based JPQL queries and JPA criteria based queries are equivalent in power and performance. Choosing one method over the other is also a matter of personal choice. If you choose for your  projects, please consider the pros and cons of each method. However, JPA itself recommends using the Criteria API.

Problem with JPQL Query

Lets look at the below code:

[code lang=”java”]
EntityManager em = …;
String jpql = "select e from Employee where e.id > 20";
Query query = em.createQuery(jpql);
List result = query.getResultList();
[/code]

If you look at the above code, it has one error. The correct code is below:

[code lang=”java”]
String jpql = "select e from Employee e where e.id > 20";
[/code]

These errors are caught at the run time. That is the main dis-advantage of using the JPQL query.

A Simple JPA Criteria Query

The following query represents a simple JPQL query:

[code]
select * from employee e
[/code]

The same query can be built using the JPA criteria API as below:

[code lang=”java”]
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Employee> e = cb.createQuery(Employee.class);
Root<Employee> ee = e.from(Employee.class);
e.select(ee);
[/code]

CriteriaBuilder is the main factory for getting the criteria queries. You can get this object by using the EntityManagerFactory or EntityManager interface.

Typesafe Criteria Query with Metamodel

I have explained in the previous post about the metamodel. It helps you to understand the metamodel and requires understanding the below code.

[code lang=”java”]
EntityManager em = …
CriteriaBuilder qb = em.getCriteriaBuilder();
CriteriaQuery<Employee> c = qb.createQuery(Employee.class);
Root<Employee> p = c.from(Employee.class);
Predicate condition = qb.gt(p.get(Employee_.id), 20);
c.where(condition);
TypedQuery<Employee> q = em.createQuery(c);
List<Employee> result = q.getResultList();
[/code]

The above code has many new things which is introduced from JPA 2. But, here we have to understand the TypedQuery which is the important concept for making the query is strongly typed.  Also look at the “Employee_” which is generated as part of the metamodel.

Reference Links

  • Dynamic, typesafe queries in JPA 2.0
  • JPA Query API
  • JPA 2.0 Features

Filed Under: Java EE Tagged With: Hibernate 4 Tutorials, JPA 2 Tutorials

TypedQuery in JPA 2

December 28, 2013 by Krishna Srinivasan Leave a Comment

One of the new feature introduced in JPA 2.0 is using the TypedQuery interface for building the query. This can be used with the CriteriaBuilder in JPA 2. As the name itself specifies, the main purpose of using the TypedQuery would be to narrow the result type and eliminate the need for type casting after the result is returned. Prior to this feature, the Query interface returns the generic object which needs to be typecast to the specific instance. This will have lot of issues like ClassCastException at run time if there is mismatch in both the types. JPA 2.0 added TypedQuery and over-loaded methods of EntityManager that allow you to specify the query result type.

Lets look at the simple example for using the TypedQuery.

[code lang=”java”]
EntityManager entityManager = entityManagerFactory.createEntityManager();
TypedQuery<Employee> queryEmployee = entityManager.createNamedQuery("employee.findByEmployee",
Employee.class);
queryEmployee.setParameter("employee", "Anand");
Employee employee = queryEmployee.getSingleResult();
[/code]

Filed Under: Java EE Tagged With: JPA 2 Tutorials

  • « Previous Page
  • 1
  • …
  • 11
  • 12
  • 13
  • 14
  • 15
  • …
  • 21
  • Next Page »

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved