Sunday, August 24, 2008

==> FAQs on Java Server Pages

What is JSP- JavaServer Pages ?
JavaServer Pages. A server-side technology, JavaServer pages are an extension to the Java servlet technology that was developed by Sun. JSPs have dynamic scripting capability that works in tandem with HTML code, separating the page logic from the static elements -- the actual design and display of the page. Embedded in the HTML page, the Java source code and its extensions help make the HTML more functional, being used in dynamic database queries, for example. JSPs are not restricted to any specific platform or server.
Jsp contains both static and dynamic resources at run time.Jsp extends web server functionalities

What are advantages of JSP
whenever there is a change in the code, we dont have to recompile the jsp. it automatically does the compilation. by using custom tags and tag libraries the length of the java code is reduced.

What is the difference between include directive & jsp:include action
include directive (): if the file includes static text if the file is rarely changed (the JSP engine may not recompile the JSP if this type of included file is modified) .
if you have a common code snippet that you can reuse across multiple pages (e.g. headers and footers)
jsp:include : for content that changes at runtime .to select which content to render at runtime (because the page and src attributes can take runtime expressions) for files that change often JSP:includenull

What are Custom tags. Why do you need Custom tags. How do you create Custom tag
1) Custom tags are those which are user defined.
2) Inorder to separate the presentation logic in a separate class rather than keeping in jsp page we can use custom tags.
3) Step 1 : Build a class that implements the javax.servlet.jsp.tagext.Tag interface as follows. Compile it and place it under the web-inf/classes directory (in the appropriate package structure).
package examples;
import java.io.*; //// THIS PROGRAM IS EVERY TIME I MEAN WHEN U REFRESH THAT PARTICULAR CURRENT DATE THIS CUSTOM TAG WILL DISPLAY
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class ShowDateTag implements Tag {
private PageContext pageContext;
private Tag parent;
public int doStartTag() throws JspException {
return SKIP_BODY; }
public int doEndTag() throws JspException {
try {
pageContext.getOut().write("" + new java.util.Date());
} catch (IOException ioe) {
throw new JspException(ioe.getMessage());
}
return EVAL_PAGE; }
public void release() {
}
public void setPageContext(PageContext page) {
this.pageContext = page;
}
public void setParent(Tag tag) {
this.parent = tag;
}
public Tag getParent() {
return this.parent; } }
Step 2:Now we need to describe the tag, so create a file called taglib.tld and place it under the web-inf directory."http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"> 1.0 1.1
myTag http://www.mycompany.com/taglib My own tag library showDate examples.ShowDateTag Show the current date
Step 3 : Now we need to tell the web application where to find the custom tags, and how they will be referenced from JSP pages. Edit the web.xml file under the web-inf directory and insert the following XML fragement.http://www.mycompany.com/taglib /WEB-INF/taglib.tld
Step 4 : And finally, create a JSP page that uses the custom tag.Now restart the server and call up the JSP page! You should notice that every time the page is requested, the current date is displayed in the browser. Whilst this doesn't explain what all the various parts of the tag are for (e.g. the tag description, page context, etc) it should get you going. If you use the tutorial (above) and this example, you should be able to grasp what's going on! There are some methods in context object with the help of which u can get the server (or servlet container) information.
Apart from all this with the help of ServletContext u can implement ServletContextListener and then use the get-InitParametermethod to read context initialization parameters as the basis of data that will be made available to all servlets and JSP pages.

What are the implicit objects in JSP & differences between them
There are nine implicit objects in JSP.
1. request : The request object represents httprequest that are trigged by service( ) invocation. javax.servlet

2. response:The response object represents the servers response to request.
javax.servlet
3. pageContext : The page context specifies the single entry point to many of the page attributes and is the convient place to put shared data.
javax.servlet.jsp.pagecontext

4. session : the session object represents the session created by the current user.
javax.Servlet.http.HttpSession

5. application : the application object represents servlet context , obtained from servlet configaration . javax.Servlet.ServletContext

6. out : the out object represents to write the out put stream .
javax.Servlet.jsp.jspWriter

7. Config :the config object represents the servlet config interface from this page,and has scope attribute. javax.Servlet.ServletConfig

8. page : The object is th eInstance of page implementation servlet class that are processing the current request.
java.lang.Object

9. exception : These are used for different purposes and actually u no need to create these objects in JSP. JSP container will create these objects automatically.
java.lang.Throwable

You can directly use these objects.

Example:
If i want to put my username in the session in JSP.
JSP Page: In the about page, i am using session object. But this session object is not declared in JSP file, because, this is implicit object and it will be created by the jsp container.
If u see the java file for this jsp page in the work folder of apache tomcat, u will find these objects are created.

What is jsp:usebean. What are the scope attributes & difference between these attributes
page, request, session, application

What is difference between scriptlet and expression

With expressions in JSP, the results of evaluating the expression are converted to a string and directly included within the output page. Typically expressions are used to display simple values of variables or return values by invoking a bean's getter methods. JSP expressions begin within tags and do not include semicolons:
But scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language. Within scriptlet tags, you can declare variables or methods to use later in the file, write expressions valid in the page scripting language,use any of the JSP mplicit objects or any object declared with a

What is Declaration
Declaration is used in JSP to declare methods and variables.To add a declaration, you must use the sequences to enclose your declarations.

How do you connect to the database from JSP
To be precise to connect jdbc from jsp is not good idea ofcourse if ur working on dummy projects connecting to msaccess u can very well use the same connection objects amd methods in ur scriplets and define ur connection object in init() method.
But if its real time u can use DAO design patterns which is widely used. for ex u write all ur connection object and and sql quires in a defiened method later use transfer object [TO ]which is all ur fields have get/set methods and call it in business object[BO] so DAO is accessd with precaution as it is the crucial. Finally u define java bean which is a class holding get/set method implementing serialization thus the bean is called in the jsp. So never connect to jdbc directly from client side since it can be hacked by any one to get ur password or credit card info.

