Sie sind auf Seite 1von 9

Please visit http://arutapub.brinkster.

net for Advanced Java and other books

Notes from : Prof Rajendra Salokhe

JSP V/S SERVLETS

1.JSP is a webpage scripting language that can generate dynamic content while
Servlets are Java programs that are already compiled which also create dynamic web
content
2.Servlets run faster compared to JSP.
3.JSP is compiled into Java Servlets.
4.It’s easier to code in JSP than in Java.
5.JSP and Java Servlets are usually used in conjunction nowadays.
6. JSP is more convenient than Servlet and JSP is clearly superior, shorter, simple
and easier to use.
7. A HTML web page writer/designer can write the JSP without knowing Java, using
beans and custom tags written by Java experts.
8. The Java Server Pages are document-centric. Servlets, on the other hand, look and
act like programs.
9. A JSP pages contain a mixture of HTML, Java scripts (not JavaScript), JSP
elements, and JSP directives while . A servlet is a Java class implementing the
javax.servlet.Servlet interface that runs within a Web or application server's servlet
engine, servicing client requests forwarded to it through the server.

JSP TAGS
JSP uses the following tags
1] Declaration
2] Expressions
3] Directives
4] Scriplets
5] Comments
6] Actions
7] Implicit JSP objects
8] Error Pages
9] JavaBeans

We will discuss the tags one by one


DECLARATIONS
This tag is useful for defining the functions and variables to be used in the JSP. They
do not generate any output to the screen.
Declarations start with <%! and end with %>.
You can embed any amount of java code in the JSP Declaratives. The variables and
functions defined in the declaratives are class level and can be used anywhere in the
JSP page.

<html>
<body>
<%!
int count=0;
private int incrCount(){
// increment count and return the value
count++;
return count;
}
%>
<p>Values of count are:</p>
<p><%=incrCount()%></p>
<p><%=incrCount()%></p>
<p><%=incrCount()%></p>
</body>
</html>

OUTPUT

In the above program we have declared the ‘count’ variable as well the incrCount()
method.
EXPRESSIONS
The expression tag is used to output any data on the generated page. These data are
automatically converted to string and printed on the output stream.
An expression tag contains a scripting language expression that is evaluated,
converted to a String, and inserted where the expression appears in the JSP file.
Because the value of an expression is converted to a String, you can use an
expression within text in a JSP file.
You cannot use a semicolon to end an expression.
<HTML>
<BODY>
<%! double Faren= 84; %>
The Centigrade is
<%=(Faren-32)*5/9 %>

</BODY>
</HTML>

OUTPUT

The Centigrade is 28.88888888888889

DIRECTIVES
The directives are used to import packages, define error handling pages or the
session information of the JSP page. They do not generate screen output. JSP
Directives control the processing of an entire page. Directive examples include setting
a scripting language, setting an error page, including other sections, and setting a
character encoding.
The syntax for the directives is

<%@directive attribute="value" %>


The directives are page,include and taglib while the attributes are import, session,
errorPage and contentType.

THE PAGE DIRECTIVE


The examples of page directive are
<%@ page language="java" %>
Sets the JSP script language to java.
<%@ page import="java.io" %>
<%@ page session="true" %>
Tells JSP that the page participates in a session. Defaults is
true.
<%@ page contentType="text/plain; charset=utf-8" %>
Sets the content type and character encoding of the page.
<%@ page errorPage="path" %>
Defines a page to display if an error occurs in the JSP page
THE include DIRECTIVE

The examples are


