SIDE-BANNERCENTER-BANNERSIDE-BANNER * Oh God! Let there be PEACE. Make them calm, gentle, humble and stable. Make them realize their mistakes. Make them to confess, seek and pray for forgiveness. Let there be forgiveness for true hearts. Show them the right path on which they can walk. Let there be justice, satisfaction and happiness. Let them know that you are the justice and truth. Let them know that the innocent is never punished. Give them the strength, courage and wisdom to quit bad and to achieve good purpose. Let there be leaders who are followed by goodness. Make them competitive to achieve good. Remove their greed, wickedness and bad ambitions. Let them know that your love is infinite. Speak to them in simple ways so they understand. May your heart hear their pure hearts. * Never say die.Live and let live.* Accept Good if not, it Perishes.* What you Sow is what you Reap.* United we Stand divided we Fall.* Where there is a Will there is a Way.* Love is the strongest Power on earth.* When going gets Tough the Tough gets going.* For every problem created there is a perfect Solution.* When your hand starts paining you don't Cut it, Cure it.* A good purpose of life is the persistence to be constructive.* The arch of justice is wide, but it bends towards freedom and justice.* Lion king says he wants all the Power but none of the Responsibilities.* Life is a puzzle which can be solved by Hard work, Character and Discipline.* Money is like Manure, Spread it and it does good.* Pile it up in one place and it Stinks.* When a man wants to be a King he should exactly know the responsibilities of a King.* The only thing necessary for evil to triumph is for good men to do nothing - Edmund Burke.* Face is the reflection of mind.* A purpose of life is a life of purpose.* Beauty lies in the eyes of the beholder.* Necessity is the mother of all inventions. Real friends are those who help us in troubles.* Freedom and Power are lost if it’s miss utilized. Repeating mistakes will lead to sin and blunders.* Quantity is appreciated only when it has Quality.* Everyday is a new day, which brings hope with it.* Ego of superiority is the destruction of individuality.* We cannot learn to swim without going into the water.* Everything happens for good and thus leads to destiny.* Every problem has a perfect solution, we need to find them.* A good purpose of life is the persistence for constructiveness.* It’s hard to create good things where as it’s easy to break them.* Ideas are appreciated and respected only when we express them.* Mistakes do happen by humans, they are forgiven when we pray.* Freedom means giving others the right to achieve good purposes.* We have to put our efforts and leave the rest for destiny to decide.* All big things start with a first step.* First step is sometimes difficult.* Prayers come true when the purpose is good, thus pray for everyone.* Dreams come true when we have faith and pray for good things in life.* We got to have strength, courage and wisdom to achieve good things in life.* Every relationship has a meaning; we have to give them the proper meaning.* The only thing necessary for the triumph of evil is for good men to do nothing.* If wealth is lost, nothing is lost. If health is lost, something is lost. But, if character is lost, everything is lost.* “Stand up, be bold, be strong. Take the whole responsibility on your own shoulders, and know that you are the creator of your own destiny.” - Swami Vivekananda.
HOME-PAGEREALIZATIONQUOTESPUZZLESPRAYERSPERCEPTIONSMUSIC-DOWNLOADSTORIESJOKES
BOOKSBITTER-TRUTHANCIENT-SCRIPTURESBEAUTIFUL-LIFETHOUGHTSFRIENDSHIPPRAYERS-TO-WORSHIPWinning-Publications

Technology ADV-JAVA Manoj Kumar

QUANTITY is appreciated only when it has QUALITY. Recitation is the mother of Memory. Necessity is the mother of Invention. Knowledge grows when distributed. Enrichment for Information Technology. Persistence to be constructive is the key to success.

Tuesday, February 26, 2008

Portal Builder Concepts: Role, Category, Page, Group



Portal Builder Concepts: Role, Category, Page, Group.

*[How to Build a Personalized, Secure Web Portal Using]: eDirectory, iChain, and Corporate Yahoo! Enterprise Portal

*[OracleAS Portal: Getting Started.]

*What is a PortalBuilder?
PortalBuilder is a one stop access to personalized, selected information to large number of end users, from enterprise systems, databases and internet. Content from diverse sources is presented to authenticated users.

Page: A page can contain multiple named panes. These panes contain categories composed of content items. These panes can be maximized or minimized.

Categories: There are three type of categories. Parsed HTML, Parsed XML and Database categories which can be created.

User Groups: User Groups consists of users.

Roles: All users are assigned to roles. Role refers to group of users. Users are able to view page contents based on the rules defined by the Roles. (Roles)

PortalBuilder requires a Database, an LDAP Server and a web-server.
LDAP (Lightweight Directory Access Protocol) stores profile of each user. Profile consists of: registration info, category subscription info, roles info, object instances, etc. (OpenLdap)

User Authentication: Supports three types, Cookie authentication, web server authentication and external authentication.

* * * * * * * * * * * * *
*[Read:Amazing-Constructive-Vibrations.] *[Significance-of-Nava-ratna(Nava-Graha).]
*[Oh-God!-Please-Speak-to-me.]
* [Read:Good-Health-Tips:Nature-Cure/Therapy.] *[The-Piercing-of-the-ears(Karnavedha).]

Read: Peace

Home Download Music Prayers Life Is Beautiful Add to Google
Life is Beautiful.
*Creating successful constructive personality. *Why God Gave Us Friends? *Way to Paradise. *Creating the Beautiful World. *Doing the job of goodness. *Life is Meaningful. *The A to Z for Goodness. *Life is full of Tests. *History Proves That. *Love in different forms. *True to the heart.

Thursday, February 14, 2008

Struts



* How STRUTS Works? (Steps Involved in the process.) (Tutor) (API Doc)
* Client request is handled by ActionServlet. (Controller) (Questions)
* Requested page (Ex: Login.jsp) is produced to client. (Intro to Struts: Ex)
* Login.jsp page contains html:form tag, to collect the client entered data. (Tag Lib Doc)
* struts-config.xml file has "action-mappings" element to specify action bean.
* struts-config.xml file has "form-beans" element to specify the form bean.
* struts-config.xml file has "plug-in" element to specify the validator bean (Ex: validator-rules.xml and validator.xml).
* The form data entered by client is populated in ActionForm.
* Server container invokes "Action" bean's execute method to return "ActionForward" object.
* Action beans "execute()" method initializes "HttpSession" object using "HttpRequest" object. Then, retrieves values from the FORM bean by creating the object. Creates "Serializable" object after retrieving the data from database. Assigns it to "setAttribute" method of session object for later retrieval.