How do you call stored procedures from JSP
By using callable statement we can call stored procedures and functions from the database.
How do you restrict page errors display in the JSP page
set isErrorPage=false

How do you pass control from one JSP page to another
we can forward control to aother jsp using jsp action tags forward or incllude

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 JSPengine. In any case, your new superclass has to fulfill the contract with the JSPngine 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 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 a browser. The bean is then 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" /

Is there a way I can set the inactivity lease period on a per-session basis?
Typically, a default inactivity lease period for all sessions is set within your JSPengine admin screen or associated properties file. However, if your JSP engine supports the Servlet 2.1 API, you 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 can I set a cookie and delete a cookie from within a JSP page?
A cookie, mycookie, can be deleted using the following scriptlet:
<%
//creating a cookie
Cookie mycookie = new Cookie("aName","aValue");
response.addCookie(mycookie);
//delete a cookie
Cookie killMyCookie = new Cookie("mycookie", null);
killMyCookie.setMaxAge(0);
killMyCookie.setPath("/");
response.addCookie(killMyCookie);
%>

How can I declare methods within my JSP page?
You can declare methods for use within your JSP page as declarations. The methods can then be invoked within any other methods you declare, or within JSP scriptlets and expressions.
Do note that you do not have direct access to any of the JSP implicit objects like request, response, session and so forth from within JSP methods. However, you should be able to pass any of the implicit JSP variables as parameters to the methods you declare.
For example:
<%!
public String whereFrom(HttpServletRequest req) {
HttpSession ses = req.getSession();
...
return req.getRemoteHost();
}
%>
<%
out.print("Hi there, I see that you are coming in from ");
%>
<%= 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);% >



How can I enable session tracking for JSP pages if the browser has disabled cookies?
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, you need to append the session ID for each and every link that is part of your servlet response. Adding the session ID to a link is greatly simplified by means of of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if you 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");
%>
'>hello2.jsp
hello2.jsp
<%@ page session="true" %>
<%
Integer i= (Integer )session.getValue("num");
out.println("Num value in session is "+i.intValue());

How do I use a scriptlet to initialize a newly instantiated bean?
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, although you are not restricted to using those alone. The following example shows the "today" property of the Foo bean initialized to the current date when it is instantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action.


value="<%=java.text.DateFormat.getDateInstance().format(new java.util.Date())
%>"/ >
<%-- scriptlets calling bean setter methods go here --%>


How does JSP handle run-time exceptions?
You can use the errorPage attribute of the page directive to have uncaught runtime 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, via the directive:
<%@ page isErrorPage="true" %>
the Throwable object describing the exception may be accessed within the error page via the exception implicit object.
Note: You must always use a relative URL as the value for the errorPage attribute.

How do I prevent the output of my 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 do I use comments within a JSP page
You can use "JSP-style" comments to selectively block out code while debugging or simply to comment your scriptlets. JSP comments are not visible at the client.
For example:
<%-- the scriptlet is now commented out
<%
out.println("Hello World");
%> --%>
You can also use HTML-style comments anywhere within your JSP page. These comments are visible at the client. For example:

Of course, you can also use comments supported by your JSP scripting language within your scriptlets. For example, assuming Java is the scripting language, you can have:
<%
//some comment
/**
yet another comment **/ %>

Can I stop JSP execution while in the midst of processing a request?
Yes. 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 (asuming Java is your scripting language) is to use the return statement when you 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;
}
%>

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 do I perform browser redirection from a JSP page?
You can use the response implicit object to redirect the browser to a different resource, as:
response.sendRedirect("http://www.exforsys.com/path/error.html");
You can also physically alter the Location HTTP header attribute, as shown below:
<%
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
String newLocn = "/newpath/index.html";
response.setHeader("Location",newLocn);
%>
You can also use the: Also note that you can only use this before any output has been sent to the client. I beleve this is the case with the response.sendRedirect() method as well. If you want to pass any paramateres then you can pass using


How do I include static files within a JSP page?
Answer 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" %>
Do note that you should 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.

What JSP lifecycle methods can I override?
You cannot override the _jspService() method within a JSP page. You can however, 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().
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() {
. . . }
%>

Can a JSP page process HTML FORM data?
Yes. However, unlike servlets, you are not required to implement HTTP-protocol specific methods like doGet() or doPost() within your JSP page. You can obtain the data for the FORM input elements via 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 do I mix JSP and SSI #include?
If you're just including raw HTML, use the #include directive as usual inside your .jsp file.

But it's a little trickier if you want the server to evaluate any JSP code that's inside the included file. If your data.inc file contains jsp code you will have to use <%@ vinclude="data.inc" %> The is used for including non-JSP files.

How can I implement a thread-safe JSP page?
You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive
<%@ page isThreadSafe="false" % > within your JSP page.

How do I 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: Do note that you should 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 you prevent the Creation of a Session in a JSP Page and why?
By default, a JSP page will automatically create a session for the request if one does not exist. However, sessions consume resources and if it is not necessary to maintain a session, one should not be created. For example, a marketing campaign may suggest the reader visit a web page for more information. If it is anticipated that a lot of traffic will hit that page, you may want to optimize the load on the machine by not creating useless sessions.

What is the page directive is used to prevent a JSP page from automatically creating a session:
<%@ page session="false">

Is it possible to share an HttpSession between a JSP and EJB? What happens when I change a value in the HttpSession from inside an EJB?
You can pass the HttpSession as parameter to an EJB method, only if all objects in session are serializable.This has to be consider as "passed-by-value", that means that it's read-only in the EJB. If anything is altered from inside the EJB, it won't be reflected back to the HttpSession of the Servlet Container.The "pass-byreference" can be used between EJBs Remote Interfaces, as they are remote references. While it IS possible to pass an HttpSession as a parameter to an EJB object, it is considered to be "bad practice (1)" in terms of object oriented design. This is because you are creating an unnecessary coupling between back-end objects (ejbs) and front-end objects (HttpSession). Create a higher-level of abstraction for your ejb's api. Rather than passing the whole, fat, HttpSession (which carries with it a bunch of http semantics), create a class that acts as a value object (or structure) that holds all the data you need to pass back and forth between front-end/back-end. Consider the case where your ejb needs to support a non-http-based client. This higher level of abstraction will be flexible enough to support it. (1) Core J2EE design patterns (2001)

