JSP Features & Syntax Scripting Elements Scripting elements allow Java code to be written directly into the JSP page. It is compiled and available within the page. There are three kinds of scripting elements: declarations expressions scriplets 1.Declarations Declarations are used to define variables and methods -- both instance and static -- that are likely to be repeated. Thus, they correspond to writing code at the Java Class level. They can also be used to overwrite jspInit or Advanced JAVA Lab Manual Dept., of MCA GRIET
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
JSP Features & Syntax
Scripting Elements
Scripting elements allow Java code to be written directly into the JSP page. It is compiled and available within the page. There are three kinds of scripting elements:
declarations expressions scriplets
1.Declarations
Declarations are used to define variables and methods -- both instance and static -- that are likely to be repeated. Thus, they correspond to writing code at the Java Class level. They can also be used to overwrite jspInit or jspDestroy methods that are created when the JSP is compiled.
The basic form is:
<%! Java variable or method %>
Example:
<%! String message; %>
Advanced JAVA Lab Manual Dept., of MCA GRIET
or
<% String message = "Hello, World, from JSP"; %>
2. Expressions
Expressions are references to variables, methods, or composable structures of such. They are most often used as a way of dynamically inserting a value into a parameter slot. You may also think of them as representing a call to a static method. They are evaluated at run time and the results inserted into the output stream at the location of the expression.
Note that expressions do not include a semicolon(;).
3. Scriplets
Scriplets are sections of Java code that are executed in place. They can be as simple as a declaration of
Advanced JAVA Lab Manual Dept., of MCA GRIET
a variable that is treated as an instance variable, but they can also include loops that mix Java and HTML.
The basic form is:
<% Java code %>
Example:
<% if ( sessionBean.getLoginType() == 0 ) { %>
<p align="center"><B>Super User</B></p>
<%} else if ( sessionBean.getLoginType() == 1 ) {%>
<p align="center"><B>Administrative User</B></p>
<%} else if ( sessionBean.getLoginType() == 2 ) {%>
<p align="center"><B>Author User</B></p>
<%} else {%>
<p align="center"><B>Registered User</B></p>
<%} %>
Advanced JAVA Lab Manual Dept., of MCA GRIET
Implicit Objects
Several local variables are available to scriptlets and expressions through the ServletContext. They include the following:
application config session request response out page pageContext exception
Most are self-explanatory. Application, which is the ServletContext of the JSP and stores attributes for the duration of the application.. Page is the current jsp page and stores attributes associated wit the current page. Out is a writer that can be used by scriplets to put information onto the output stream.
Directives
Directives are instructions to the JSP compiler. The three types of directives are:
Advanced JAVA Lab Manual Dept., of MCA GRIET
page include taglib
Only the include directive will be discussed here.
The include directive instructs the JSP compiler to fetch the file referenced in the directive and insert it into the page at that point. Thus, it can be used to include standard boilerplate, such as headers and footers.
The basic form is:
<%@ directive %>
Example:
<%@ include file="header.html" %>
If the included file is HTML, it should not repeat any HTML HEAD or BODY tags that may already be defined in the output stream.
Actions
Actions are JSP tags that transfer control to other server objects or perform operations on other objects. They may also generate output. They are another means of building view objects within a M - V - C architecture. There are some half-dozen
Advanced JAVA Lab Manual Dept., of MCA GRIET
action tags. The three that will be discussed here are:
include forward useBean
All are marked by tags that have the following form:
<jsp:action attributes />
Include
The include tag is very similar to the include directive, discussed above. It allows content to be included in place. The content may be either static or dynamic.
Here is an example:
<jsp:include page="header.html" flush="true"/>
Forward
The forward tag transfer control to a static or dynamic resource, usually referenced by a URL, that exists on the same server.
The useBean action is by far the most powerful and the most complex of the JSP actions. It allows a JSP to create an instance or receive an instance of a Java Bean.
The JSP could provide typical servlet controller functions by passing the request object to the bean and allowing it to extract user parameters and call back-end functions, just like a servlet. However, supporting those functions in a servlet is generally considered a better practice. However, rather than transferring result values to another type, such as a Hash table, and passing that object to a JSP, if a back-end process returned a result bean back to a controller servlet, it could simply pass this bean to the relevant JSP.
In fact, so long as the Java server supports it and is properly configured, it permits beans to be passed from servlet to JSP, to another JSP, to another servlet, etc. This is called chaining and is an
Advanced JAVA Lab Manual Dept., of MCA GRIET
architecture used to provide incrementally processing using filtering principles.
JSP Page Scopes
All jsp objects exist within a particular scope or context. There are four jsp scopes:
page request session application
Request and session should be familiar. Page is the current jsp page. Application is the current overall application and can include multiple sessions. Thus, all users sharing a given application, who may be associated with different sessions, would have access to the same set of application-scope resources.
Programs
-------------
1. HelloWorld.jsp
Advanced JAVA Lab Manual Dept., of MCA GRIET
------------------------<HTML><HEAD><TITLE>Hello Program </TITLE></HEAD> <body> <h1>Hello World message from Ganapathi Raju</h1> <!-- This is JSP comment --> <%out.println("Hello World");%> </body><html>
Note: example of Declarations of var:- ---------------------------------------------- <%! int a; %> <%! int a=50; %> <%! int a=50,b=100; %> <%! int a=75;String s="Ganesh"; %> <%! int a=50;float f=10.2f;%>
// program with page directive8.Excel.jsp--------<%@ page contentType="application/vnd.ms-excel" %><%-- Note that there are tabs, not spaces, between columns. --%>1997 1998 1999 2000 2001 (Anticipated)12.3 13.4 14.5 15.6 16.7
9.Ex.html----------<body> here specify the format either "excel" or "html" <form name="f1" action="ApplesAndOranges.jsp"> <br><input type="text" name="format" ><br>
Advanced JAVA Lab Manual Dept., of MCA GRIET
<input type="submit"></body>
Ex.jsp-----------<HTML><HEAD><TITLE>Comparing Apples and Oranges</TITLE></HEAD><BODY><CENTER><H2>Comparing Apples and Oranges</H2>
//Program with Method Declaration and call10 met.jsp ------------ <body> <%! public int mysum(int a,int b)
Advanced JAVA Lab Manual Dept., of MCA GRIET
{ return a+b; }
%> <%out.println("<h1>sample method invocation</h1>"); int a=mysum(10,20); out.println("data is "+a);%><br><b> <%out.println(" sum is "+mysum(100,300);%> </b> </body>
<body> <h1>JSP TO RECEIVE DATA FROM HTML</h1> <% String s1=request.getParameter("t1";%> <% if(s1.equal("")) response.sendRedirect("error.jsp");%> <b> Data received is <%=s1%>from html</b> </body>
// 12.JSP to Database Connectity-------------------------------------------------
a) JSP PROGRAM to insert data into the data base using method:-
Html prg:-<html> <head> <title> Insert data into the database </title> </head> <body bgcolor="grey" background="a.jpg"> <form name="f1" action="r.jsp"> <div align="center"> <h2>Inserting Data into the data base</h2><hr>
<body background="a.jpg"><%@ page language="java" contentType="text/html" %><%@ page import ="java.sql.*" %><%! public int insertRec (String a,String b) {try{Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");Connection c = DriverManager.getConnection("jdbc:odbc:mydsn1");Statement st = c.createStatement();int i = st.executeUpdate("insert into e values("+a+",'"+b+"')");
Advanced JAVA Lab Manual Dept., of MCA GRIET
st.close();c.close();return i;}catch(Exception e){System.out.println("exception "+e);return 0;}} %><% String s1 = request.getParameter("t1"); String s2=request.getParameter("t2"); int i = insertRec(s1,s2);
out.println(i+"record(s) posted to the database"); %></body>
12 b) JSP PROGRAM TO SELECT DATA FROM DATABASE
HTML PRG:-
<html> <head> <title> Read data from data base </title> </head> <body bgcolor="grey" background="a.jpg">
Advanced JAVA Lab Manual Dept., of MCA GRIET
<form name="f2" action="r1.jsp"> <div align="center"> <h2>getting data from database</h2><hr>
<!--CompositeView.jsp--><%@ include file="Header.html"%><TR><TD width="20%"><%@ include file="Menu.html"%></TD><TD><%@ include file="BodyContent.html"%></TD></TR><jsp:include page="Footer.html"/>
Advanced JAVA Lab Manual Dept., of MCA GRIET
JSP Programs with Beans--------------------------------
// 14. program shows how to use beans with JSP
//This application combines seperates control layers and presentation layers of MVC.
/*Example on jsp:useBean*/jsp\EmpQuery.jsp\WEB-INF\classes\beans\EmpBean.java
java.sql.ResultSet rs=stmt.executeQuery("select empno, ename, job, sal from emp where empno="+empno);
if(rs.next()){this.ename=rs.getString(2);this.job=rs.getString(3);this.sal=rs.getDouble(4);}// if()rs.close();stmt.close();con.close();}// trycatch(Exception e){e.printStackTrace();}// catch()}// setEmpno()}// class
Advanced JAVA Lab Manual Dept., of MCA GRIET
16. Program to implement strict MVC architecture .MVC:View: Presentation logicBusiness logic: validates user I/P data with all required conditionsControl: which controls flow of execution between MVBModel: access DB
Note1: In MVC arch business logic and control layers are combined into one layerNote2: In classic MVC Model 2 arch business logic seperated from control control
Preferable way of utilizing web components in MVC & MVC 2:JSP/HTML - ViewServlets - ControlJavaBeans - Business logic & model