Sunteți pe pagina 1din 14

Java Server Pages

-----------------
Server Side Scripting Language. It is implemented in Java, so they are cross
platform and inherit all of java's other strengths. They are built on top of
servlets, so they are fast and can be easily changed.

They are extensible, and programmers can create new objects and functionality using
Java beans.

Webserver's running JSP


------------------------
Internet Information Server 5.0 (WindowsNT)
JavaWebserver 2.0
Apache Tomcat Server - This Server provide full support for JSP(WindowsNT)
J2EE server
Weblogic
Websphere
pws
glass fish
pranathi--- hyderabad
joomla
ramp

Life cycle of JSP


-----------------
1. Browser Request HTML or JSP
2. The Request are received by the server.
3. Server sends request to Java Engine
4. If needed, the Java engine reads the .jsp file
5. The JSP is turned into a Servlet, compiled and loaded
6. The servlet runs and generates HTML
7. Java engine sends HTML to server
8. Server sends HTML back to browser

Advantages
-----------
1. Flexible Environment
2. It supports direct beans information
3. It is an Interpreter Language(Automatically compiled)
4. It supports XML(Extensible Markup Language) tags

Structural syntax of JSP


--------------------------
Constructor
-----------
jspInit() - Initialization
jspService() - Processing request
jspDestroy() - Destroyed
Comments
---------
< %-- ...text... --% > <!-- HTML Comment -->

JSP comments are stripped out by the JSP Engine at Translation time.

Declarations
------------

<%! type varname; %>


<%! returntype methodname(argument1,argument2...){} %>

<%! String s=null; %>


<%! void disp() {} %>

Declarations may be used to add variables or methods to a JSP.

<% (Scriptlet)
Statements
%>

Expression
-----------
<%= Expression %>
<%= a+b %>

int x=20;

<input type='text' name='t1' value='10'>

<input type='text' name='t1' value='<%=x%>' >

The expression tag places the printable form of a Java expression into the
output of a page.

Scriptlets
-----------
<% ...java code ...%>

Scriptlets allow arbitary Java code, and eventually other languages, to be


placed in a JSP. For the most part such code should reside in beans and other
classes, but there are times when placing it in a page is unavoidable. Complex
logic can be added to pages by surrounding regions of text with scriptlets, when
one scriptlets ends with an opening brace and a second one provides a matching
close.

Eg:
----
HTML file
--------------
<html>
<body>
<h1> JSP </h1>
<form method=get action="first.jsp">
<br>
<input type=submit>
</form>
</body>
</html>

JSP file
---------
<%@ page language="java" %>
<%! String s=null; %>
<%s="csc" %>
<B>s= <%= s %>
</B>

Include Directive
-----------------
<%@ include file=" " %>

The include directive adds the text of one JSP or Other file to another file
at translation time.

Page Directive
---------------------
<%@ page options ... %>

The page directive specifies a large number of options that affect the entire
page. Each of these options may be used independently

language="java"

This code will specifies what language will be used in scriplets. Currently
only java is supported

extends = "base class"

This code can force the generated servlet to extend a specific class. This
should be used very rarely

import="package.class" import="java.sql.*"
import="package.*" import="java.util.Date"

Import parameters within a page directive turn into import statements in the
generated java file. Multiple import statements can be used.

session=true|false

By default, the first time a user access any JSP on a site, a session is
started for that user and the user will be issued a cookie. This behaviour can be
disabled by setting the session flag to false.

buffer="none|sizekb"

This flag sets the amount of data that will be buffered before being sent to
the user. The default is 1024Kb. None indicates that all output should be sent
directly.

autoflush="true|false"

if buffering is turned on and this value is set to true, data will


automatically be sent to the user when the buffer is full. if buffering is on and
this value is set to false, an exception will occur when the buffer is full. is
buffering is not on, this value has no effect. The default is true
isThreadSafe="true|false"