Can a JSP page instantiate a serialized bean?
No problem! The useBean action specifies the beanName attribute, which can be used for indicating a serialized bean. For example:


A couple of important points to note. Although you would have to name your serialized file "filename.ser", you only indicate "filename" as the value for the beanName attribute. Also, you will have to place your serialized file within the WEB-INFjspbeans directory for it to be located by the JSP engine.

Can you make use of a ServletOutputStream object from within a JSP page?
No. You are supposed to make use of only a JSPWriter object (given to you 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 implementational perspective, it is not. A page author can always disable the default buffering for any page using a page directive as:
<%@ page buffer="none" %>

What are the steps required in adding a JSP Tag Libraries?
1. Create a TLD file and configure the required class Information.
2. Create the Java Implementation Source extending the JSP Tag Lib Class (TagSupport).
3. Compile and package it as loosed class file or as a jar under lib folder in Web Archive File for Class loading.
4. Place the TLD file under the WEB-INF folder.
5. Add reference to the tag library in the web.xml file.

Saturday, August 23, 2008

==> FAQs on Servlets

1. What is the servlet?
Servlets are modules that extend request/response-oriented servers, such as Java-enabled web servers. For example, a servlet may be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company's order database.
-Servlets are used to enhance and extend the functionality of Webserver.
-Servlets handles Java and HTML separately.

2. What are the uses of Servlets?
A servlet can handle multiple requests concurrently, and can synchronize requests. This allows servlets to support systems such as on-line conferencing. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task.

3. What are th characters of Servlet?
As Servlet are written in java, they can make use of extensive power of the JAVA API,such as networking and URL access,multithreading,databaseconnectivity,RMI object serialization.
Efficient : The initilazation code for a servlet is executed only once, when the servlet is executed for the first time.
Robest : provide all the powerfull features of JAVA, such as Exception handling and garbage collection.
Portable: This enables easy portability across Web Servers.
Persistance : Increase the performance of the system by executing features data access.

4. What is the difference between JSP and SERVLETS
Servlets : servlet tieup files to independitently handle the static presentation logic and dynamic business logic , due to this a changes made to any file requires recompilation of the servlet.
- The servlet is Pre-Compile.

JSP : Facilities segregation of work profiles to Web-Developer and Web-Designer , Automatically incorporates changes made to any file (PL & BL) , no need to recompile.
Web-Developer write the code for Bussiness logic whereas Web-Designer designs the layout for the WebPage by HTML & JSP.
- The JSP is Post-Compile.

5. What are the advantages using servlets than using CGI?
Servlets provide a way to generate dynamic documents that is both easier to write and faster to run. It is efficient, convenient, powerful, portable, secure and inexpensive. Servlets also address the problem of doing server-side programming with platform-specific APIs. They are developed with Java Servlet API, a standard Java extension.

6. What is the difference between servlets and applets?
Servlets are to servers. Applets are to browsers. Unlike applets, however, servlets have no graphical user interface.

7. What is the difference between GenericServlet and HttpServlet?
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.
GenericServlet belongs to javax.servlet package
GenericServlet is an abstract class which extends Object and implements Servlet, ServletConfig and java.io.Serializable interfaces.
The direct subclass to GenericServlet is HttpServlet.It is a protocol-independent servlet

8. What are the differences between GET and POST service methods?
Get Method : Uses Query String to send additional information to the server.
-Query String is displayed on the client Browser.
Query String : The additional sequence of characters that are appended to the URL ia called Query String. The length of the Query string is limited to 255 characters.
-The amount of information you can send back using a GET is restricted as URLs can only be 1024 characters.

POST Method : The Post Method sends the Data as packets through a separate socket connection. The complete transaction is invisible to the client. The post method is slower compared to the Get method because Data is sent to the server as separate packates.
--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!

9. What is the servlet life cycle?

In Servlet life cycles are,
init(),services(),destory().
Init( ) : Is called by the Servlet container after the servlet has ben Instantiated.
--Contains all information code for servlet and is invoked when the servlet is first loaded.
-The init( ) does not require any argument , returns a void and throws Servlet Exception.
-If init() executed at the time of servlet class loading.And init() executed only for first user.
-You can Override this method to write initialization code that needs to run only once, such as loading a driver , initializing values and soon, Inother case you can leave normally blank.
Public void init(ServletConfig Config) throws ServletException

Service( ) : is called by the Servlet container after the init method to allow the servlet to respond to a request.
-Receives the request from the client and identifies the type of request and deligates them to doGet( ) or doPost( ) for processing.
Public void service(ServletRequest request,ServletResponce response) throws ServletException, IOException

Destroy( ) : The Servlet Container calls the destroy( ) before removing a Servlet Instance from Sevice.
-Excutes only once when the Servlet is removed from Server.
Public void destroy( )

If services() are both for get and post methods.
-So if u want to use post method in html page,we use doPost() or services() in servlet class.
-if want to use get methods in html page,we can use doGet() or services() in servlet calss.
-Finally destory() is used to free the object.

10. What is the difference between ServletContext and ServletConfig?
Both are interfaces.
Servlet Config():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.
A ServletConfig object passes configuration information from the server to a servlet. ServletConfig also includes ServletContext object.
getParameter( ) , getServletContext( ) , getServletConfig( ), GetServletName( )

Servlet Context(): 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.
ServletContext defines methods that allow a servlet to interact with the host server. This includes reading server-specific attributes, finding information about particular files located on the server, and writing to the server log files. I f there are several virtual servers running, each one may return a different ServletContext.
getMIMEType( ) , getResourse( ), getContext( ),getServerInfo( ),getServletContetName( )

11. Can I invoke a JSP error page from a servlet?
Yes, you 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.

12. 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

13. Can I just abort processing a JSP?
Yes.Because your JSP is just a servlet method,you can just put (whereever necessary) a < % return; %>

14. What is a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?
Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not scale well. If you anticipate your users to increase in the future, you may be better off implementing explicit synchronization for your shared data. The key however, is to effectively minimize the amount of code that is synchronzied so that you 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 you did add more memory and increased the size of the instance pool.

15. If you want a servlet to take the same action for both GET and POST request, what should you do?
Simply have doGet call doPost, or vice versa.

16. Which code line must be set before any of the lines that use the PrintWriter?
setContentType() method must be set before transmitting the actual document.

17. How HTTP Servlet handles client requests?
An HTTP Servlet handles client requests through its service method. The service method supports standard HTTP client requests by dispatching each request to a method designed to handle that request.

18. What is the Servlet Interface?
The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or, more commonly, by extending a class that implements it such as HttpServlet.
Servlets-->Generic Servlet-->HttpServlet-->MyServlet.
The Servlet interface declares, but does not implement, methods that manage the servlet and its communications with clients. Servlet writers provide some or all of these methods when developing a servlet.

19. When a servlet accepts a call from a client, it receives two objects. What are they?
ServeltRequest: which encapsulates the communication from the client to the server.
ServletResponse: which encapsulates the communication from the servlet back to the
Client.
ServletRequest and ServletResponse are interfaces defined by the javax.servlet package.

20. What information that the ServletRequest interface allows the servlet access to?
Information such as the names of the parameters passed in by the client, the protocol (scheme) being used by the client, and the names of the remote host that made the request and the server that received it. The input stream, ServletInputStream.Servlets use the input stream to get data
from clients that use application protocols such as the HTTP POST and PUT methods.

21. What information that the ServletResponse interface gives the servlet methods for replying to the client?
It Allows the servlet to set the content length and MIME type of the reply. Provides an output stream, ServletOutputStream and a Writer through which the servlet can send the reply data.

22. Difference between single thread and multi thread model servlet
A servlet that implements SingleThreadModel means that for every request, a single servlet instance is created. This is not a very scalable solution as most web servers handle multitudes of requests. A multi-threaded servlet means that one servlet is capable of handling many requests which is the way most servlets should be implemented.
a. A single thread model for servlets is generally used to protect sensitive data ( bank account operations ).
b. Single thread model means instance of the servlet gets created for each request recieved. Its not thread safe whereas in multi threaded only single instance of the servlet exists for what ever # of requests recieved. Its thread safe and is taken care by the servlet container.
c. A servlet that implements SingleThreadModel means that for every request, a single servlet instance is created. This is not a very scalable solution as most web servers handle multitudes of requests. A multi-threaded servlet means that one servlet is capable of handling many requests which is the way most servlets should be implemented.

A single thread model for servlets is generally used to protect sensitive data ( bank account operations ).

23. What is servlet context and what it takes actually as parameters?
Servlet context is an object which is created as soon as the Servlet gets initialized.Servlet context object is contained in Servlet Config. With the context object u can get access to specific
resource (like file) in the server and pass it as a URL to be displayed as a next screen with the help of RequestDispatcher
eg :-
ServletContext app = getServletContext();
RequestDispatcher disp;
if(b==true)
disp = app.getRequestDispatcher
("jsp/login/updatepassword.jsp");
else
disp = app.getRequestDispatcher
("jsp/login/error.jsp");
this code will take user to the screen depending upon the value of b.
in ServletContext u can also get or set some variables which u would
like to retreive in next screen.
eg
context.setAttribute("supportAddress", "temp@temp.com");
Better yet, you could use the web.xml context-param element to
designate the address, then read it with the getInitParameter method
of ServletContext.

24. Can we call destroy() method on servlets from service method?
destroy() is a servlet life-cycle method called by servlet container to kill the instance of the servlet. "Yes". You can call destroy() from within the service(). It will do whatever logic you have in destroy() (cleanup, remove attributes, etc.) but it won't "unload" the servlet instance itself. That can only be done by the container

25. What is the use of ServletConfig and ServletContext..?
An interface that describes the configuration parameters for a servlet. This is passed to the servlet when the web server calls its init() method. Note that the servlet should save the reference to the ServletConfig object, and define a getServletConfig() method to return it when asked. This interface defines how to get the initialization parameters for the servlet and the context under which the servlet is running.
An interface that describes how a servlet can get information about the server in which it is running. It can be retrieved via the getServletContext() method of the ServletConfig object.

26. What is difference between forward() and sendRedirect().. ? Which one is faster then other and which works on server?
Forward( ) : javax.Servlet.RequestDispatcher interface.
-RequestDispatcher.forward( ) works on the Server.
-The forward( ) works inside the WebContainer.
-The forward( ) restricts you to redirect only to a resource in the same web-Application.
-After executing the forward( ), the control will return back to the same method from where the forward method was called.
-the forward( ) will redirect in the application server itself, it does’n come back to the client.
- The forward( ) is faster than Sendredirect( ) .
To use the forward( ) of the requestDispatcher interface, the first thing to do is to obtain RequestDispatcher Object. The Servlet technology provides in three ways.
1. By using the getRequestDispatcher( ) of the javax.Servlet.ServletContext interface , passing a String containing the path of the other resources, path is relative to the root of the ServletContext.

RequestDispatcher rd=request.getRequestDispatcher(“secondServlet”);
Rd.forward(request, response);

2. getRequestDispatcher( ) of the javax.Servlet.Request interface , the path is relative to current HtpRequest.
RequestDispatcher rd=getServletContext( ).getRequestDispatcher(“servlet/secondServlet”);
Rd.forward(request, response);

3. By using the getNameDispatcher( ) of the javax.Servlet.ServletContext interface.
RequestDispatcher rd=getServletContext( ).getNameDispatcher(“secondServlet”);
Rd.forward(request, response);

Sendredirect( ) : javax.Servlet.Http.HttpServletResponce interface
-RequestDispatcher.SendRedirect( ) works on the browser.
-The SendRedirect( ) allows you to redirect trip to the Client.
-The SendRedirect( ) allows you to redirect to any URL.
-After executing the SendRedirect( ) the control will not return back to same method.
-The Client receives the Http response code 302 indicating that temporarly the client is being redirected to the specified location , if the specified location is relative , this method converts it into an absolute URL before redirecting.

-The SendRedirect( ) will come to the Client and go back,.. ie URL appending will happen.
Response. SendRedirect( “absolute path”);
Absolutepath – other than application , relative path - same application.

When you 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 completely with in the web container. When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completely new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.

27. do we have a constructor in servlet ? can we explictly provide a constructor in servlet programme as in java program ?
We can have a constructor in servlet .

Session : A session is a group of activities that are performed by a user while accesing a particular website.
Session Tracking :The process of keeping track of settings across session is called session tracking.
Hidden Form Fields : Used to keep track of users by placing hidden fields in the form.
-The values that have been entered in these fields are sent to the server when the user submits the Form.
URL-rewriting : this is a technique by which the URL is modified to include the session ID of a particular user and is sent back to the Client.
-The session Id is used by the client for subsequent transactions with the server.
Cookies : Cookies are small text files that are used by a webserver to keep track the Users.
A cookie is created by the server and send back to the client , the value is in the form of Key-value pairs. Aclient can accept 20 cookies per host and the size of each cookie can be maximum of 4 bytes each.
HttpSession : Every user who logs on to the website is autometacally associated with an HttpSession Object.
-The Servlet can use this Object to store information about the users Session.
-HttpSession Object enables the user to maintain two types of Data.
ie State and Application.

28. How to communicate between two servlets?
Two ways:
a. Forward or redirect from one Servlet to another.
b. Load the Servlet from ServletContext and access methods.

29. How to get one Servlet's Context Information in another Servlet?
Access or load the Servlet from the Servlet Context and access the Context Information

30. 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();
}
} }