<%@ include file="path" %>
Includes the raw file path at translation time. A file on the local system to be
included when the JSP page is translated into a servlet.
THE taglib DIRECTIVE
<%@ taglib prefix="x" uri="foo" %>
Configures tags with prefix x to use the tag library foo.
[You may refer http://java.sun.com/products/jsp/tags/tags.html]
SCRIPTLETS
JSP scriptlets are similar to expressions except they are designed for multiple lines of
code in which you can define variables and control structures. Unlike a JSP
expression and JSP scriptlet does not output anything to the client side unless you use
specific output functions to do so. A JSP scriptlet is embedded in HTML using a
similar tag structure, but without the equals sign.
EXAMPLE

<html>

<form action=http://localhost:8080/jsp-examples/jsp2/el/numbers.jsp

method=post>
Type a number :
<input type=text name=t1>

<br>
<input type=submit >
</form>
</html>
<%-- numbers.jsp --%>
<%! int n; %>
<%

n=Integer.parseInt(request.getParameter("t1"));
out.println("You typed : "+n);
out.println("<br>");
if(n>=10 && n<=100)
out.println("You typed a number between 10 and 100 ");
else
out.println("You typed a number above 100");

%>

COMMENTS
The JSP comments different a little than the HTML comments. They are not included
in the output page.
<%-- comments --%>
However if you want that the same should be included then you can use the HTML
comments as
<!-- comments --!>

ACTIONS
Action tags in JSP are used to perform action on particular page. They provide
runtime instructions to the JSP elements. There are three main actions
1.include
2. forward
3. useBean.
1. include action tag

‘include’ action tag is similar to include directive. The Actions ‘include’ tag is first
compiled and the output is inserted in the file with parent file.The actions ‘include’
can be static or dynamic.
The example is
<jsp:include page="header.jsp" />
You can just write ‘include’ instead of ‘jsp:include’. The jsp:include adds the content
of the included page at runtime while ‘include’ adds it at compilation time.

2. Forward action tag


Forward action tag in JSP transfer the control of one JSP page to another JSP,
servlet or HTML file with specify URL and maintains the same request and
response objects.
The example is
<jsp:forward page="relativeURL | or <%= expression %>" />
<jsp:forward page="success.jsp" />

3. useBean action tag


Before you can use a bean in a JSP page, you must declare that you're about to use it by
invoking the <jsp:usebean> action tag .The useBean action tag allows a JSP to create
an instance or receive an instance of a Java Bean. It is used for creating or
instantiating a bean with a specific name and scope.
THE HTML FILE
<html>
<form action=http://localhost:8080/jsp-examples/jsp2/el/SB.jsp method=post>
enter message:
<input type=text name="t1">
<br>
<input type=submit value="Click">
</form>
</html>
THE JSP FILE (SB.jsp)

<HTML>
<HEAD>
<TITLE>JavaBeans and JSP</TITLE>

</HEAD>

<BODY>

<CENTER>
<p><font face="Castellar">JAVA BEANS AND JSP</font></p>
</CENTER>
<%! String msg; %>
<%
msg=request.getParameter("t1");

%>
<jsp:useBean id="test" class="first.SimpleBean" />
<jsp:setProperty name="test"
property="message"
value="<%= msg %>" />

<CENTER>
<H1>Message: <I>
<jsp:getProperty name="test" property="message" />
</I></H1>
<CENTER>
</BODY>
</HTML>
jsp:setProperty tag is used to set the value of one or all the properties of given
JavaBean. you can initialize properties of the bean with the <jsp:setProperty> tag.
You can set bean properties either to values that you specify or to values passed in
from an HTTP request, such as from a form submission.
The ‘name’ attribute sets the name of an instance of a Bean that has already been
created or located with a <jsp:useBean> tag
The ‘property’ attribute Stores all of the values in the request object parameters
(called request parameters) in matching Bean properties.
The ‘value’ attribute sets a bean property to value.
jsp:getProperty tag gets the value of a Bean property so that the same can be
displayed it in a result page.
THE BEAN FILE
(SimpleBean.class)
package first;
public class SimpleBean {
private String message = "No message specified";
public String getMessage() { return(message); }
public void setMessage(String message) { this.message = message; }

OUTPUT

Since we have declared a package ‘first’, the class file will be created in folder
named ‘first. (There is no need to create jar files).
You have to copy the SimpleBean.class file to
C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\jsp-
examples \WEB-INF\classes\first
folder. Create the folder named ‘first’ if you have compiled the bean class elsewhere
and the folder is not available in the classes folder.
The value of ‘message’ is received by the bean through getMessage.The setMessage
sets the message value to the received value which is returned to JSP.

THE <jsp:param TAG

It is possible to pass parameters to dynamically included resources with the <jsp:


param tag.

THE errorPage TAG

A JSP page specifies the error page with the page directive and errorPage attribute.
When an unhandled exception occurs, any unflushed output in the output stream is
discarded and the error page is immediately executed.

CONNECTING TO DATABASE
CONNECT.HTML FILE
<html>
<form action=http://localhost:8080/jsp-examples/jsp2/el/ConnectToJDBC.jsp
methos=post>
Enter Query
<input type=text name=t1 size=100>
<br>
<input type=submit >
</form>
</html>

ConnectToJDBC.jsp FILE

<%@ page import="java.sql.*"%>


<%@ page import="java.io.*"%>
<%
String s=null;
response.setContentType("text/html");
s=request.getParameter("t1");
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection cn=DriverManager.getConnection("jdbc:odbc:servletjspdsn");
Statement st=cn.createStatement();
String sr=s;
if(sr.startsWith("select"))
{
ResultSet rs=st.executeQuery(sr);
ResultSetMetaData rsmd=rs.getMetaData();
out.println("<html><table border=1>");
String str1="";
for(int k1=1;k1<=rsmd.getColumnCount();k1++)
{

str1=str1+"<td>"+rsmd.getColumnName(k1)+"</td>";
}
out.println("<tr>"+str1+"</tr>");
while(rs.next())
{
out.println("<tr>");
for(int k=1;k<=rsmd.getColumnCount();k++)
{

out.println("<td>");
out.println(""+rs.getString(k));
out.println("</td>");
}
out.println("</tr>");
}
}else
{
st.executeUpdate(sr);
out.println("Update successfully");
}
cn.close();
st.close();
}
catch(Exception e){out.println(e);}

%>

Explain the life-cycle mehtods in JSP?

A:

THe generated servlet class for a JSP page implements the HttpJspPage interface
of the javax.servlet.jsp package. Hte HttpJspPage interface extends the JspPage
interface which inturn extends the Servlet interface of the javax.servlet package.
the generated servlet class thus implements all the methods of the these three
interfaces. The JspPage interface declares only two mehtods - jspInit() and
jspDestroy() that must be implemented by all JSP pages regardless of the client-
server protocol. However the JSP specification has provided the HttpJspPage
interfaec specifically for the JSp pages serving HTTP requests. This interface
declares one method _jspService().
The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is
called before any other method, and is called only once for a servlet instance.
The _jspservice()- The container calls the _jspservice() for each request, passing
it the request and the response objects.
The jspDestroy()- The container calls this when it decides take the instance out of
service. It is the last method called n the servlet instance.

Scope and state maintenance in JSP Scope Description


page Object is accessible only by a single client from the page on which it is created.
request Object is accessible by a single client for the lifetime of a single client request.
session Object is accessible by a single client from anywhere in the application for the
lifetime of an entire user session. application Object accessible is by any client from any
page within the application for the lifetime of the application.

Das könnte Ihnen auch gefallen