This value indicates whether it is safe for the JSP engine to send multiple
requests to a page simultaneously. The default is true. Setting it to false is
equivalent to declaring the generated servlet will implement SingleThreadModel.

info="text"

This value sets a description of the page's purpose, its author, or any other
information. Anything placed here will be accessible through the resulting
servlet's getServletInfo method.

errorPage="pathToErrorPage"
errorPage = "customerror.jsp"

This value customizes the page sent to the user when an error occurs at run
time.

isErrorPage="true|false"

This value indicates that a JSP will be used as an error page. When this is
true, the JSP will have access to an additional implicit value called exception,
which will be Exception or Throwable representing the error that occured. The
default for this value is false.

contentType="mime-type" (Multipurpose Internet Mail Extensions)

This value changes the content type of the page. In current implementations,
It is equivalent to request.set("mime-type"). The default is text/html.
(Multipurpose Internet mail extension)

Implicit Objects available in JSP


---------------------------------
Out - output stream for page content
Config - Servlet configuration data

Request - Request data, including parameters


Response - Response data
Session - User specific session data
Application - Data shared by all application pages.
PageContext - Context data for page execution
Exception - Uncaught error or exception
Page - Page's servlet instance

Request Object
--------------
Used to get information from the client browser

Methods
-------
Enumeration getParameterNames() Returns the names of all request
parameters
String getParameter(name) Returns the first (or primary) value of a
single request parameter
Enumeration getParameterValues() Retrieves all of the values for a single
request parameter
getHeaderNames() Retrieves the names of all headers associated with request
getHeader(name) Retrieves the value of a single request header, as a
string
getHeaders(name) Returns all of the values for a single request header
getIntHeader(name) Returns the value of a single request header,as an
integer
getDateHeader(name) Returns the value of a single request header, as a
date
getCookies() Retrieves all of the cookies associated with the
request
getMethod() Returns the HTTP(eg.GET , POST) method for the request.
getRequestURI() Returns the request URL, up to but not including any
string
getQueryString() Returns the query string that follows the request URL, if
any
getSession() Retrieves the Session data for the request(ie., the session
implicit object), optionally creating it if it does not already exists
getRequestDispatcher(path) Creates the request dispatcher for the indicated
local URL
getRemoteHost() Returns the fully qulified name of the host that sent
the request.
getRemoteAddr() Returns the network address of the host that sent the
request
getRemoteUser() Returns the name of the user that sent the request,
if known.
getProtocol() Http/1.1

Eg1:
---
<html>
<body>
Hello user! You are using a computer
called <%= request.getRemoteHost() %>!
</body>
</html>

Eg2:
------
<html>
<body>
Hello user! I am on a computer called
<%= request.getServerName() %>, and you are using a computer
called <%= request.getRemoteHost() %>!
</body>
</html>

Eg3:
------
<html>
<head> <title> Request fields </title> </head>
<body bgcolor="#ffffff">
<table border="1">
<tr>
<td> You are using this authorization type: </td>
<td><%= request.getAuthType() %> </td>
</tr>
<tr>
<td> You are using this request method: </td>
<td><%= request.getMethod() %> </td>
</tr>

<tr>
<td> Characters are encoded using this scheme: </td>
<td><%= request.getCharacterEncoding() %> </td>
</tr>

<tr>
<td> The protocol used for this request was: </td>
<td><%= request.getProtocol() %> </td>
</tr>

<tr>
<td> The scheme used for this request was: </td>
<td><%= request.getScheme() %> </td>
</tr>