Friday, August 22, 2008

==> Exception Handling in Java

Exception can be generated by Java-runtime system or they can be manually generated by code.

Error-Handling becomes a necessary while developing an application to account for exceptional situations that may occur during the program execution, such as
Run out of memory,Resource allocation Error,Inability to find a file and etc.If the Resource file is not present in the disk, you can use the Exception handling mechanisim to handle such abrupt termination of program.

Exception class is used for the exceptional conditions that are trapped by the program.An exception is an abnormal condition or error that occur during the execution of the program.

Error the error class defines the conditions that do not occur under normal conditions.

Eg: Run out of memory, Stack overflow error.

Two types of exceptions:

1. Checked Exceptions : must be declare in the method declaration or caught in a catch block. Checked exception must be handled at Compile Time. Environmental error that cannot necessarly be detected by Testing, Eg: disk full, brocken Socket, Database unavailable etc.

2. Un-checked Exceptions: Run-time Exceptions and Error, does’t have to be declare.(but can be caught).

Run-time Exceptions : programming errors that should be detectd in Testing ,
Arithmetic, Null pointer, ArrayIndexOutofBounds, ArrayStore, FilenotFound, NumberFormate, IO, OutofMemory.

Errors: Virtual mechine error – class not found , out of memory, no such method , illegal access to private field , etc.

