JSP Avanzado. Taglibs, SSL, integracion con Apache HTTPD,... PDF actualizado disponible en http://solucionjava.com/manuales_gratis.phpDescripción completa
Capitulo 5 de mi libro Técnicas avanzadas de Programacion Java
Descripción: Aprende a crear aplicaciones web con Java (JSP). Escrito en español. Para Tomcat 7 y arriba. PDF actualizado disponible en http://solucionjava.com/manuales_gratis.php
el mejor guia de mat lab
Natraz Sir JSP NotesFull description
One of the best of J2EE
Java Servlet Packages examplesFull description
JSP FAQ
CrudDescrição completa
jsp
Descripción: JSP and Beyond provides a matter-of-fact examination of web application development with Java Server Pages. The primer has been developed to provide an overview of the essential nuts and bolts of J...
JpaDescripción completa
This project Online Art Gallery has been developed on Java, JSP and MySQL and its a java programming projects for students. The main objective for developing this project was to sell art thr…Full description
This project Campus Recruitment System has been developed on Java, JSP and MySQL database. Our website Freeprojectz.com contains easy java projects including fully working java projects with source...
We have developed this project for a news site, where user can manage the news. The main objective for developing this project is to provide such a platform for a news agency to publish the …Full description
This project Student Management System has been developed on Java, JSP and MySQL. The main aim of the java software projects is to develop web application in college submission. This project Studen...
“JSP” Web application is collection of web resource program generating web page. Based on content that is generated there are two types of web resource prog.
a) Static web resource prog Generates the static web pages. b) Dynamic web resource prog. Generate the dynamic web pages. Based on the place of execution there are two types of web resource prog
a) Client side web resource prog (eg:- html, java script) These programs go to browser window for execution. b) Server side web resource prog (eg: servlet , jsp prog) These program execute by residing in the server Note: - Decide whether web resource program is client side or server side based on the place where it executes, not based on the place where it resides.
Client side web Technology: (useful to develop client side web resource program/components)
Html javaScript Ajax Jquery Angular JS And etc……..
Server side web Technologies:(Useful to develop server side web resource prog/components) Servlet (SunMicro system) Jsp (SunMicro system) SSJS(Server side java script) (from Netscape) PHP (from Apache) Asp Aps.net
(from Microsoft)
Aps.net MVC
Q:-Why SunMicro system has given JSP even they already got a server side technology called servlet? o In the initial day of servlet the Microsoft ASP programmer have not liked servlet even though it is having more features than ASP, because ASP supports tags based programming whereas to work with servlet strong java knowledge is required. To overcome above problem SunMicro system has given a tag based technology called JSP having all the features of servlet to attract asp programmers.
Limitations of servlet :o Strong java knowledge is required not suitable for non-java
programmer placing html code in servlet is quiet complex and error prone process. o In servlet programming the java code business logic (html code) and presentation logic will be mixed up. o Configuration of servlet prog in web.xml is mandatory. o Exception handling should be taken care by programmer. o The modification done in servlet program will be reflected only after recompilation of servlet program and reloading the web application. o No implicit obj support. o Learning and applying the servlet is complex. Note: - The object that is created by underlying environment…. And no code is required to access the obj is called implicit obj….. Note: - In servlet programming request, response, servletConfig etc.. are container created built-in objs but not the implicit obj because we need to write additional code to access those objs. this, super are the implicit objs/reference variables of java application. length, class are the implicit obj properties/member variables of java application.
Class c=Test.class; Here “class” (the implicit member variable) creates and returns object of java.lang.Class holding “Test” class data of the object. In java :“class” is a oops terminology. “class” is a keyword.
“java.lang.Class” is a pre-defined class. “class” is a built in property.
17-jul-15
Feature of jsp: Allows tags based programming.
Strong java knower is not required, so it is suitable for both java and
non-java programmers. Gives 9
implicit objects.
Allows to separate presentation logic (html) from business logic
(java code). The modification done in jsp will be reflected without any
recompilation and reloading web application.
Configuration of jsp in web.xml file is optional. Use built in tag and also allows working with third party tag or custom
tag. Easy to learn and use. Exception handling is optional.
Allow to work with all the feature of Servlet.
Every “.jsp” file is called as jsp
prog/jsp comp/jsp page/jsp file.
Jsp page runs based on page compilation
principle i.e. every jsp page
will be converted into an equivalent servlet prog. To execute jsp page jsp container is required. This Container supplies to jsp
page compiler to translate jsp page into equivalent servlet prog and this servlet prog executes with the support of jsp container + servlet container. Every server supplies 1 built-in jsp page compiler as part of its jsp container.
What is difference between servlet and jsp?
Servlet
Jsp
Strong java knowledge is required so suitable
Strong java knowledge is not required so
for java programmers.
suitable for both java and non-java
programmers. Does not supports tag based programming.
Supports tag based programming.
Modification will reflect only after
Will reflect without recompilation and
recompletion and reloading.
reloading.
Does not give implicit objects.
Gives implicit objects.(9)
Exception handling is mandatory.
Exception handling is optional.
Makes programmer to mix-up java business
Allows to separate the logic.
logic java code and presentation logic(html code) Configuration of prog in web.xml is mandatory. It is optional. Note: - in the initial days programmers have used jsp as complete alternate to servlet. But according to MVC architecture it is recommended to use both servlets and jsp together in application development. Jsp page compiler internally uses servlet API, jsp API while generating jsp class. Jsp API is the extension of servlet API. Servlet API will be used in the development of servlet container. Jsp container internally uses ServletContainer so we can say jsp container is
developed based on both jsp API and servlet API. Servlet api:- javax.servlet, javax.servlet.http, javax.servlet.annotation, javax.servlet.descriptor. Jsp api: - javax.servlet.jsp, javax.servlet.jsp.el, javax.servlet.jsp.tagext
In Tomcat sever: Servlet container name: catalinajar file : catalina.jar Jsp container name: jaspser jar file: jasper.jar Servlet api jar file: servlet-api.jar Jsp api jar file :jsp-api.jar
Note: All these entire jar files are available in \lib folder.
Template text = ordinary text + html Jsp page generate dynamic web page the fixed content of dynamic web page
will be generated through template text and the dynamic values will be generated through java code of scriptlet.
Place jspApp folder in \web apps for deployment. Request url: http://localhost:3030/jspApp/Abc.jsp>
20-Jul-15 Q: - How many object can be there in jsp?
o Two types of object in jsp. 1. Explicit object It is created by programmer manually. Eg: <% java.util.Date d=new java.util.Date(); %> 2. Implicit object Created in JES automatically. Jsp gives 9 implicit objects. 1. out 2. request 3. response 4. exception 5. application (ServletContext object.) 6. config 7. session 8. page 9. pageContext What is the difference between html and jsp?
Html
Jsp
It is client side web technology.
It is server side web technology.
These programs generate static web page.
These programs generate dynamic web pages.
To execute html, interpreter is needed.
To execute jsp code, we need jsp container/jsp engine.
Does not allow to place java code.
Allows to place java code.
Html code is not a strictly typed code.
Jsp code is strictly typed code.
Tags and attribute are not case sensitive.
Tag and attributes are case sensitive.
Servlet prog/component life cycle methods are : 1. init(ServletConfig) 2. service(ServletRequest, ServletResponse) 3. destroy() o init(), service(HttpServletRequest ,HttpServletResponse), doxxx(-) are not life cycle methods. They are convenience methods given to programmer. o Every jsp prog/page internally gets an jsp equivalent servlet prog/component for execution , so there will not be any separate life cycle methods for jsp so the servlet life cycle methods itself acts jsp life cycle methods. But different convenience methods are given for jsp. They are: jspinit()/_jspInit() will be called from init(-) life cycle method . _jspService(-,-) will be called from service(-,-) life cycle method. jspDestroy()/_jspDestroy() will be called from destroy() life cycle method. In tomcat server Jsp Equivalent Servlet(JES) class source file and class file for ABC.jsp is -
o ABC_jsp.java , ABC_jsp.class and the location is
\localhost\jspApp\org\apaceh\jsp
Here jspApp is projce name
org\apache\jsp is package name
Every JES class is a. HttpServlet class based servlet prog b. Contains only _jspService(-,-), _jspInit(), _jspDestroy() methods and does not contains jspInit(), jspDestroy() methods.
c. Extends from jsp Container supplied class which extends from HttpServlet. This supplied calls jspInit()/_jspInit(), _jspService(-,-) , jspDestroy()/_jspDestroy() methods from servlet life cycle methods in tomcat server this class name is “HttpJspBase”.
d. Template text code, scriptlet code placed in jsp automatically goes to _jspService(_,_) methods to create and use implicit objects and etc…..
Q: - When JES class obj is created by container? o
Calls init(ServletConfig obj) on JES class object. Since not found, init(ServletConfig) of super class (HttpJspBase) executeds and that methods internally calls jspInit(), _jspInit() methods.
When request processing event occurs. Calls service(ServletRequest ,ServletResponse) on JES class obj.
Since not found same service(-,-) of GenericServlet executes This calls service(HttpServletRequest, HttpServletResponse) of HttpJspBase class. Service(-,-) of HttpJspBase class internally calls _jspService(-,-) methods. When Destruct event is raised: Calls destroy () on JES class obj. Since not found destroy () of super class HttpJspBase executes. This destroy () internally calls jspDestroy ()/_jspDestroy () method. “_” (Underscore) symbol in methods name indicate that they are generated
methods in JES class i.e. we cannot place same methods in JES class through jsp page/program. jspInit()/_jspInit(),_jspService(-,-),jspDestroy()/_jspDestroy() methods are
convince methods given by jsp api i.e. these are not life cycle methods of jsp because they are not called by a container directly and they are called through servlet lifecycle method internally. When life cycle life event is occurred is called life cycle method. The method that
is called through life cycle method is not called life cycle method.
21-Jul-15 In weblogic server JES class for ABC.jsp will be generated as _ _ABC.class and also destroyed the .java file or JES class once the .class file is created.
Two phases of jsp execution A. Translation phase In this phase the jsp page/program will be converted into an equivalent servlet
source file and compiled file.
B. Request processing phase/ Execution phase. In this phase JES class will instantiated and _jspService(-,-) method executes to
process the request and to send the response to browser.
The request given to jsp program/page directly participates in “request
processing phase” if the source code of jsp page/program is not modified when compared to previous request and .class file of JES class is available otherwise request given to jsp page participates in both translation phase and request processing phase.
Jsp container internally remembers the source code of jsp program/page for
every request until next request comes to that jsp page/program and uses the comparison tools like Araxis or WDiff to compare both source codes.
Note: if the .java file JES class is deleted then the request given to jsp file will not participate in translation phase.
Note:- the modification done in the source code of JES class does not reflect to the output. WEB-INF and its sub folders are called private area of web application i.e. only underlying serve/container can use the content of that web application. If any web resource is placed inside WEB-INF then configuration of web.xml is mandatory otherwise optional. In some special cases we prefer to place jsp program or page in side WEB-INF for the following benefits:i.
To hind technology of the web site from the visitors.
ii.
To avoid ugly messages displayed by jsp when we give direct request to jsp when it is having logic to read and display request attribute value given by servlet.
To overcome above problems place jsp program inside WEB-INF folder,
configure in web.xml file and Access jsp prog either through servlet/servlet filter. o Example
A
/WEB-INF/pages/ABC.jsp
A/test
Request url
o http://localhost:3030/jspApp1/ABC.jsp (wrong) o http://localhost:3030/jspApp1/test (correct)
22-jul-15 When jsp page outside WEB-INF, configuration file is optional When jsp pages are placed inside WEB-INF folder its configuration in web.xml
file is mandatory.
Jsp Tags/Elements 1. SCRIPTING TAGS:a. Scriptlet (<% …….. %>) b. Declaration (<%! ........... %>) c. Expression (<%= …… %>) Note:- These tags are given to place java, in jsp. The java code placed in jsp is called script code.
2.
JSP COMMENTS (<%-- ……….. --%>)
3. DIRECTIVE TAGS/ELEMENTS a. page directive (<%@ page attributes %>) b. include directive (<%@ include attributes %>) c. taglib directive (<%@taglib attributes %> )
Code placed in scriptlet goes to _jspService () method of JES class. Variables declared in scriptlet becomes local variables to _jspService (-,-) method of jsp.
In jsp
in JES class
<% int a=20; %>
{
public class ABC_jsp extends ….. public void _jspService(-,-)
{
int a=20;}}
We can use scriptlet for placing request processing logic, because its code
goes to _jspService(-,-) method of JES class. in jsp <% int a=20; int b=30; int c=a+b;
In JES class
public class ABC_jsp extends …. {
public void _jspService(-,-) {
int a=20;
out.println(“sum=”+c); %>
int b=30;
int c=a+b;
out.println(“sum=”+c); }}
Using xml syntax: Welcome to jsp > Out.println(“system date “+ new java.util.Date());
While working with less than symbol “<” in the xml syntax of scriptlet we need to be very careful because if we place less than symbol “<” as the body of the tag, it will be treated as xml meaning sub-tag, and it will not treated as java conditional operator.
int b=30;
if(a
as xml sub tag.
out.println(a +” is greater than”+ b);
else
out.println(b +” is greater than”+ a);
]]>
SOLUTION-1:
Use standard syntax: <% ……..//same as above code %>
SOLUTION-2:
Use
support
the body as ordinary text (java code), so “<” will be treated as the conditional operator. ………. ……….
]]>
But greater than symbol does not have such problem:
int a=20;
int b=30;
if(a>b).
out.println(a +” is less than”+ b);
else
out.println(b +” is less than”+ a);
NOTE: - less than symbol is not there with standard syntax and greater than symbol not problem in any syntax.
goes this
Implicit object are local variable to _jspService(-,-) method in JES class, and the code placed in scriptlet also goes to _jspService(-,-) of JES class so we can use implicit objs in
java does not support nested method support so we cannot place method definition in scriptlet, because it becomes nested method definition of _jspService(-,-) method. Jsp code
In JES class
<%
public void _jspService(-,-) throws
public int sum(int x,int y)
Se,IOE
{
{
return x+y;
public int sum(int x,int y)
}
return x+y;
%>// it will gives error because it will become nested method in _jspService(-,-) method.
} }
Note: - we cannot place interface definition in a method definition that mean we cannot place interface definition in scriptlet.
But we can place class definition in the above context.
java support nested class definition, nested interface definition.
We can place interface definition inside the class and class definition inside the interface.
1. (b) Declaration Tag: The code placed in Declaration tag goes outside to _jspService method of JES class. So we can use this tag for global variables declaration, method definition,
class/interface definition (nested), jspInit(), jspDestroy() method definitions and etc…… Standard syntax:<%! ……. ……. %>
Xml syntax:-
……. ……. Variable declared in Declaration tag will come as global variable of JES class. In JES
In JES class
<%! int a=10;
public class ABC_jsp extends ……
%>
{
int a=10;
} Q: - How can we differentiate declaration tag variable from scriptlet tag variable being from scriptlet when both have got same name.
23-Jul-15 Ans:- Use either implicit object “page” or “this” as shown below:<% int a=30; %> <%! int a=20; out.println(“ local a value “+this.a); ABC_jsp o1=(ABC_jsp)page; //out.println(“ Local a value “+this.a); out.println(“ global a value “+o1.a); // it is not recommended because it demands typecasting //with JES class that changes server to server. %>
We can place user defined method in declaration tag. JSP program <%! public int findBig(int x,int y) { if (x <% out.println(“Big value” + findBig(10,20)); %>
In JES class publc class ABC_jsp { public void _jspService(-,-) { out.println(“Big value” + findBig(10,20)); } public int findBig(int x,int y) { if (x
<% out.println(“Big value” + findBig(10,20));%>
Implicit object of jsp cannot be used in declaration tag because implicit object are the local variable of _jspService(-,-) method and declaration tag code not goes to _jspService(-,-) in JES class. By default JES class gives _jspInit (), _jspDestroy () and _jspService () method, but we can use declaration tag support to place jspInit() and jspDestroy() method as shown below. <%! public void jspInit() { System.out.println("jspInit()"); } <%! public void jspDestroy() { System.out.println("jspDestroy()") } %> <% System.out.println("_jspDestroy(-,-)%> jspInit() useful to place the initialization logic of program like crating jdbc connection. jspDestroy() useful to place the un-initialization logic of programmer like closing jdbc connection. _jspServce(-,-) useful to place request processing logic. _jspInit() contains JES class related predefined initialization logic. _jspDestroy() contains JES class related predefined un-initialization. Q: - can we place servlet life cycle methods directly in jsp program using declaration tags?
Ans) No, Not possible because all these methods are declared as final methods in the super class of JES class that is HttpjspBase class in Tomcat server and final methods of super class cannot be overridden in sub-class. Q :- what is the advantage of enabling load-on-startup on jsp page?
Ans: - The container performs the following operations either during server startup or during deployment of web application.
1) Complete translation phase on jsp program. 2) Create JES class objects using 0-params constructor. 3) jspInit() methods executes. So the first request given to jsp directly participates in request processing.
a/ABC.jsp
1
a/abc
Note: - we need to request to jsp by using its url pattern. Note: - jsp configuration in web.xml benefits will come only when jsp is requested through URL pattern. Q: - can we placed _jspInit (), _jspDestoy (), _jspService () method in declaration tags of jsp? Ans:- not Possible, because they become duplicate method of JES class and java does not support duplicates. We can place class, method, and interface definition in declaration tag, they will become nested class or nested interface of JES. Jsp:
JES class
{
{
<%!class Test }
%>
<%! interface xyz{ }%>
public class ABC_jsp extends HttpJspBase class Test{}
interface xyz{}
}
<%! int counter=0;%> <% counter++;
out.println(“No of request:”+counter); %>
In one jsp program we can place multiple tags in any order having only xml syntax and mix of both. In one declaration tag we can declare multiple global variables and we can place multiple method definitions.
24-Jul-15 1. (c) expression: Anything that returns values after the evaluation is called expression. Arithmetic, logical, methods call comes under expression. Expression tag evaluates the given expression and displays the generated results on browser as the webpage content. Standard syntax:-
<%= %>
Xml syntax:-
…………
We can use expression tag to display variable values. <% int a=20; out.println(“ value=”+a+””); %> Bad practice because we are mixing up html code and java code… <%int a=10; %> value =<%a=%> Here <%a=%> will display variable “a” value.
Jsp program <% int a=10;%>
value : <%=a%> ---display
JES class public class ABC_jsp extends – { public void _JspService(-,-)
The code placed in expression tag goes to _jspService(-,-) of JES class and becomes the argument value of out.print() method. If we use expression tag effectively there is no need of working with out.println() method jsp. All implicit object of jsp are visible in Expression tags. in jsp class:
Browser
%>
In JEs class:
out.println(“Browser”);
Name:<%=request.getHeader("user-
out.println(request.getHeader(“user-
agent");
agent”));
We can use expression tag to call both pre-defined and user-defined methods but those methods must return value. <%! public int sum(int x,int y) {
return x+y; } %>
<% int x=10,y=20;%> Sum of: <%=x%> <%=y%>is <%=sum(x, y)%> <% string s=”hello how are you”;%>
Length of <%=s> is <%=s.length()%>
Date and Time: <%=new java.util.Date()%>
Date and Time new java.util.Date()
Even cannot solve the “<” symbol that raise with xml syntax of expression tag. Date and Time //here is “<” problem which can not be solved by using CDATA One expression tag can evaluate only one expression at a time. If we want to evaluate more than one expression we can use String
concatenation support. <%=a*a a*a*a%> //wrong <%=a*a,a*a*a%> //wong <%=a*a+” “+ a*a*a %>// correct Note:- We cannot place class definition, method definition, and interface definition in expression tags. Procedure to jsp page based web application in Eclipse IDE?
Step-1) configure tomcat 8 with eclipse ide. Step-2) windowserverrun time environmentaddapache tomcat 8nextlocation of tomcat serverfinishok. Step-3) create dynamic web project. filenew dynamic web project step-4) add first jsp to web content folder of the project. <%! public String generateWishMessage(String uname) {
//get system data java.util.Calendar c1=java.util.Calendar.getInstance();
//get current hour of the day(24 hrs formate)
int h=c1.get(java.util.Calendar.HOUR_OF_DAY); //generate wish message
if(h<=12)
return “Good morning”+uname; else if(h<=16)
return “good after noon: “+uname;
else if( h<=20) return “Good evening”+uname;
else
return “Good night: uname; }
%>//end of declaration tag
Welcome to Jsp
Date and time is : <%=new java.util.Date()%> //end of expression tag
<% String name=request.getParameter(“uame”);reads the request parameter value %> Wish messge:<%=generateWishMessage(name)%> Request Url- http://localhost:3030/jspApp2/ Step-4) run the application.
27-Jul-15 (thr to fri) Detailed Life cycle of jsp
Comment in jsp:-
Compiler or interpreter recognizes the comments and places white space character in the place of commented code due to this commented code does not participate in execution.
Jsp supports three type of comments
1. Jsp comments (<%-- --%> )//hidden comments 2. Html comment() //output comments 3. java comments(// or /* */) //scripting comments.
Jsp comments are useful to comment jsp code/tags of jsp program.
These tags will be recognized by jsp page compiler. <%-- <%=a %> -- %>
Html comments are useful to comment html code/ tags of jsp prog.
These tags will be recognized by html interpreter.
java comments are useful to comment java code of jsp program. Theses comment is recognized by java compiler (javac). <% int a=110; //a=a*a; %> Comment Visibility .jsp In JES In JES source compiled
Code that goes to browser No
Jsp comment Yes No No <%-- --%> Html comment Yes Yes Yes Yes java comments Yes no No No jsp comments not visible in any phase of jsp execution so they are called as “hidden comments”.
Html comments go to the output code that goes to browser so they are called “output comments”.
Technically speaking in jsp implicit object are not there but implicit reference
variable are there pointing to various object of web application.
“config” is the implicit reference variable pointing to ServletConfig object.
“application” is reference variable pointing to ServletContext object.
Since these implicit reference variable are local variable of _jspService(,-) method. We cannot use them in declaration tag code. But we can create other reference variable accessing same object in declaration tag by using servlet API support.
Example :o
We can access ServletContext, ServletConfig obj in jspInit() or other methods declaration tags as shown below.
30-Jul-15 page scope means item is specific to current jsp page/program. request scope means item is visible through request and it is specific to each request. Session scope means item is specific to each browser but it is visible in all web resources programs. application scope means item is visible in all web resource programs of web applicant irrespective of any condition. Implicit object Reference object Scope Out javax.servlet.jsp.JspWriter (AC) Page pageContext javax.servlet.jsp.tagext.PageContext(Ac) Page Config javax.serlvet.servletConfig (I) Page application javax.serlvet.ServletContext (I) Application Request javax.servlet.HttpServletReqeuest (I) Request Response javax.servlet.HttpServletResponse (I) Response Exception java.lang.Throwable (C) Page session javax.serlvet.HttpSession (i) Session page java.lang.Object ( C) Page
The above implicit objects are not objects technically, they are reference variables pointing to various implementations class object or sub-class object that are given above. To know the class name of any implicit object, use getClass() method as shown below. Response object class name<%=respose.getClass()%> Request object classname<%=request.getclass()%>
JspWriter object of class name<%=out.getClass()%> “out” is the object of class given by jsp container extending from JspWriter (AC) class, that class name in Tomcat is org.apache.jasper.runtime.JspWriterImpl, this class is actually extends from JspWriter.