Eg4:
-------
<%@ page language="java" %>
<h1> Request Info </h1>
<%
out.print("<table>");
out.print("<tr><td> Protocol = <td>" + request.getProtocol());
out.print("<tr><td> ServerName = <td>" + request.getServerName());
out.print("<tr><td> ServerPort = <td>"+request.getServerPort());
out.print("<tr><td> Remote Address = <td>"+request.getRemoteAddr());
out.print("<tr><td> Method = <td>"+request.getMethod());
out.print("<tr><td> RequestURI = <td>"+request.getRequestURI());
out.print("<tr><td> QueryString = <td>"+request.getQueryString());
out.print("<tr><td> Session = <td>" + request.getSession());
out.print("<tr><td> RemoteHost = <td>" + request.getRemoteHost());
out.print("<tr><td> RemoteUser = <td>" + request.getRemoteUser());
out.print("</table>");
%>

Eg5:
-----
<body>
<form method=get action="form.jsp"><br>
Name <input type=text name=Name><br>
Last Name <input type=text name=Last><br>
Mail Id <input type=text name=Email><br>
Send <input type=submit>
</form>
</body>

<%@ page language="java" import="java.util.Enumeration" %>


<%! Enumeration e=null; %>
<%! String Name=null; %>
<%! String value=null; %>
<%
e=request.getParameterNames();
out.print("<table border=2>");
while(e.hasMoreElements()) {
Name=(String)e.nextElement();
value=request.getParameter(Name);
out.print("<tr><td>" + Name + "<td>" + value);
}
out.print("</table>");
%>

Eg6:
----
<html>
<title> checkBox </title>
<body>
<form method="post" action="http://localhost:8080/check.jsp">
<b> Click the CheckBox below </b>
<input type=checkbox value=red name="rcolor" checked> Red
<input type=checkbox value=blue name="rcolor" > Blue
<input type=checkbox value=green name="rcolor" > Green
<input type=submit value=enter>
</form>
</body>
</html>

<html>
<title> Check box </title>
<body> <b> The color you selected is </b>
<% String names[]= request.getParameterValues("rcolor") ;
for(int i=0;i<names.length;++i)
{
out.println(names[i]);
}
%>
</body>
</html>

Eg7:
-----
<%@ page import="java.util.Date" %>
<%! Date now = new Date(); %>
<html>
<head><title> Current Time </title></head>
<body>
<% now = new Date(); %>
Hello! At the tone, the time will be exactly
and <%= now.getHours() %>:<%= now.getMinutes() %>
and <%= now.getSeconds() %> seconds.
<p>
<b> Beeep! </b>
</body>
</html>

Eg8:
-----
<%@ page language="java" import="java.io.*" %>
<%! FileReader fi=null; %>
<%! public void jspInit() {
try {
fi=new FileReader("d:/demo/jsp/JSPText1.txt");
}catch(FileNotFoundException fx) {}
}
%>
<%
int r;
try {
while((r=fi.read()) != -1)
out.print((char)r);
}catch(Exception ex)
{
out.println(e);
}
%>
demofile
-----------
This is a sample demofile
Eg9:
-----
<%@ page isErrorPage="true" %>
<body> <%=exception.getMessage() %>
</body>

<%@ page errorPage="errorpage.jsp"%>


<%
if(true) {
throw new Exception("A pure JSP Exception");
}
%>

Eg10:
-----
forward.html
------------------
<body>
<form method=get action="http:\\localhost:8080\forward.jsp">
<h1> Forward jsp </h1>
send <input type=submit>
</form>
</body>

forward.jsp
-------------
<%@ page language="java" %>
<jsp:forward page="inbox.jsp"/>

inbox.jsp
---------------
<%@ page language="java" %>
<h1> JSP forward tag </h1>

Response Object
------------------------
Response Object represents the response that will be sentback to a user as a
result of processing the JSP page. This object implements the
javax.servlet.ServletResponse interface.

Methods
-------------
setContentType(string) - Sets the Content type("text/html") and character encoding
(ISO)
getCharacterEncoding() - Default character Encoding
setContentLength(int) -
OutputStream getOutputStream()
Writer getWriter()
addCookie(cookie)
setStatus(int sc) -
sendError(int sc)
sendError(int sc,String sm)
sendRedirect(String URL)