Java Exception handling can be managed by five keywords:

Try : The try block governs the statements that are enclosed within it and defines the scope of exception handler associated with it. Try block follows catch or finally or both.

Catch: This is a default exception handler. since the exception class is the base class for all the exception class, this handler id capable of catching any type of exception.
The catch statement takes an Object of exception class as a parameter, if an exception is thrown the statement in the catch block is executed. The catch block is restricted to the statements in the proceeding try block only.

Try {
// statements that may cause exception
}
catch(Exception obj)
{

}


Finally : when an exception is raised, the statement in the try block is ignored, some times it is necessary to process certain statements irrespective of wheather an exception is raised or not, the finally block is used for this purpose.

Throw : The throw class is used to call exception explicitly. You may want to throw an exception when the user enters a wrong login ID and pass word, you can use throw statement to do so.

The throw statement takes an single argument, which is an Object of exception class.


Throw [throwable Instance]


If the Object does not belong to a valid exception class the compiler gives error.

Throws :The throws statement species the list of exception that has thrown by a method.
If a method is capable of raising an exception that is does not handle, it must specify the exception has to be handle by the calling method, this is done by using the throw statement.

[access specifier] [access modifier] {return type} {method name} {arg-list} [exception-list]


Eg: public void accept password( ) throws illegalException
{
System.out.println(“Intruder”);
Throw new illegalAccesException;
}

==> Interface vs Abstract Class

Interfaces

Interfaces can be used to implement the Inheritance relationship between the non-related classes that do not belongs to the same hierarchy, i.e. any Class and any where in hierarchy. Using Interface, you can specify what a class must do but not how it does.

-> A class can implement more than one Interface.

-> An Interface can extend one or more interfaces, by using the keyword extends.

-> All the data members in the interface are public, static and Final by default.

-> An Interface method can have only Public, default and Abstract modifiers.

-> An Interface is loaded in memory only when it is needed for the first time.

-> A Class, which implements an Interface, needs to provide the implementation of all the methods in that Interface.

-> If the Implementation for all the methods declared in the Interface are not provided , the class itself has to declare abstract, other wise the Class will not compile.

-> If a class Implements two interface and both the Intfs have identical method declaration, it is totally valid.

-> If a class implements tow interfaces both have identical method name and argument list, but different return types, the code will not compile.

-> An Interface can’t be instantiated. Intf Are designed to support dynamic method resolution at run time.

-> An interface can not be native, static, synchronize, final, protected or private.

-> The Interface fields can’t be Private or Protected.

-> A Transient variables and Volatile variables can not be members of Interface.

-> The extends keyword should not used after the Implements keyword, the Extends must always come before the Implements keyword.