* Steps involved in data retrieval from database, in STRUTS.
(1) Use "InitialContext" to create "Context" Ex: Context ctx = new InitialContext();
(2) Use "Context" to create DataSource Ex: DataSource ds = (DataSource) ctx.lookup(jdbc/oracleds");
(3) Use "DataSource" to create "Connection" Ex: Connection con = ds.getConnection();
(4) Use "Connection" to create "Statement" Ex: Statement stmt = con.createStatement();
(5) Use "Statement" to create "ResultSet" Ex: ResultSet rs = stmt.executeQuery(String);
(6) Use "ResultSet" to create "String" Ex: String str = rs.getString(No.#);
(7) Use "String" to create "User Object" Ex: UserObject user = user.setUserId(str);

(Note: Changes from step "4" onwards.)
Steps involved in creating "CallableStatement insted of "Statement". (for Stored Procedures)
(4) Use "Connection" to create "CallableStatement" (Ex:)
Ex: CallableStatement cstmt = con.prepareCall("{call myProc}"); // String
cstmt.registerOutParameter(1, OracleTypes.CURSOR); // this # is later passed in getObject parameter.
(5) Use "CallableStatement" to create "ResultSet"
Ex: ResultSet rs = cstmt.getObject(No.#); // # of
cstmt.registerOutParameter
(6) Use "ResultSet" to create "String" Ex: String str = rs.getString(No.#);
(7) Use "String" to create "Array List Object" Ex: ArrayList alist = alist.add(Object);

* Theory: There are two "configuration files" in struts applications.
(1) Web application deployment descriptor (web.xml) (Directory Structure)
(2) Struts configuration file (struts-config.xml) (Apache Guide)

* Web.xml: This is placed in WEB-INF directory. This is used by web container on startup to configure the runtime environment. (Example) (Apache)
Element "servlet-class" is used to specify ActionServlet, which acts as a controller.
Element "url-pattern" *.do is used to specify that url mapping with *.do will be processed by ActionServlet.
Element "init-param" is used to specify the struts-config.xml used to config runtime environment. “Initialization parameters” Ex: "init-value" "param-value" *.xml.
Element "load-on-startup" No.# directs the web container to initiate an instance of init() method of servlet. The integer value specifies the order in which the servlet is called. A negative value indicates container to load in any order.
Element "welcome-file-list" specifies the starting page for web application.
Element "tag-lib" specifies JSP tag libraries to use in JSP files, which helps the container to find descriptor tld files. Ex: struts-html.tld, struts-bean.tld, struts-logic.tld, etc. (Tag Lib Doc)

* Struts-config.xml: This is used by struts framework to configure the application. This is a default name, and can be changed in web.xml file. Its normally placed in WEB-INF directory. We can also use more than one struts-config.xml files. Ex: "param-name" struts-config.xml, struts-config2.xml etc.
Element "data-source" is used to setup data source for struts framework. It contains multiple (set-property property="_" value="_") elements. Property attribute is name of setter method. Value attribute is value passed to setter method.
Element "form-beans" is used to configure ActionForm to be used in Action class. Within this element multiple elements of "form-bean" can be configured.
Element "global-exception" is used to configure exception handling.
Element "global-forwards" is used to forward an action to a view. It contains multiple "forward" elements (this can also be in action element). If the forward name is same in both places then action level takes precedence.
Element "action-mapping" is used to map Action class to request path. It may contain multiple action elements. (ActionMapping)
Element "message-resources" is used to specify the "*.properties" file, which contains text messages. (MessageResources)

* What is Jakarta Struts Framework?
A: Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for the development of web based applications. Jakarta Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java.

* What is Struts?
A: The core of the Struts framework is a flexible control layer based on standard technologies like Java Servlets, JavaBeans, ResourceBundles, and XML, as well as various Jakarta Common packages.
Struts encourages application architectures based on the Model 2 approach, a variation of the classic Model-View-Controller (MVC) design paradigm.
Struts provides its own CONTROLLER component and integrates with other technologies to provide the Model and the View.
For the MODEL, Struts can interact with standard data access technologies, like JavaBeans, JDBC and EJB, as well as most any third-party packages, like Hibernate, iBATIS, or Object Relational Bridge.
For the VIEW, Struts works well with JavaServer Pages (JSP), including JSTL and JSF, as well as Velocity Templates, XSLT, and other presentation systems. The Struts framework provides the invisible underpinnings every professional web application needs to survive. Struts helps you create an extensible development environment for your application, based on published standards and proven design patterns.

(Hibernate-Intro) - (Hibernate-Xml-Mapping) - (Hibernate-Questions) - (Struts-Plugin) - (Example)

* What is ActionServlet?
A: The class (org.apache.struts.action.ActionServlet), in the Jakarta Struts Framework plays the role of a controller. All the client requests to the server are handled by this controller.

* How you will make available any Message Resources Definitions file to the Struts Framework Environment?
A: The Message Resources Definitions file are simple "*.properties" files and these files contains the messages that can be used in the struts project. Message Resources Definitions files can be added to the struts-config.xml file through tag "message-resources".

* What is Action Class?
A: The Action Class is part of the MODEL and is a wrapper around the business logic. To use the Action, we need to Subclass and overwrite the execute() method. All the database/business processing are done in the Action Class.
execute method returns: ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) (Example) (Intro to Struts)
{
String pwd = form.getPassword(); /* Retrive value from ActionForm */
/* validate this pwd in database and assign "result" as "success" or "failed" */
return mapping.findForward(String result); /*
ActionForward object */
}
The return type of the execute method is ActionForward which is used by the Struts Framework (struts-config.xml) to forward the request to the VIEW file.

* What is ActionForm?
A: An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from the
client side VIEW form. (Example)

* What is Struts Validator Framework? (Ex: Intro to Struts)
A: Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used to validate the form data on the client browser. Server side validation of form can be accomplished by sub classing the FormBean with DynaValidatorForm class. (Dyna Ex.) (Ex:2) (Code:1) (Code:2)
The Validator framework was developed as a third-party add-on to Struts. Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings.

* Give the Details of XML files used in Validator Framework? (Intro) (Guide)
A: The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. The validator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml. to define the form specific validations. The validation.xml defines the validations applied to a form bean. Validation.xml defines mapping for client entered string data. Validator-rules.xml defines mapping for the ClassName used to process the data.

* How you will enable front-end validation based on the xml in validation.xml?
A: Specify parameter values of VIEWform in validation.xml and add the below code in the VIEW file.
"html:javascript formname='VIEWform' dynamicjavascript='true' staticjavascript='true' "
This generates the client side java script as defined in the validation.xml. [Article]

* How to get data from the velocity page in a action class? (Velocity) (Overview)
A: We can get the values in the action classes by using data.getParameter(\"variable name defined in the velocity page\");
Velocity separates Java code from the web pages. It's an alternative to JSP. It permits web page designers to reference methods defined in Java code. (What is Velocity?)


Read: Peace
Read some More good ones Here: Friendship

Here is something nice to motivate:
*[Let’s-make-it-happen.] *[Someone-Somewhere.] *[Logic-of-Good-and-Bad.] *[Only-One-I-have-got.]

*[Faith-in-Patience.] *[Ingredients-of-Super-Power.] *[Successful-Life.] *[Amazing-Constructive-Vibrations.]

* * * * * * * * * * * * *

"WE" has More Power than "I". Please leave a comment if you encounter any problems or have any suggestions.

Home Download Music Prayers Life Is Beautiful Add to Google
Life is Beautiful.
*Creating-successful-constructive-personality. *Why-God-Gave-Us-Friends? *Way-to-Paradise. *Creating-the-Beautiful-World. *Doing-the-job-of-goodness. *Life-is-Meaningful. *The-A-to-Z-for-Goodness. *Life-is-full-of-Tests. *History-Proves-That. *Love-in-different-forms. *True-to-the-heart.

Servlet



* Explain the life cycle methods of a Servlet. (Sun Tutor)
A: The javax.servlet.Servlet interface defines the three methods known as life-cycle methods.
public void init(ServletConfig config) throws ServletException
public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy()
First the servlet is constructed, then initialized with the init() method. Any request from client are handled initially by the service() method before delegating to the doXxx() methods in the case of HttpServlet. The servlet is removed from service, destroyed with the destroy() method, then garbage collected and finalized.

* What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?
A: The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface accepts parameter path to the resource included or forwarded, which can be relative to the request of the calling servlet. In order to create it we need to give the relative path of the resource.
The getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot accept "relative paths". All path must sart with a "/" and are interpreted as "relative to the current context root". In order to create it we need to give the absolute path of the resource.

* What is the difference between Interfaces ServletContext and ServletConfig?
A:
ServletContext: Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized. The ServletContext interface provides information to servlets regarding the environment in which they are running. It also provides standard way for servlets to write events to a log file.
ServletConfig: The object created after a servlet is instantiated and its default constructor is read. It is created to pass initialization information to the servlet.
The servlet engine implements the ServletConfig interface in order to pass configuration information to a servlet. The server passes an object that implements the ServletConfig interface to the servlet's init() method.

* Explain the directory structure of a web application.
A: The directory structure of a web application consists of two parts.
A private directory called WEB-INF consists of "web.xml" "classes directory" and "lib directory".
A public resource directory which contains public resource folder.

* What are the common mechanisms used for session tracking? (Cookies) (Session)
A: Cookies SSL sessions and URL- rewriting. (Geek Interview)

* Explain ServletContext.
A: ServletContext interface is a window for a servlet to view it's environment. A servlet can use this interface to get information such as initialization parameters for the web application or servlet container's version. Every web application has one-and-only-one ServletContext and is accessible to all active resource of that application. The ServletContext object is contained within the ServletConfig object: ServletConfig.getServletContext() OR Servlet.getServletConfig().
init() method provides a config object:
public void init(ServletConfig config) throws ServletException {
super.init(config);
paramName = config.getInitParameter("paramName"); }

* What is pre-initialization of a servlet? (Ex: Web.xml)
A: A container does not initialize the servlets as soon as it starts up, it initializes a servlet when it receives a
request for the first time. This is called lazy loading. The servlet specification defines the element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in, is called preloading or preinitializing a servlet. Specify "1" in between the tag "load-on-startup".

* What is the difference between doGet() and doPost()? (Servlets)
Client HTML FORM Ex: <.FORM ACTION="/servlet/RedirectServlet" METHOD="POST".>
<.SELECT NAME="url" ONCHANGE="goFunction()" ONBLUR="return options[0].selected=true".>
<.OPTION VALUE="/developer/products/j2me/".> Consumer <./OPTION.> ... many more Options ...
When you select a destination and click the Go button, the menu form invokes the servlet by through the Action line. NAME attributes describes the information that is entered into the values. NAME and its values must be meaningful so if the data is written to email messages, log files, or databases the information makes sense to the user viewing them (writing servlet code). When a client calls a servlet by typing the URL in the browser, submitting a form, or clicking a button on a menu, the servlet's service method checks the HTTP request type, such as POST or GET. This in turn calls doGet, doPOST, doPUT, or doDelete as needed. A servlet must override doGet or doPost, depending on whether data is sent by POST or GET in the HTML form.
public void init(ServletConfig config) throws ServletException { super.init(config);
-------String paramName = config.getInitParameter("paramName"); }
public void doPost(HttpServletRequest request, HttpServletResponse response)
{ doGet(req, res) {
-------response.sendRedirect(request.getParameter(paramName));
HttpServletRequest has methods such as getParameter that takes the value of a NAME attribute as a string Object.
sendRedirect, sends a temporary redirect response to the client using the specified redirect location URL.
The doGet method calls the getParameter method through the request object, passing in the paramName String Object and its value as a string pair, in this case url(NAME) and the actual URL(
/developer/products/j2me/). A special sendRedirect method then passes the string to the browser and redirects the user to the desired destination. The doPost or doGet methods instruct the server about what it must do, whether printing information back to the client's browser, writing to a database, or simply redirecting the client to a requested URL. Within these methods you will use Java programming syntax to give specific instructions for the servlet to interact between the client and the server.
A: A doGet() method is limited with 2k of data to be sent, and doPost() method doesn't have this limitation. A request string for doGet() looks like the following: http://www.allapplabs.com/svt1?p1=v1&p2=v2&...&pN=vN doPost() method call doesn't need a long text tail after a servlet name in a request. All parameters are stored in a request itself, not in a request string, and it's impossible to guess the data transmitted to a servlet only looking at a request string. (HttpServlet)
HTML FORM GET request is a request to get a resource from the server. Choosing GET as the "method" will append all of the data to the URL and it will show up in the URL bar of your browser. The amount of information you can send back using a GET is restricted as URLs can only be 1024 characters. A POST request is a request to post (to send) form data to a resource on the server. A POST on the other hand will (typically) send the information through a socket back to the webserver and it won't show up in the URL bar. You can send much more information to the server this way - and it's not restricted to textual data either. It is possible to send files and even binary data such as serialized Java objects!

* In the Servlet 2.4 specification SingleThreadModel has been deprecated, why? (SERVLET)
Because it is not practical to have such model. Whether you set isThreadSafe to true or false, you should take care of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the page level.

* Can we use the constructor, instead of init(), to initialize a servlet? (SERVLET)
Its possible but not recommended. The original reason for init() was that, in ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructor a ServletConfig. That no longer applies, but still, the servlet containers call the no-arg constructor. Thus we do not have access to a ServletConfig or ServletContext. (GenericServlet has two methods init() and init(ServletConfig config)

* How many cookies can one set in the response object of the servlet? Are there any restrictions on the size of cookies? (SERVLETS)
If the client is using Netscape, the browser can receive and store 300 total cookies
4 kilobytes per cookie (including name)
20 cookies per server or domain

* What's the difference between sendRedirect( ) and forward( ) methods?
A HttpServletResponse.sendRedirect method creates a new request (it's also reflected in browser's URL ).
Where as RequestDispatcher.forward method forwards the same request to the new target(hence the change is NOT reflected in browser's URL).
The
sendRedirect request scope objects are no longer available after a redirect because it results in a new request, but it's available in forward.
SendRedirect is slower compared to forward.

* Is there some sort of event that happens when a session object gets bound or unbound to the session?
HttpSessionBindingListener will hear the events When an object is added and/or remove from the session object, or when the session is invalidated, in which case the objects are first removed from the session, whether the session is invalidated manually or automatically (timeout).

* What do the differing levels of bean storage (page, session, app) mean?
page life time - NO storage. This is the same as declaring the variable in a scriptlet and using it from there.
session life time - request.getSession(true).putValue("myKey", myObj);
application level - getServletConfig().getServletContext().setAttribute("myKey ",myObj ). Application level objects can be used by multiple servlets.
request level - The storage exists for the lifetime of the request, which may be forwarded between jsp's and servlets

* Is it true that, servlet containers, service each request, by creating a new thread? If that is true, how does a container handle a sudden dramatic surge, in incoming requests, without significant performance degradation?
The implementation depends on the Servlet engine. For each request generally, a new Thread is created. But to give performance boost, most containers, create and maintain a thread pool at the server startup time. To service a request, they simply borrow a thread from the pool and when they are done, return it to the pool.
For this thread pool, upper bound and lower bound is maintained. Upper bound prevents the resource exhaustion problem associated with unlimited thread allocation. The lower bound can instruct the pool not to keep too many idle threads, freeing them if needed.

* What is URL Encoding and URL Decoding?
URL encoding is the method of replacing all the spaces and other extra characters into their corresponding Hex Characters.
Decoding is the reverse process converting all Hex Characters back their normal form.
For Example consider this URL, /ServletsDirectory/Hello'servlet/
When Encoded using URLEncoder.encode("/ServletsDirectory/Hello'servlet/")
the output is: http%3A%2F%2Fwww.javacommerce.com%2FServlets+Directory%2FHello%27servlet%2F This can be decoded back using:
URLDecoder.decode("http%3A%2F%2Fwww.javacommerce.com%2FServlets+Directory%2FHello%27servlet%2F")
the output is: "/ServletsDirectory/Hello'servlet/"

* Do objects stored in a HTTP Session need to be serializable? Or can they store any object?
Yes, the objects need to be serializable, but only if our servlet container supports persistent sessions. Most lightweight servlet engines (like Tomcat) do not support this. However, many EJB-enabled servlet engines do. Even if our engine does support persistent sessions, it is usually possible to disable this feature.

* What is the difference between session and cookie?
The difference between session and a cookie is two-fold.
1) Session should work regardless of the settings on the client browser. Even if users decide to forbid the cookie (through browser settings) session still works. There is no way to disable sessions from the client browser.
2) Session and Cookies differ in types and amount of information they are capable of storing.
Javax.servlet.http.Cookie class has a setValue() method that accepts Strings. javax.servlet.http.HttpSession has a setAttribute() method which takes a String to denote the name and java.lang.Object which means that HttpSession is capable of storing any java object. Where as Cookie can only store String objects.

* What is HttpTunneling?
HTTP tunneling is used to encapsulate other protocols within the HTTP or HTTPS protocols. Normally the intra-network of an organization is blocked by a firewall and the network is exposed to the outer world only through a specific web server port , that listens for only HTTP requests. To use any other protocol, that by passes the firewall, the protocol is embedded in HTTP and send as HttpRequest. (Applet Tunneling) (Implement HTTPS tunneling) (JavaTunnelService Examples)

* How can a servlet refresh automatically if some new data has been entered the database? (SERVLET)
You can use a client-side Refresh or Server Push. (Comet API)

* What is Server Side Push and how is it implemented and when is it useful?
Server Side push is useful when data needs to change regularly on the clients application or browser, without intervention from client. Standard examples might include apps like Stock's Tracker, Current News etc. As such server cannot connect to client's application automatically. The mechanism used is, when client first connects to Server, (Either through login etc..), then Server keeps the TCP/IP connection open.
It's not always possible or feasible to keep the connection to Server open. So another method used is, to use the standard HTTP protocols ways of refreshing the client page, which is normally supported by all browsers.
<.meta http-equiv='Refresh' content='5;URL=/servlet/stockquotes/'.>
This will refresh the page in the browser automatically and loads the new data every 5 seconds.

* Request parameter How to find whether a parameter exists in the request object?
1. boolean hasFoo = !(request.getParameter("foo") == null || request.getParameter("foo").equals(""));
2. boolean hasParameter = request.getParameterMap().contains(theParameter);
(which works in Servlet 2.3+)

* What is the Max amount of information that can be saved in a Session Object?
As such there is no limit on the amount of information that can be saved in a Session Object. Only the RAM available on the server machine is the limitation.
The only limit is the Session ID length(Identifier) , which should not exceed more than 4K. If the data to be store is very huge, then it's preferred to save it to a temporary file onto hard disk, rather than saving it in session. Internally if the amount of data being saved in Session exceeds the predefined limit, most of the servers write it to a temporary cache on Hard disk. (Tutor)

* How can we send user authentication information while makingURLConnection?
We may want to use HttpURLConnection.setRequestProperty and set all the appropriate headers to HTTP authorization.

* What is the difference between GenericServlet and HttpServlet?
A: A GenericServlet has a service() method aimed to handle protocol-independent requests.
GenericServlet is for servlets that might not use HTTP, like for instance FTP service. As of only Http is implemented completely in HttpServlet.
The GenericServlet has a service() method that gets called when a client request is made. This means that it gets called by both incoming requests and the HTTP requests are given to the servlet as they are.
HttpServlet extends GenericServlet and adds support for doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(), doDelete(), doTrace() methods (HTTP 1.1). Both these classes are abstract.

* Can we invoke a JSP error page from a servlet?
Yes, we can invoke the JSP error page and pass the exception object to it from within a servlet. The trick is to create a request dispatcher for the JSP error page, and pass the exception object as a javax.servlet.jsp.jspException request attribute. However, note that you can do this from only within controller servlets. If your servlet opens an OutputStream or PrintWriter, the JSP engine will throw the following translation error:
java.lang.IllegalStateException: Cannot forward as OutputStream or Writer has already been obtained
The following code snippet demonstrates the invocation of a JSP error page from within a controller servlet:
protected void sendErrorRedirect(HttpServletRequest request, HttpServletResponse response, String errorPageURL, Throwable e) throws ServletException, IOException {
request.setAttribute ("javax.servlet.jsp.jspException", e);
getServletConfig().getServletContext(). getRequestDispatcher(errorPageURL).forward(request, response); }
public void doPost(HttpServletRequest request, HttpServletResponse response) {
try { // do something
} catch (Exception ex) { try { sendErrorRedirect(request,response,"/jsp/MyErrorPage.jsp",ex);
} catch (Exception e) { e.printStackTrace(); } } }

* How can I run multiple instances of the same servlet class in the same WebLogic Server instance?
If you want to run multiple instances, your servlet will have to implement the SingleThreadModel interface. An instance of a class that implements the SingleThreadModel interface is guaranteed not to be invoked by multiple threads simultaneously. Multiple instances of a SingleThreadModel interface are used to service simultaneous requests, each running in a single thread.
When designing your servlet, consider how you use shared resources outside of the servlet class such as file and database access. Because there are multiple instances of servlets that are identical, and may use exactly the same resources, there are still synchronization and sharing issues that must be resolved, even if you do implement the SingleThreadModel interface.

Java Platform, Micro Edition (Java ME) here a application MIDlet, is designed for the Mobile Information Device Profile, MIDP is one of the Java ME specifications.

Wireless Development. How to write and deploy a servlet, and then how to hook up a MIDlet with the servlet.


* * * * * * * * * * * *
*[Read: He is the one!]

Home Download Music Prayers Life Is Beautiful Add to Google
Life is Beautiful.
*Creating successful constructive personality. *Why God Gave Us Friends? *Way-to-Paradise. *Creating-the-Beautiful-World. *Doing-the-job-of-goodness. *Life-is-Meaningful. *The-A-to-Z-for-Goodness. *Life-is-full-of-Tests. *History-Proves-That. *Love-in-different-forms. *True-to-the-heart.

Java Server Pages



* Explain the life-cycle methods in JSP?
A: The generated servlet class for a JSP page implements the HttpJspPage interface of the javax.servlet.jsp package.
The HttpJspPage interface extends the JspPage interface which extends Servlet interface of the javax.servlet package. The generated servlet class thus implements all the methods of these three interfaces.
The JspPage interface declares only two methods: "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 interface specifically for the JSP pages serving HTTP requests. This interface declares one method "_jspService()"
JspPage.jspInit()- The container calls the jspInit() to initialize the servlet instance. It is called before any other method, and is called only once for a servlet instance.
HttpJspPage._jspservice()- The container calls the method for each request, passing the request and response objects. This method cannot be overridden.
JspPage.jspDestroy()- The container calls this method to destroy the servlet instance. It is the last method called in the servlet instance.

* What are the phases in JSP? (JSP)
A: Translation phase, conversion of JSP to a Servlet source, then the Compilation of servlet source into a class file. The translation phase is typically carried out by the JSP engine itself, when it initially receives an request for the JSP page. The init(), service() and destroy() are the life cycle methods.

* What JSP life cycle methods can we override? (Sun-Tutor-1) (Sun-Tutor-2)
A: We can override the jspInit() and jspDestroy() methods within a JSP page. jspInit() can be useful for allocating resources like database connections, network connections, and so forth for the JSP page. It is good programming practice to free any allocated resources within jspDestroy(). Note that we cannot override the _jspService() method within a JSP page.
The jspInit() and jspDestroy() methods are each executed just once during the lifecycle of a JSP page and are typically declared as JSP declarations:
<.%! public void jspInit() { . . . } %>
<.%! public void jspDestroy() { . . . } %>

* How many JSP scripting elements are there and what are they? (Elements)
A: There are three JSP scripting language elements: declarations, scriptlets, expressions.

* What is a Expression tag element?
A: 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 and is short for out.println().
We cannot use a semicolon to end an expression. Only one statement per tag.
Expression tag is used to insert Java values directly into the output.
The following Expression tag displays time on the output: <.%= (new java.util.Date()).toLocaleString() %>
The same thing can be done using Scriptlet tag: <.% String str = (new java.util.Date()).toLocaleString(); out.println(str); %>

* What is a Declaration tag element?
A: A declaration tag (<.%! -- %>) declares one or more variables or methods to be used in the JSP source file. We can declare any number of variables or methods within one declaration tag, as long as they are separated by semicolons. The declaration must be valid in the scripting language used in the JSP file and must contain at least one complete declarative statement.
<.%! some declarations %>
<.%! int i = 0; %>
<.%! int a, b, c; %>

* What is a Scriptlet tag element?
A: A scriptlet tag (<.% --- %>) can contain any number of language statements, variable or method declarations, or expressions that are valid in the scripting language. Within scriptlet tags, we can:
1.Declare variables or methods.
2.Write expressions valid in the scripting language.
3.Use any of the JSP implicit objects or any object declared with a <.jsp:usebean> tag.
We cannot include: plain text, HTML-encoded text, or other JSP tags in the scriptlet.
Scriptlets are executed at request time, when the JSP engine processes the client request. If the scriptlet produces output, the output is stored in the out object, from which it is displayed.
Between <.% and %> tags,any valid Java code is called a Scriptlet. This code can access any variable or bean declared.
For example,to print a variable: <.% String username="visualbuilder"; out.println(username); %>

* How do we use a scriptlet to initialize a newly instantiated bean? (JavaBean)
A: A jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated. Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean. (Tutor) (Sun 1.4 Tutor)
The following example shows the "today" property of the Foo bean initialized to the current date when it is instantiated. Note that here, we use a scriptlet within the jsp:setProperty action. (Web Services)
<.jsp:usebean id='foo' class='com.Bar.Foo'>
<.jsp:setproperty name='foo' property='today' value='_'>
<.%-- scriptlets calling bean setter methods go here --%>
<./jsp:setproperty>

What are implicit objects? List them?
These are the objects which are readily available in the JSP file without any declarations or initializations. These objects are parsed by the JSP engine and are inserted into the generated servlet.
List of implicit objects: request, response, pageContext, session, application, out, config, page, exception.

Difference between forward and sendRedirect? (Java Quiz)
A: The <.jsp:forward> element forwards the request object containing the client request information from one JSP file to another file. The target file can be an HTML file, another JSP file, or a servlet, as long as it is in the same application context as the forwarding JSP file. When we invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completly with in the web container.
The sendRedirect sends HTTP temporary redirect response to the browser, and browser creates a new request to the redirected page. When a sendRedirect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. The browser issues a completely new request. Any object that is stored as request attribute before the redirect occurs will be lost. Thus HttpServletResponse.sendRedirect kills the session variables. This extra round trip makes a redirect slower than the forward.

What is the difference between <.jsp:include page = ... > and <.%@ include file = ... >?
A: Both the tags includes the information from one page in another. The differences are as follows: (JSP Syntax)
<.jsp:include page = "/index.jsp"
>: This is like a function call from one JSP to another JSP. The included page is executed and the generated html content is included in the content of calling JSP. This happens at runtime. It is executed each time the page is accessed by the client. This approach is useful for modularizing the web application. If the included file changes, then the new content will be included in the output.
<.%@ include file = "relativeURL" >: (OR <.jsp:directive.include file="_">) A relative URL is just the path segment of an URL, without a protocol, port, or domain name (Ex: "/beans/calendar.jsp"). In this case the content of the included file is textually embedded in the requested JSP page. The include process is STATIC.
The included file is added at the time of page translation, i.e before translation of jsp to servlet. The included file must not contain <.html>, <./html>, <.body>, or <./body> tags, as the entire content of the included file is added to the including JSP page. The included file can be a JSP page, HTML file, XML document, or text file.

* What is the difference between directive include and jsp include?
<.%@ include.> : Used to include static resources during translation time.
<.jsp:include.>: Used to include dynamic content or static content during runtime.

* How do we include static files within a JSP page?
Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. The following example shows the syntax:
<.%@ include file="copyright.html" %> OR <.jsp:directive.include file="relativeURL" />
Do note that we must always supply a relative URL for the file attribute. Although you can also include static resources using the action, this is not advisable as the inclusion is then performed for each and every request.

* How do we mix JSP and SSI #include?
If we are just including raw HTML, we may use the #include directive inside the .jsp file.
<.!--#include file="data.inc"-->.
This is used for including non-JSP files.
But it's trickier if we want the server to evaluate any JSP file that's included. If our data.inc file contains jsp code, we have to use <.%@ vinclude="data.inc" %>

* How to pass information from JSP to included JSP?
Using <.jsp:param.> tag.

* How does JSP handle run-time exceptions?
A: You can use the errorPage attribute of the page directive to handle uncaught run-time exceptions automatically forwarded to an error processing page. For example: <.%@ page errorPage="error.jsp" %> redirects the browser to the JSP page "error.jsp" if an uncaught exception is encountered during request processing. Within error JSP, if you indicate that it is an error-processing page, using the directive: <.%@ page isErrorPage="true" %> the Throwable object describing the exception may be accessed within the error page via the exception implicit object. Note: We must always use a relative URL as the value for the errorPage attribute.

* How can we get to print the stack-trace for an exception occurring within the JSP page?
By printing out the exception's stack trace, we can usually diagnose a problem better when debugging JSP pages. By looking at a stack trace, a programmer should be able to discern which method threw the exception and which method called that method. However, we cannot print the stack-trace using the JSP out implicit variable, which is of type JspWriter. We may have to use a PrintWriter object instead. The following snippet demonstrates how we can print a stack-trace from within a JSP error page:
<.%@ page isErrorPage="true" %.>
<.% out.println(" ");
PrintWriter pw = response.getWriter();
exception.printStackTrace(pw); out.println(" "); %.>

* Can we just abort processing a JSP?
Yes we can, because our JSP is just a servlet method, we can just put a <.% return; %.> whereever necessary.

* What is a JSP output comment?
Answer: A comment that is sent to the client in the viewable page source. The JSP engine handles an output comment as uninterpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser.
JSP Syntax
<.!-- comment [ <%= expression %> ] -->
Example 1
<.!-- This is a commnet sent to client on <%= (new java.util.Date()).toLocaleString() %> -->
Displays in the page source:
<.!-- This is a commnet sent to client on (Month) (Date), (Year) -->

How can we implement a thread-safe JSP page? What are the advantages and Disadvantages of using it?
A: We can make our JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <.%@ page isThreadSafe="false" % > within our JSP page. With this, instead of a single instance of the servlet generated for our JSP page loaded in memory, we will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized. We can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for our JSP engine. More importantly, we must avoid using the tag for variables. If we do use this tag, then one should set isThreadSafe to true, as mentioned above. Otherwise, all requests to that page will access those variables, causing a nasty race condition. SingleThreadModel is not recommended for normal use. There are many pitfalls, including the example above of not being able to use . Its better to make them thread-safe the old fashioned way.

* What is a Hidden Comment?
Answer: A comment that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide or "comment out" part of your JSP page.
You can use any characters in the body of the comment except the closing --%> combination. If you need to use --%> in your comment, you can escape it by typing --%\>.
JSP Syntax
<.%-- comment --%>
Examples
<.%@ page language="java" %>
<.title>A Hidden Comment <./title>
<.%-- This comment will not be visible to the client in the page source --%>

How can we prevent the word "null" from appearing in our HTML input text fields when we populate them with a resultset that has null values?
A: We can make a simple wrapper function, like String blanknull(String s) { return (s == null) ?"":s; } then use it inside our JSP form, like <.input name="lastName" value="<.%=blanknull(lastName)%.>" type="text".>

What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?
A: Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not scale well. If we anticipate our users to increase in the future, we may be better off implementing explicit synchronization for our shared data. The key however, is to effectively minimize the amount of code that is synchronized so that we take maximum advantage of multithreading. Also, note that SingleThreadModel is pretty resource intensive from the server's perspective. The most serious issue however is when the number of concurrent requests exhaust the servlet instance pool. In that case, all the unserviced requests are queued until something becomes free - which results in poor performance. Since the usage is non-deterministic, it may not help much even if we did add more memory and increased the size of the instance pool.

How can we enable session tracking for JSP pages if the browser has disabled cookies?
A: We know that session tracking uses cookies by default to associate a session identifier with a unique user. If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking using URL rewriting. URL rewriting essentially includes the session ID within the link itself as a name/value pair. However, for this to be effective, we need to append the session ID for each and every link that is part of our servlet response. Adding the session ID to a link is greatly simplified by means of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if we are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input. Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the browser; if so, the input URL is returned unchanged since the session ID will be persisted as a cookie. Consider the following example, in which two JSP files, say hello1 JSP and hello2 JSP, interact with each other. Basically, we create a new session within hello1 JSP and place an object within this session. The user can then traverse to hello2 JSP by clicking on the link present within the page. Within hello2 JSP, we simply extract the object that was earlier placed in the session and display its contents. Notice that we invoke the encodeURL() within hello1 JSP on the link used to invoke hello2 JSP; if cookies are disabled, the session ID is automatically appended to the URL, allowing hello2 JSP to still retrieve the session object. Try this example first with cookies enabled. Then disable cookie support, restart the brower, and try again. Each time you should see the maintenance of the session across pages. Do note that to get this example to work with cookies disabled at the browser, your JSP engine has to support URL rewriting.
hello1.JSP: <.%@ page session="true" %.> <.% Integer num = new Integer(100); session.putValue("num",num); String url =response.encodeURL("hello2.jsp");%.> <.a href='<.%=url%.>'.>hello2.jsp<./a>
hello2.JSP: <.%@ page session="true" %.> <.% Integer i= (Integer )session.getValue("num"); out.println("Num value in session is " + i.intValue()); %>

What is the difference b/w variable declared inside a declaration part and variable declared in scriplet part?
A: Variable declared inside declaration part is treated as a global variable. That means after conversion of JSP file into servlet, that variable will be outside the service method or it will be declared as instance variable. And its scope is available to complete JSP in the converted servlet class. Where as if we declare a variable inside a scriplet, that variable will be declared inside a service method and its scope is within the service method.

Is there a way to execute a JSP from the command-line or from our own application?
A: There is a little tool called JSPExecutor that allows you to do just that. The developers aim was not to write a full blown servlet engine, but to provide means to use JSP for generating source code or reports. Therefore most HTTP-specific features (headers, sessions, etc) are not implemented, i.e. no response-line or header is generated. Nevertheless we can use it to pre-compile JSP for our website.
GnuJsp is a similar tool, like JspExtractor. GNU-JSP translates "*.jsp" files to java source files. Also compiles and runs them. It runs on a wide range of platforms, webservers and servlet engines.

* Can a JSP page process HTML FORM data?
Yes it can, unlike servlets, we are not required to implement HTTP-protocol specific methods like doGet() or doPost() within our JSP page. we can obtain the data for the FORM input elements from the request implicit object within a scriptlet or expression as:
<.% String item = request.getParameter("item"); int howMany = new Integer (request.getParameter ("units") ). intValue () ; %.>
or <.%= request.getParameter("item") %.>

* How can we perform browser redirection from a JSP page?
We can use the response implicit object to redirect the browser to a different resource, as:
response.sendRedirect("http://www.foo.com/path/error.html");
We can also alter the Location HTTP header attribute, as shown below:
<.% response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); String newLocn = "/newpath/index.html"; response.setHeader("Location",newLocn); %>
We can also use the: <.jsp:forward page="/newpage.jsp">
Note that we can only use this before any output has been sent to the client.
Hope this is the case with the response.sendRedirect() method as well.
We can pass any parameters using <.jsp:forward page="/servlet/login"> <.jsp:param name="username" value="jsmith"> <./jsp:param>.>

* Can a JSP page instantiate a serialized bean?
Yes, it can! The useBean action specifies the beanName attribute, which can be used for indicating a serialized bean. For example:
<.jsp:useBean id="shop" type="shopping.CD" beanName="CD"> <.jsp:getproperty name="shop" property="album">
Although we have to name our serialized file "filename.ser", we indicate "filename" as the value for the beanName attribute. We have to place our serialized file within the WEB-INF\jsp\beans directory for it to be located by the JSP engine. (Serialization Example.)

* Can we make use of a ServletOutputStream object from within a JSP page?
No we cannot. We are supposed to make use of only a JSPWriter object (Available to us in the form of the implicit object out) for replying to clients. A JSPWriter can be viewed as a buffered version of the stream object returned by response.getWriter(), although from an implementation perspective, it is not. A page author can always disable the default buffering for any page using a page directive as: <.%@ page buffer="none" autoflush="true/false" %>

* Can we stop JSP execution while in the midst of processing a request?
Yes we can. Preemptive termination of request processing on an error condition is a good way to maximize the throughput of a high-volume JSP engine. The trick is to use the return statement when we want to terminate further processing.
For example, consider:
<.% if (request.getParameter("foo") != null) { // generate some html or update bean property } else { /* output some error message or provide redirection back to the input form after creating a memento bean updated with the 'valid' form elements that were input. this bean can now be used by the previous form to initialize the input elements that were valid then, return from the body of the _jspService() method to terminate further processing */ return; } %>

* How can we view any compilation/parsing errors at the client while developing JSP pages?
With JSWDK 1.0, set the following servlet initialization property within the \WEB-INF\servlets.properties file for your application:
jsp.initparams=sendErrToClient=true
This will cause any compilation/parsing errors to be sent as part of the response to the client.

* Is there a way to reference the "this" variable within a JSP page?
Yes, there is. Under JSP 1.0, the page implicit object is equivalent to "this", and returns a reference to the servlet generated by the JSP page.

* How can we instantiate a bean whose constructor accepts parameters using the useBean tag?
Consider the following bean: package bar;
public class FooBean {
public FooBean(SomeObj arg) { ... }
//getters and setters here }
The only way you can instantiate this bean within your JSP page is to use a scriptlet. For example, the following snippet creates the bean with session scope:
<.% SomeObj x = new SomeObj(...); bar.FooBean foobar = new FooBean(x); session.putValue("foobar",foobar); %> You can now access this bean within any other page that is part of the same session as: <.% bar.FooBean foobar = session.getValue("foobar"); %>
To give the bean "application scope", we have to place it within the ServletContext as:
<.% application.setAttribute("foobar",foobar); %>
To give the bean "request scope", we have to place it within the request object as:
<.% request.setAttribute("foobar",foobar); %>
If we do not place the bean within the request, session or application scope, the bean can be accessed only within the current JSP page (page scope).
Once the bean is instantiated, it can be accessed in the usual way:
<.jsp:getProperty name="foobar" property="someProperty".>
<.jsp:setProperty name="foobar" property="someProperty" value="someValue".>

* Can we implement an interface in a JSP?
No, we cannot implement an interface in a JSP file.

* What is the difference between ServletContext and PageContext?
ServletContext: Gives the information about the container.
PageContext: Gives the information about the Request.

* What is the difference between RequestDispatcher and sendRedirect?
RequestDispatcher: server-side redirect with request and response objects.
sendRedirect : Client-side redirect with new request and response objects.

*
How to set a cookie and delete a cookie in a JSP page?
<.% //creating a cookie
Cookie mycook = new Cookie("name","value");
response.addCookie(mycook);
//delete a cookie
Cookie killmycook = new Cookie("mycook","value");
killmycook.setMaxAge(0);
killmycook.setPath("/");
response.addCookie(killmycook); %.>

* How can you store international / Unicode characters into a cookie?
One way is, before storing the cookie URLEncode it.
String = URLEncoder.encode(str); // This method uses the platform's default encoding as the encoding scheme.
And use URLDecoder.decode(str) when you get the stored cookie.

* Is JSP technology extensible?
YES. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries. JSP developers can create custom tag libraries by createing their own tag libraries for common functions. This lets web page developers work with familiar tools and constructs, such as tags, to perform sophisticated functions.

* How can we prevent the output of JSP or Servlet pages from being cached by the browser?
You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser. Just execute the following scriptlet at the beginning of your JSP pages to prevent them from being cached at the browser. You need both the statements to take care of some of the older browser versions.
<.% response.setHeader("Cache-Control","no-store"); //HTTP 1.1 response.setHeader("Pragma","no-cache"); //HTTP 1.0 response.setDateHeader ("Expires", 0); //prevents caching at the proxy server %.>

* How can we use comments within a JSP page?
We can use "JSP-style" comments to selectively block out code while debugging or simply to comment our scriptlets. JSP comments are not visible at the client side. For example:
<.%-- this scriptlet is commented <.% out.println("Hello World"); %.> --%.>
We can also use HTML-style comments anywhere within our JSP page. These comments are visible at the client side. For example:
<.!-- (c) 2004 sun-java.com --.>
We can also use comments supported by our JSP scripting language within our scriptlets. For example, assuming Java is the scripting language, we can have:
<.% //some comment /** yet another comment **/ %.>

* Whats the meaning of error: "Response has already been committed"?
Case 1: We can get an IllegalStateException when we attempt to write to the output stream after something else has been written to it. For example if we are using jsp:include, if the outer jsp has already called getWriter() on the response object, then the inner jsp will get an IllegalStateException if it calls getOutputStream() on the same response object. Response.sendRedirect() throws this error if the response has already been committed increasing the buffer of jsp page can help so that it doesn't get committed before having to send the redirect <%@ page buffer="16kb" %> (default is 8kb).
Case 2: This error is shown only when we try to redirect a page after we have already written something in that page. This happens because HTTP specification forces the header to be set up before the layout of the page can be shown (to make sure of how it should be displayed, content-type="text/html" or "text/xml" or "plain-text" or "image/jpg", etc.) When we try to send a redirect status (Number is line_status_402), our HTTP server cannot send it if it hasn't finished to set up the header. There are no problems if the header is not yet set, but if it's already begun to set up the header, then our HTTP server expects these headers to be finished setting up and it cannot be the case if the stream of the page is not over. In this case it's like we have a file started with some output (like testing our variables.) and before we indicate that the file is over (and before the size of the page can be set up in the header), we try to send a redirect status. It's improper as per the specifications of HTTP 1.0 and 1.1.

* How can we declare methods within a JSP page?
We can declare methods for use within our JSP page as declarations. The methods can then be invoked within any other methods we declare, or within JSP scriptlets and expressions. Do note that we do not have direct access to any of the JSP implicit objects like request, response, session and so forth from within JSP methods. However, we should be able to pass any of the implicit JSP variables as parameters to the methods we declare. For example: <.%! public String whereFrom(HttpServletRequest req) { HttpSession ses = req.getSession(); ... return req.getRemoteHost(); } %.>
<.% out.print("Hi there, this is out.print method. "); %.>
<.%= whereFrom(request) %.>
Another Example
file1.jsp:
<.%@page contentType="text/html" %.>
<.%! public void test(JspWriter writer) throws IOException { writer.println("Hello!"); } %.>
file2.jsp:
<.%@include file="file1.jsp" %.>
<.% test(out); %. >

* Is there any way we can set the inactivity lease period on a per-session basis?
Typically, a default inactivity lease period for all sessions is set within our JSP engine admin screen OR associated properties file. However, if our JSP engine supports the Servlet 2.1 API, we can manage the inactivity lease period on a per-session basis. This is done by invoking the HttpSession.setMaxInactiveInterval() method, right after the session has been created. For example:
<% session.setMaxInactiveInterval(300); %>
would reset the inactivity period for this session to 5 minutes. The inactivity interval is set in seconds.

* How does a servlet communicate with a JSP page?
The following code snippet shows how a servlet instantiates a bean and initializes it with FORM data posted by the browser. The bean is placed into the request, and the call is then forwarded to the JSP page, Bean1.jsp, by means of a request dispatcher for downstream processing.
public void doPost (HttpServletRequest request, HttpServletResponse response) {
try {
govi.FormBean f = new govi.FormBean();
String id = request.getParameter("id");
f.setName(request.getParameter("name"));
f.setAddr(request.getParameter("addr"));
f.setAge(request.getParameter("age"));
//use the id to compute, additional bean properties like info, maybe perform a db query, etc.
f.setPersonalizationInfo(info);
request.setAttribute("fBean",f);
getServletConfig().getServletContext().getRequestDispatcher ("/jsp/Bean1.jsp").forward(request, response);
} catch (Exception ex) { . . . } }
The JSP page Bean1.jsp can then process fBean, after first extracting it from the default request scope via the useBean action.
<.jsp:useBean id="fBean" class="govi.FormBean" scope="request" .>
<.jsp:getProperty name="fBean" property="name" .>
<.jsp:getProperty name="fBean" property="addr" .>
<.jsp:getProperty name="fBean" property="age" .>
<.jsp:getProperty name="fBean" property="personalizationInfo" .>

* How do I have the JSP-generated servlet subclass my own custom servlet class, instead of the default?
One should be very careful when having JSP pages extend custom servlet classes as opposed to the default one generated by the JSP engine. In doing so, you may lose out on any advanced optimization that may be provided by the JSP engine. In any case, your new superclass has to fulfill the contract with the JSP engine by:
Implementing the HttpJspPage interface, if the protocol used is HTTP, or implementing JspPage otherwise Ensuring that all the methods in the Servlet interface are declared final Additionally, your servlet superclass also needs to do the following:
The service() method has to invoke the _jspService() method
The init() method has to invoke the jspInit() method
The destroy() method has to invoke jspDestroy()
If any of the above conditions are not satisfied, the JSP engine may throw a translation error.
Once the superclass has been developed, you can have your JSP extend it as follows:
<.%@ page extends="packageName.ServletName" %.>

* How do you pass an InitParameter to a JSP?
The JspPage interface defines the jspInit() and jspDestroy() method which the page writer can use in their pages and are invoked in much the same manner as the init() and destory() methods of a servlet. The example page below enumerates through all the parameters and prints them to the console.
<.%@ page import="java.util.*" %.>
<.%! ServletConfig cfg =null; public void jspInit() { ServletConfig cfg=getServletConfig(); for (Enumeration e=cfg.getInitParameterNames(); e.hasMoreElements();) { String name=(String)e.nextElement(); String value = cfg.getInitParameter(name); System.out.println(name+"="+value); } } %.>

* How can my JSP page communicate with an EJB Session Bean?
The following is a code snippet that demonstrates how a JSP page can interact with an EJB session bean:
<%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject, foo.AccountHome, foo.Account" %>
<%! //declare a "global" reference to an instance of the home interface of the session bean AccountHome accHome=null; public void jspInit() { //obtain an instance of the home interface InitialContext cntxt = new InitialContext( ); Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB"); accHome = (AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class); } %>
<% //instantiate the session bean Account acct = accHome.create(); //invoke the remote methods acct.doWhatever(...); // etc etc... %>

* How can my application get to know when a HttpSession is removed?
Define a Class HttpSessionNotifier which implements HttpSessionBindingListener and implement the functionality what you need in valueUnbound() method.
Create an instance of that class and put that instance in HttpSession.

* We made our class Cloneable but still we get "Can’t access protected method clone". Why?
Some of the Java books imply that all we have to do in order to have our class support clone() is implement the Cloneable interface. But it's not so. Perhaps that was the intent at some point, but that’s not the way it works currently. As it stands, we have to implement our own public clone() method, even if it doesn’t do anything special and just calls super.clone().



*[Read All Stories.]

*[Read:Two Wolves.] *[Moral Stories.] *[Karna.] *[Ekalavya.] *[Krishna-and-Sudama.] *[Freedom-and-Prison.]

*[Read:Blind-Men-Buddha.] *[Tied-Elephants.] *[Critical-mass-Experiment.] *[Healing-affection.]

*[Read:Punyakoti-Truth.] *[Reply-to-Question.] *[Hasty-decision.] *[False-Cry.] *[Views.]

Read: Peace

Home Download Music Prayers Puzzles - Riddles - Think Add to Google

Stories.

*The-Monkey’s-Justice-for-two-cats. *The-Blind-Men-And-The-Elephant. *Manoj-Kargudri. *Two-rich-merchants-and-a-thief. *Healing-is-contagious. *Two-saints-in-a-market-place. *A-Terrible-Fight-Between-Two-Wolves. *Hen-that-laid-golden-eggs. *Healing-forgiveness-and-affection. *Elephants-held-by-small-ropes. *Story-of-Punyakoti-the-strength-of-truth. *What-is-the-reason? *Reply-Depends-on-the-Question. *Critical-mass-Experiment. *The-Brahman's-Wife-and-the-Mongoose. *The-Boy-Who-Cried-Wolf. *Difference-between-Heaven-and-Hell! *Freedom-and-Prison! *It's-in-Your-Eyes!

About Me

My photo
Simple guy who believes in being Competitive rather than being Ambitious. Persistence to be constructive, without frustrations, is a good purpose of life.
.

* * * * * * * * * * * * *

MeetUp Message Board:
Read: Wishes-and-Prayers. *Issue-of-Illegal-Immigration-&-Happy-Kingdom. *The-New-York-Hillary-Rodham-Clinton *Cast-God-Religion! *Barack-Obama-Meetup *Duty- Responsibility-Law-and-Order *John-Edwards-One-America *Good-Wishes-Life-is-Meaningful-&-Beautiful *Dennis-Kucinich-Meetup *Let-there-be-peace! *Bill-Richardson-for-President-2008 *Logic-of-Good-and-Bad-convert-bad-to-good *MORAL-STORY-Elephants-held-by-small-ropes.
* * * * * * * * * * * * *

Realizations.
*Realizations-In-Real-Life-Please-be-gentle-and-humble. *Manoj-D-Kargudri. *Amazing-Constructive-Vibrations. *Astrology. *Creating-Leaders. *How-ideas-are-concluded-and-decisions-are-materialized. *“Relationships-in-Life”-“Partnerships-in-Life”. *The-path-of-victory-the-path-of-life-winning-in-looseing. *An-attempt-for-definition. *Speak-with-a-heart. *These-are-contagious. *Key-to-happy-kingdom. *MIRACLES. *Better-to-create-one! *Cast-God-and-Religion! *Manoj-Kargudri. *Things-become-inevitable! *We-are-all-looking-for! *Phase-of-Life. *Destiny-Karma-and-God. *Struggle-perfection-and-Money. *Independence-and-Freedom. *Relationships-and-Happiness.
* * * * * *

Quotes.
*Love-Compassion-Tolerance-Forgiveness-Courtesy. *Manoj-D-Kargudri. *True-to-Heart-going-back-to-Basics!
* * * * * *

Puzzles-Riddles-Think.
*River-Crossing-Puzzles-Brain-Teasers. *Manoj-Kargudri. *Perpetual-Motion-Gravity-and-Kinetics. *Illusions-Paradoxes-Perpetually-ascending-staircase. *Milk-man-with-no-measureing-jar. *Amazing-Horoscope-Mind-Reader. *Find-the-hidden-images-in-these-STEREOGRAMS. *Are-they-12-or-13? *What-would-U-do? *ABCD-Four-Digit-Number. *10-Digit-Number. *4-QUESTIONS...GOOD-LUCK! *Think-Wise.
* * * * * *

Prayers.
*God-gave-us-everything-we-ever-needed. *Good-Wishes. *Manoj-Kargudri. *Love-Compassion-Tolerance-Forgiveness-Courtesy. *Interview-With-God! *He-is-the-one! *Candle-of-Hope! *Let-there-be-Peace! *Manoj-Kargudri.
* * * * * *

Perceptions.
*Issue-of-Illegal-Immigration. *To-which-religion-does-this-universe-belongs-to? *Law-and-order-helps-to-maintain-justice. *Implementing-regulations-by-justice. *Putting-our-sincere-efforts. *Religion-and-cast. *Impact-of-reservation-based-on-religion-and-cast. *Free-and-Fare-Education-system-Electoral-system.
* * * * * *

Stories.
*The-Monkey’s-Justice-for-two-cats. *The-Blind-Men-And-The-Elephant. *Manoj-Kargudri. *Two-rich-merchants-and-a-thief. *Healing-is-contagious. *Two-saints-in-a-market-place. *A-Terrible-Fight-Between-Two-Wolves. *Hen-that-laid-golden-eggs. *Healing-forgiveness-and-affection. *Elephants-held-by-small-ropes. *Story-of-Punyakoti-the-strength-of-truth. *What-is-the-reason? *Reply-Depends-on-the-Question. *Critical-mass-Experiment. *The-Brahman's-Wife-and-the-Mongoose. *The-Boy-Who-Cried-Wolf. *Difference-between-Heaven-and-Hell! *Freedom-and-Prison! *It's-in-Your-Eyes!
* * * * * *

Jokes.
*Please-listen-to-me. *The-Silent-Treatment! *Surgeon-Vs-Mechanic. *Manoj-Kargudri. *God's-doing-a-lot-better-job-lately.
* * * * * *

The-Bitter-Truth.
*Duty-Responsibility-Law-and-Order. *"Happy-Kingdom"-proudly-proclaimed-as-"Paradise". *Trying-to-learn-something-for-the-first-time. *Time-is-the-only-solution. *For-every-Action-there-is-an-Equal-and-Opposite-Reaction. *Logic-of-Good-and-Bad. *Manoj-Kargudri. *Duties-Responsibilities-verses-Luxuries-and-Pleasures. *Beggars!
* * * * * *

Life-is-Beautiful.
*Creating-successful-constructive-personality. *Why-God-Gave-Us-Friends? *Way-to-Paradise. *Creating-the-Beautiful-World. *Doing-the-job-of-goodness. *Life-is-Meaningful. *Manoj-Kargudri. *The-A-to-Z-for-Goodness. *Life-is-full-of-Tests. *History-Proves-That. *Love-in-different-forms. *True-to-the-heart.
* * * * * *

Prayers-To-Worship.
*Please-do-not-leave-me-ever. *Let’s-make-it-happen. *Faith-in-Patience. *The-only-one-I've-got. *Someone-somewhere. *How-I-Love-You. *Will-You? *Successful-Life. *Manoj-Kargudri. *Please-say-something. *Way-to-Paradise. *My-Everything.
* * * * * *

Friendship.
*Life-Still-Has-A-Meaning. *Heavenly-Garden. *GOD-SPEAK-TO-ME! *Why-God-Made-Friends? *I-asked-the-Lord! *A-Best-Friend! *Why-GOD-Gave-Us-Friends? *Portrait-of-a-Friend. *Friends-till-the-end. *Some-Assorted! *Forever-Friends. *What-is-a-friend!
* * * * * *

Winning-Publications.
*Significance-of-Nava-ratna (Nava-Graha). *Amazing-Constructive-Vibrations. *Manoj-Kargudri. *The-piercing-of-the-ears (karnavedha) . *Nature-Cure. *Steps-to-improve-work-place. *Steps-Involved-In-Relationships. *Some-of-the-aspects-which-materialize-the-relationships.
* * * * * *

Music-Download.
*Bhakti-Songs. *Manoj-Kargudri. *English-Songs. *Gazal-Bhajan-Hindi. *Hindi-Life. *Hindi-Love. *Hindi-Old-Kishore. *Hindi-Old-Mukesh. *Hindi-Old-Songs. *Hindi-Rock. *Hindi-Pops. *Instrumental. *Vocal-Ragas.
* * * * * *

Technology.
*READ: Why-JAVA *Manoj-Kargudri. *Start-Learning-JAVA *Why-Java's-Hot *Start-Using-LINUX *Java-Q-&-A *Question *Java-SE-6-Doc *Struts-Doc *Java-Tutorial-Index *Java-Certification *Tech. *Struts. *Manoj-Kargudri. *Servlet. *JSP. *EJB. *JNDI-JMS *SQL. *JDBC. *CORE-JAVA: *OOP *CLASS. *Manoj-Kargudri. *ABSTRACT *EXCEPTIONS *THREADS *UTILS *PACKAGES *JVM *CASTING *NETWORKING *RMI-XML
* * * * * *

MUSIC-DOWNLOAD.
*Hindi-Vocal-Raga. *Hindi-Remix-Rock. *Hindi-Old-Songs. *Hindi-Mukesh-Mohd-Rafi-Songs. *Hindi-LOVE-Songs. *Hindi-Remix-LIFE. *English-Rock-Songs. *Kannada-Janapada-Geete. *Kannada-Film-Songs. *Kannada-Devotional-Songs. *Instrumental-Music. *Manoj-Kargudri. *Hindi-Pop-Songs. *Hindi-Bhakti-Songs. *Hindi-Kishore-Kumar-SAD. *Hindi-Kishore-Kumar-JOY. *Hindi-R-D-Burman. *Hindi-Gazals. *English-Soft-Songs.
* * * * * *