Sc_constants
-------------------
SC_CONTINUE = 100
SC_OK = 200
SC_CREATED = 201
SC_ACCEPTED = 202
SC_NOT_FOUND = 404
SC_NOT_ACCEPTABLE = 406
SC_BAD_GATEWAY = 502

response.sendRedirect Method
-------------------------------------------
sample.html
----------------
<form method=get action="sample.jsp">
Enter login name : <input type=text name=login><br>
<input type=submit>
</form>

sample.jsp
-------------
<%@ page language="java" %>
<%! String l=null; %>
<%
l = request.getParameter("login");
if(l.equals("scott"))
response.sendRedirect("mypage.jsp");
else
response.sendError(404);
%>

inbox.jsp
-------------
<h1> inbox file </h1>

Session
-------------
Used to cache information about a specific browser instance. The server gives
the browser a unique token(SessionID) in response to its first request so the
browser can identify itself to the server for subsequent request.

Methods
--------------
String getId()
long getCreationTime()
long getLastAccessedTime()
boolean isNew()
putValue(String key,Object value)
Object getValue(String key)
removeValue(String key)

session.jsp
--------------
<%@ page language="java" import="java.util.Date" %>
<h1> Session Info </h1>
<%

out.print("<table>");
out.print("<tr><td> Creation time <td>" + new
Date(session.getCreationTime()));
out.print("<tr><td> Last Accessed Time <td>" + new
Date(session.getLastAccessedTime()));
out.print("<tr><td> New <td>" + session.isNew());
out.print("</table>");
%>

session2.jsp
-----------------
<%@ page language="java" %>
<%
String name=(String)session.getValue("BookName");
if(name==null) {
session.putValue("BookName","Professional JSP");
response.sendRedirect("session3.jsp");
} else {
out.println(name);
}
%>

session3.jsp
-----------------
<%@ page language="java" %>
<%
String s=(String)session.getValue("BookName");
out.print(s);
%>

JDBC Connectivity
----------------------------
<%@ page language="java" import="java.sql.*" %>
<%! Connection con=null; %>
<%! Statement st = null; %>
<%! String qry; %>
<%! String uname,pword,rpword,dob,addr,email; %>
<%! int age,phno; %>
<%
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:mysql","sa","killer");
}catch(Exception e)
{
out.println(e);
}
%>
<%
String label;
try
{
label = request.getParameter("cmd");
if(label.equals("Add"))
{
uname = request.getParameter("uname");
pword = request.getParameter("pword");
rpword = request.getParameter("rpword");
dob = request.getParameter("dob");
age = Integer.parseInt(request.getParameter("age"));
addr = request.getParameter("addr");
phno = Integer.parseInt(request.getParameter("phno"));
email = request.getParameter("email");

st = con.createStatement();
qry = "Insert into register values('" + uname + "','" + pword +
"','" + rpword + "','" + dob + "'," + age + ",'" + addr + "'," + phno + ",'" +
email + "')";
int r = st.executeUpdate(qry);
System.out.println(r + " row(s) Inserted");
}
else if(label == null)
{
out.println("No Values");
}
}catch(Exception e)
{
out.println(e);
}
%>
<html>
<head>
<title> Register Form </title>
<script>
function AddRec()
{
document.reg.cmd.value = "Add"
}
</script>
</head>
<body bgcolor="lightyellow">
<h2 align=center> Registration Form </h2>
<table align=center>
<form method=post action="DBRegister.jsp" name="reg">
<tr>
<td> Username <td> <input type=text name=uname>
<tr>
<td> Password <td> <input type=password name=pword>
<tr>
<td> Retype Password <td> <input type=password name=rpword>
<tr>
<td> Date of Birth <td> <input type=text name="dob">
<tr>
<td> Age <td> <input type=text name="age">
<tr>
<td> Address <td> <textarea rows=5 cols=25 name="addr"> </textarea>
<tr>
<td> Phone No <td> <input type=text name="phno">
<tr>
<td> Email <td> <input type=text name="email">
<tr>
<td> <td> <input type=submit onClick="AddRec()"> <input type=reset> <input
type=hidden name="cmd">
</form>
</table>
</body>
</html>