-> A top level Interface can not be declared as static or final.

-> If an Interface species an exception list for a method, then the class implementing the interface need not declare the method with the exception list.

-> If an Interface can’t specify an exception list for a method, the class can’t throw an exception.

-> If an Interface does not specify the exception list for a method, he class can not throw any exception list.

Abstract Class

Abstract classes can be used to implement the inheritance relationship between the classes that belongs same hierarchy.Abstract Class means - Which has more than one abstract method which doesn’t have method body but at least one of its methods need to be implemented in derived Class.

-> Classes and methods can be declared as abstract.

-> Abstract class can extend only one Class.

-> If a Class is declared as abstract , no instance of that class can be created.

-> If a method is declared as abstract, the sub class gives the implementation of that class.

-> Even if a single method is declared as abstract in a Class , the class itself can be declared as abstract.

-> Abstract class have at least one abstract method and others may be concrete.

-> In abstract Class the keyword abstract must be used for method.

-> Abstract classes have sub classes.

-> Combination of modifiers Final and Abstract is illegal in java.

Difference Between Interfaces And Abstract class

-> All the methods declared in the Interface are Abstract, where as abstract class must have atleast one abstract method and others may be concrete.

-> In abstract class keyword abstract must be used for method, where as in Interface we need not use the keyword for methods.

-> Abstract class must have Sub class, where as Interface can’t have sub classes.

-> An abstract class can extend only one class, where as an Interface can extend more than one.

==> Microsoft .NET vs Sun J2EE



==> Know about "Ant"

Ant is an open source build tool (a program for putting together all the pieces of a program) from the Apache Software Foundation. The utility is the most commonly used build tool for programs written in Java. Although similar to the GNU make utility that it replaces, Ant is said to be more portable and simpler to use. Unlike many other build tools, Ant is independent of both platform and development environment.

Make (the most common build tool) and most alternatives are based on a particular shell or command interface, and for that reason are limited to the type of operating system that uses that shell. Ant uses Java classes rather than shell-based commands. Developers use XML to describe the modules in their program build, what those modules should do, and any dependencies between them and other parts of the program. Ant determines the parts of the program that have been changed since the last compilation, as well as any parts of the program that are dependent on those components, and then compiles only those parts that require it, in the proper order.

Ant is part of Apache's Jakarta project. Software consultant James Duncan Davidson created Ant in 1998. Davidson was working on a cross-platform program build and running into problems using available build tools, so he created his own. Davidson named the tool "Ant" because it is a little thing that can build big things.


Ant documentation can be found at

http://ant.apache.org/manual/index.html

A good tutorial on Ant can be found at

http://www.exubero.com/ant/antintro-s5.html

==> Installing Rational Application Developer 7.0



This video will give you an overall idea on the installation of Rational Application Developer 7.0.

==> What is Hibernate

Hibernate is a free, open source Java package that makes it easy to work with most of the available relational databases.Hibernate makes it seem as if the database contains simple Java objects, without having to worry about how to retrieve the data from (or save it back into) database tables.

Most of the applications need to interact with database.Data will be stored in no of interconnected objects when the application is running. But all those objects will be vanished when the program ends.So there is a need to store that data before those objects get vanished. Moreover, the task of loading the huge amounts of data from the database into the interconnected objects is tedious and error prone, and represents major portion effort involved. So many programmers worked on automating this process to reduce the effort of application developers. Finally they are succeded in developing some object / relational mapping tools.

Hibernate is one among the object / relational mapping tools developed which gives so much of flexibility to the application developers.

Hibernate gives the pesistence ability to the objects.All that is required to use Hibernate in the application is creating an XML mapping document which says what classes need to be stored in the database and how the class relate to the tables and columns in the database. That can do the magic of fetching the data into objects and storing the data into the database.

Hibernate has an inbuilt API to query the objects represented by the database. To update the database, simply modify those objects and ask hibernate to save the changes. To create a new reacords in database, simply create an object and ask hibernate to save. Hibernate saves back the data into the database.

The Hibernate API is simple to learn and interacts quite naturally with the flow of the program. Hibernate is database independent. When hibernate is being used in the application, the application can be interacted with any kind of database.

The HTML version of Hibernate tutorial can be found at

http://www.hibernate.org/hib_docs/v3/reference/en/html/

The PDF version of Hibernate tutorial can be downloaded from

http://www.hibernate.org/hib_docs/v3/reference/en/pdf/hibernate_reference.pdf

Monday, August 4, 2008

==> Implicit objects in JSP

Implicit objects in JSP :

1. request : The request object represents httprequest that are trigged by service( ) invocation.

2. response:The response object represents the servers response to request.

3. pageContext : The page context specifies the single entry point to many of the page attributes and is the convient place to put shared data.

4. session : the session object represents the session created by the current user.

5. application : the application object represents servlet context , obtained from servlet configaration.

6. out : the out object represents to write the out put stream .

7. Config :the config object represents the servlet config interface from this page,and has scope attribute.

8. page : The object is th eInstance of page implementation servlet class that are processing the current request.

9. exception : These are used for different purposes and actually u no need to create these objects in JSP. JSP container will create these objects automatically.

One can directly use these objects in JSP.

==> Comparision of JDBC Drivers

Types Of Drivers :

1. Type-1 (JDBC ODBC-Bridge Driver)
2. Type-2 (Java-Native API Driver / Native API Partly JAVA Driver / Thick Driver)
3. Type-3 (Java Net Protocol Driver / Intermediate DataBase Access Server)
4. Type-4 (Java Native Protocol driver / Pure JAVA Driver / Thin driver)

Type-1 : JDBC-ODBC Bridge Driver :

Since ODBC is written in C-language using pointers, so JAVA does’t support pointers, a java program can’t communate directly with the DataBase. The JDBC-ODBC bridge drivertransulates JDBC API calls to ODBC API calls.

Advantages :