Javabeans Vs JSP
--------------------------
1. Security
2. Reusability of Source code

<jsp:useBean id="id_name" class="classname"/>

<jsp:setProperty name="id_name" property="property_name" param="paramname"


value="value"/>

<jsp:getProperty name="id_name" property="property_name"/>

getNextInt()
setNextInt()
Scope
------------
Session
Application
Request
Response

Steps to Create Bean file and extract in JSP


-------------------------------------------------------------
1. Create a java file and compile it.
2. Copy the class file to c:\javawebserver2.0\classes
3. Create JSP file in public_html and run it.

Eg:
------
paintbrush.java
---------------------
public class paintbrush {
private String color;
public paintbrush() {
color="red";
}
public void setColor(String col) {
color=col;
}
public String getColor() {
return color;
}
}
paint.jsp
-----------
<%@ page import="paintbrush" %>
<pre> <h1>
<jsp:useBean id="p1" class="paintbrush" scope="session"/>
<form method=post action="paint.jsp">
Current color value :
<jsp:getProperty name="p1" property="color" /></h1>
<jsp:setProperty name="p1" property="color" value="blue"/>
<input type=submit value=Repeat>
</pre>
</form>

Cookies
-----------------
For Creating Cookie
--------------------------
Cookie c = new Cookie("Cookie_name","Value")
request
-------------
String getName() - Get the name of the Cookie
String getValue() - Get the value of the Cookie
response
--------------
response.addCookie(c);

Cookie[] request.getCookies() - get the Cookies values.

Eg:
-----
Login.html
---------------
<html>
<body>
<h2 align=center> Login Form </h2>
<table align=center>
<form method=post action="Cookie1.jsp">
<tr>
<td> Username <td> <input type=text name="uname">
<tr>
<td> Password <td> <input type=password name="pword">
<tr>
<td> <td> <input type=submit> <input type=reset>
</form>
</table>
</body>
</html>

Cookie1.jsp
----------------
<%@ page language="java" %>
<%! String uname,pword; %>
<%
uname = request.getParameter("uname");
pword = request.getParameter("pword");

out.println("<h2 align=center> Adding Cookies </h2>");


Cookie c1 = new Cookie("username",uname);
Cookie c2 = new Cookie("password",pword);

response.addCookie(c1);
response.addCookie(c2);

out.println("<a href=http://localhost:8080/Cookie2.jsp> Next </a>");


%>

Cookie2.jsp
-------------------
<%@ page language="java" %>
<%! String un,pw; %>
<%
Cookie c1[] = request.getCookies();
for(int i=0;i<c1.length;i++)
{
if(c1[i].getName().equals("username"))
{
un = c1[i].getValue();
}
else if(c1[i].getName().equals("password"))
{
pw = c1[i].getValue();
}
}

out.println("<font face=Arial size=4 color=blue>");


out.println("Username : " + un + "<br>");
out.println("Password : " + pw + "<br>");
out.println("<a href=http://localhost:8080/Cookie3.jsp> Next </a>");
%>

Cookie3.jsp
----------------
<%@ page language="java" %>
<%! String un,pw; %>
<%
Cookie c1[] = request.getCookies();
for(int i=0;i<c1.length;i++)
{
if(c1[i].getName().equals("username"))
{
un = c1[i].getValue();
}
else if(c1[i].getName().equals("password"))
{
pw = c1[i].getValue();
}
}

out.println("<font face=Arial size=4 color=red>");


out.println("Username : " + un + "<br>");
out.println("Password : " + pw + "<br>");
%>

S-ar putea să vă placă și