1) Simple to use because ODBC drivers comes with DB installation/Microsoft front/back office product installation
2) JDBC ODBC Drivers comes with JDK software

Disadvantages :

1) More number of layers between the application and DB. And more number of API conversions leads to the downfall of the performance.
2) Slower than type-2 driver.

Where to use :

This type of drivers are generaly used at the development time to test your application’s.
Because of the disadvantages listed above it is not used at production time. But if we are not available with any other type of driver implementations for a DB then we are forced to use this type of driver (for example Microsoft Access)

Type-2 : Native API Partly JAVA Driver / Thick Driver :

JDBC Database calls are translated into Vendor-specific API calls. The database will process the request and send the results back through API to JDBC Driver – this will translate the results to the JDBC standard and return them to the Java application. The Vendor specific language API must be installed on every client that runs the JAVA application.

Advantages :

1) Faster than the other types of drivers due to native library participation in socket programing.

Disadvantage :

1) DB spcifiic native client library has to be installed in the client machine.
2) Preferablly work in local network environment because network service name must be configured in client system

Where to use :

This type of drivers are suitable to be used in server side applications.
Not recommended to use with the applications using two tire model (i.e. client and database layer’s) because in this type of model client used to interact with DB using the driver and in such a situation the client system sould have the DB native library.

Type-3 Intermediate DataBase Access Server :

Type-3 Driver uses an Intermediate(middleware) database driver that has the ability to connect multiple JAVA clients to multiple database servers. Client connect to the Databse server via an Intermediate server component (such as listener) that acts as a gateway for multple database servers. Bea weblogic includes Type-3 Driver.

Advantages :

1) It allows the flexibility on the architecture of the application.
2) In absence of DB vendor supplied driver we can use this driver
3) Suitable for Applet clients to connect DB, because it uses Java libraries for communication between client and server.

Disadvantages :

1) From client to server communication this driver uses Java libraries, but from server to DB connectivity this driver uses native libraries, hence number of API conversion and layer of interactions increases to perform operations that leads to performance deficit.
2) Third party vendor dependent and this driver may not provide suitable driver for all DBs

Where to use :

Suitable for Applets when connecting to databases

Type-4 Pure JAVA Driver / Thin driver :

Type-4 Driver translates JDBC-API calls to direct network calls using vendor specific networking protocols by making direct server connections with the database.

Advantage :

1) Type-4 driver are simple to deploy since there is No client native libraries required to be installed in client machine
2) Comes with most of the Databases

Disadvantages :

1) Slower in execution compared with other JDBC Driver due to Java libraries are used in socket communication with the DB

Where to use :

This type of drivers are sutable to be used with server side applications, client side application and Java Applets also.

==> Access Specifiers & Access Modifiers in Java

Access Specifiers :-

Public : The public variables and methods can be access any where and any package.
Protected : The protected variables and methods can be access same Class, same Package & sub class.
Private : The private variables and methods can be access in same class only.

Access Modifiers :-

Static :

Variable-Static int b;
Method- static void meth(int x)

1) When a member is declared as Static, it can be accessed before any objects of its class are created and without reference to any object. Eg : main(),it must call before any object exit.
2) Static can be applied to Inner classes, Variables and Methods.
3) Local variables can’t be declared as static.
4) A static method can access only static Variables. and they can’t refer to this or super
in any way.
5) Static methods can’t be abstract.
6) A static method may be called without creating any instance of the class.
7) Only one instance of static variable will exit any amount of class instances.

Final :

1) All the Variables, methods and classes can be declared as Final.
2) Classes declared as final class can’t be sub classed.
3) Method ‘s declared as final can’t be over ridden.
4) If a Variable is declared as final, the value contained in the Variable can’t be changed.
5) Static final variable must be assigned in to a value in static initialized block.

Transient :

1) Transient can be applied only to class level variables.
2) Local variables can’t be declared as transient.
3) During serialization, Object’s transient variables are not serialized.
4) Transient variables may not be final or static. But the complies allows the declaration
and no compile time error is generated.

Volatile :

1) Volatile applies to only variables.
2) Volatile can applied to static variables.
3) Volatile can not be applied to final variables.
4) Transient and volatile can not come together.
5) Volatile is used in multi-processor environments.

Native :
1) Native applies to only to methods.
2) Native can be applied to static methods also.
3) Native methods can not be abstract.
4) Native methods can throw exceptions.
5) Native method is like an abstract method. The implementation of the abstract class and native method exist some where else, other than the class in which the method is declared.

Synchronized :
1) Synchronized keyword can be applied to methods or parts of the methods only.
2) Synchronize keyword is used to control the access to critical code in multi-threaded programming.

Usage of access specifier and access modifiers:

Class - Public, Abstract, Final
Inner Class - Public, Protected, Private, Final, Static,
Anonymous - Public, Protected, Private, Static
Variable - Public, Protected, Private, Final, Static, Transient, Volatile, Native
Method - Public, Protected, Private, Final, Abstract, Static, Native, Synchronized
Constructor - Public, Protected, Private
Free-floating code block - Static, Synchronized

==> A Small Tutorial on Struts

Apache Struts is an open-source web application framework for developing Java EE web applications. It uses and extends the Java Servlet API to encourage developers to adopt a model-view-controller (MVC) architecture. It was originally created by Craig McClanahan and donated to the Apache Foundation in May, 2000. Formerly located under the Apache Jakarta Project and known as Jakarta Struts, it became a top level Apache project in 2005.

I made simple power point presentation to explain the fundamentals about Struts. Click on the link below to download Struts.

==> A Good application in Struts to Start with

I developed an application in Struts to give the beginners an idea how the Struts works.
Its a simple and good application to start with.

Download the application from the following link

Employee Management System in Struts

Follow the steps below to deploy the application

1) After downloading the Zip file, unzip it and copy the folder to Tomcat Webapps folder.
2) Create a data source name "emp" for the MS Access Database present inside in the folder.

Now the application is ready. You can run the application.

The Username to be used to login is "sanjeev" and the password is also "sanjeev".

Saturday, July 26, 2008

==> Coding Standards for Java Web Application

  • All the variables, methods & classes should have the meaning full names.

  • Indentation should be strictly followed.

  • All the variables, methods & classes should have the appropriate java comments.

  • The code should not contain any sysouts instead appropriate logger statements should be used.

  • All the variables should be declared at the top (beginning of method) and instantiated wherever required.

  • The code should not contain any hard coding of string or number.

  • While designing the JSP Page instead of writing the styles every where, all the styles should be fetched from the common CSS file and used.

  • Unnecessary code should be avoided by using proper java constructs.

  • The labels in the JSP Page should be fetched from property file.

  • The no of characters in a line in code should not exceed 80.

Saturday, April 12, 2008

==> Introduction to AJAX

AJAX - Asynchronous JavaScript and XML

AJAX is not a new programming language, but a technique for creating better, faster, and more interactive web applications. With AJAX, your JavaScript can communicate directly with the server, using the JavaScript XMLHttpRequest object. With this object, your JavaScript can trade data with a web server, without reloading the page. AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages. The AJAX technique makes Internet applications smaller, faster and more user-friendly.

*** AJAX is a browser technology independent of web server software.

AJAX is based on the following web standards:
1) JavaScript
2) XML
3) HTML
4) CSS

The web standards used in AJAX are well defined, and supported by all major browsers. AJAX applications are browser and platform independent. AJAX is About Better Internet Applications
Web applications have many benefits over desktop applications; they can reach a larger audience, they are easier to install and support, and easier to develop. However, Internet applications are not always as "rich" and user-friendly as traditional desktop applications.
With AJAX, Internet applications can be made richer and more user-friendly.

In traditional JavaScript coding, if you want to get any information from a database or a file on the server, or send user information to a server, you will have to make an HTML form and GET or POST data to the server. The user will have to click the "Submit" button to send/get the information, wait for the server to respond, then a new page will load with the results.
Because the server returns a new page each time the user submits input, traditional web applications can run slowly and tend to be less user-friendly.

With AJAX, your JavaScript communicates directly with the server, through the JavaScript XMLHttpRequest object. With an HTTP request, a web page can make a request to, and get a response from a web server - without reloading the page. The user will stay on the same page, and he or she will not notice that scripts request pages, or send data to a server in the background.

A good AJAX material can be found at

http://www.w3schools.com/Ajax/default.asp

==> Introduction to Java

Java is a high-level language, like C, FORTRAN, Smalltalk, Perl, and many others. Java can be used to write computer applications that do operations on numbers, process words, play games, store data and do many other operations that a computer software can do.
Compared to other programming languages, Java is most similar to C. Java shares much of C's syntax. Knowing how to program C++ will certainly help you to learn Java more quickly, but you don't need to know C or C++ to learn Java.
Features of Java
1) Simple:-
Java was designed to make it much easier to write bug free code. The most important part of helping programmers write bug-free code is keeping the language simple.
Java has the rich feature set to help the programmers in writing the code. Despite its simplicity Java has considerably more functionality than C, primarily because of the large class library.
About half of the bugs in C and C++ programs are related to memory allocation and deallocation. The runtime environment provides automatic memory allocation and garbage collection so there's less for the programmer to think about.
Because Java is simple, it is easy to read and write. There aren't a lot of special cases or tricks that will confuse beginners.
2) Object-Oriented:-
Java is a pure Object Oriented language. In object-oriented programs data is represented by objects. Objects have two sections, fields (instance variables) and methods. Fields tell you what an object is. Methods tell you what an object does. These fields and methods are closely tied to the object's real world characteristics and behavior.
Object oriented programming is alleged to have a number of advantages including:
Simpler, easier to read programs
More efficient reuse of code
Faster time to market
More robust, error-free code

3) Platform Independent:-
A program written in any programming language on one platform can be moved on another platform and can be compiled and executed. But it’s very difficult to run the program compiled on another platform.
But java makes it possible by introducing Byte Code. Once you compile a java program, the java compiler gives you a class file which is purely in byte code. The byte code can be executed on Java Virtual Machine installed on any platform.
So java gives the flexibility to the programmers to write platform independent programs.
4) Secured:-
To make the programs more secured, Java avoided so many features of C and C++ to include. Most notably there are no pointers in Java. Java programs cannot access arbitrary addresses in memory. All memory access is handled behind the scenes by the trusted Java Runtime Environment. Furthermore Java has strong typing. Variables must be declared, and variables do not change types when you aren't looking. Casts are strictly limited to casts between types that make sense. Thus you can cast an int to a long or a byte to a short but not a long to a boolean or an int to a String.
5) Exception Handling:-
Java implements a robust exception handling mechanism to help the programmers to deal with both expected and unexpected errors.
6) Robust & Scalable:-
Java byte codes can be compiled on the fly in speed using a "just-in-time compiler." Several companies are also working on native-machine-architecture compilers for Java. These will produce executable code that does not require a separate interpreter.
It is certainly possible to write large programs in Java. The HotJava browser, the Eclipse integrated development environment, the LimeWire file sharing application, the jEdit text editor, the JBoss application server, the Tomcat servlet container, the Xerces XML parser, the Xalan XSLT processor, and the javac compiler are large programs that are written entirely in Java.
7) Multi-Threaded:-
Java is inherently multi-threaded. A single Java program can have many different threads executing independently and continuously. It also helps to contribute to Java's robustness.
8) Garbage Collection:-
You do not need to explicitly allocate or deallocate memory in Java. Memory is allocated as needed, both on the stack and the heap, and reclaimed by the garbage collector when it is no longer needed. There's no malloc(), free(), or destructor methods.
There are constructors and these do allocate memory on the heap, but this is transparent to the programmer.
The exact algorithm used for garbage collection varies from one virtual machine to the next. The most common approach in modern JVMs is generational garbage collection for short-lived objects, followed by mark and sweep for longer lived objects. I have never encountered a Java VM that used reference counting.