java4all@1986 java. Powered by Blogger.

>> Wednesday, June 15, 2011

Q).What are the uses of ServletRequest Interface?
A).ServletRequest defines an object to provide client request information to a servlet.
The servlet container creates a ServletRequest object and passes it as an argument to the servlet's
service method.

A ServletRequest object provides data including parameter name and values, attributes, and an input stream. Interfaces that extend ServletRequest can provide additional protocol-specific data (for example, HTTP data is provided by HttpServletRequest.

Packages that use ServletRequest :
  * javax.servlet      
  * javax.servlet.http      
  * javax.servlet.jsp

Q).How can a servlet Refresh automatically?
A).We can Refresh Servlet Page by two ways : one through client side and another through Server Push.

Client Side Refresh :
< META HTTP-EQUIV="Refresh" CONTENT="5; URL=/servlet/MyServlet/">


Server Side Refresh :
response.setHeader("Refresh",5);

This will update the browser after every 5 seconds.

Q).How does a servlet handles multiple requests at a time?
A).Servlets are under the control of web container. When a request comes for the servlet,
the web container find out the correct servelt based on the URL, and create a separeate thread for each request.
In this way each request is processed by the different thread simultaneously.

Q).What is difference between Context Init parameter and servlet init parameter?
A).Context init parameter is accessible through out the web application and declared outside the <servlet>...</servlet>
element tag in the deployment descriptor(DD) . Servlet init parameters are declared inside the <servlet>...</servlet>
element and only accessible only to the that specific servlet. You can access the context init parameters using the getServletContext() method and Servlet init parameters using the getServletConfig() method.

Declaring the Servlet init parameter in DD :

<servlet> 
   <servlet-name>My Page</servlet-name>
   <sevlet-class>/mypage</servlet-class> 
   <init-param> 
      <param-name>name</param-name>    //it will be applicable to only one single servlet
      <param-value>pream</param-value) </init-param>
</servlet>

Declaring the Context init parameter in DD :

<context-param> 
<param-name>webmaster</param-name> 
<param-value>apache</param-value>   //it will be applicable to all servlets in an web-application
</context-param>

Q).What meant bt URL encoding and URL decoding?
A).Some characters are not valid in URLs like & can't be placed in a URL query string without changing the meaning of that query string.

These problems can be be fixed by 'escaping' them. This process involves scanning the text for those characters, and replacing them
with a special character-code that browsers can interpret as the correct symbol, without actually using that symbol in your URL.

For example, the escaped character code for '=' is '%3d'.

Q).When a session object is added or removed to session which event will be notified?
A).When an object is added or removed from a session, the container checks the interfaces implemented by the object.
If the object implements the HttpSessionBindingListener, the container calls the matching notification method.
If session is added then sessionCreated() method, and if session is removed then sessionDestroyed() method will be callled automatically by the web container.


Read more...

Q).What mechanisms are used by servlet Container to maintain the session information?
A).The mechanisms used by a Servlet Container to maintain session information :

a) Cookies

b) URL rewriting

c) Hidden form fields

d) HTTP Sessions.

Q).What are the uses of ServletResponse Interface?
A). ServletResponse interface defines an object to assist a servlet in sending a response to the client.
The servlet container creates a ServletResponse object and passes it as an argument to the servlet's
service method.
To send binary data in a MIME body response, use the ServletOutputStream returned by getOutputStream().
To send character data, use the PrintWriter object returned by getWriter(). To mix binary and text data,
for example, to create a multipart response, use a ServletOutputStream and manage the character sections manually.

Packages that use ServletResponse :
  * javax.servlet      
  * javax.servlet.http      
  * javax.servlet.jsp.

Q).What is the difference between a session and cookie?
A).Differences between a session and a cookie :
  * A cookie is a special piece of data with a bit of associated metadata that an HTTP server includes in an HTTP response.
  A session is a series of related HTTP requests and responses that together constitute a single conversation between a client and server.
  * Cookies are stored at the client side whereas session exists at the server side.
  * A cookie can keep information in the user's browser until deleted, whereas you close your browser you also lose the session.
  * Cookies are often used to store a session id, binding the session to the user.
  * There is no way to disable sessions from the client browser but cookies.

Q).What is the  preintialization of a Servlet?
A).Servlets are loaded and initialized at the first request come to the server and stay loaded until server shuts down.
However there is another way you can initialized your servlet before any request come for that servlet by saying <load-on-startup>1</load-on-startup> in the deployment descriptor.
You can specify <load-on-startup>1</load-on-startup> in between the <servlet></servlet> tag.

Q).What is the difference between ServletConfig and ServletContext?
A).ServletContext and ServletConfig are declared in the deployment descriptor.
ServletConfig is one per servlet and can be accessed only within that specific servlet.
ServletContext is one per web application and accessible to all the servlet in the web application.

Read more...

Q).What is the maximum amount of information is saved in Session Object?
A).There is no limit for amount of information that can be save into the session object.
It depends upon the RAM available on the server machine. The only limit is the Session ID length,
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.

Q).What is the web container?
A).The Web container provides the runtime environment through components that provide naming context and life cycle management,security and concurrency control. A web container provides the same services as a JSP container as well as a federated view of the Java EE.Apache Tomcat is a web container and an implementation of the Java Servlet and JavaServer Pages technologies.

Q.)Why should we go for inter Servlet Communication?
A).Due ot the following reason need inter servlet communication :

  * Two servlet want to communicate to complete the shopping cart.
  * One servlet handles the client request and forward it to another servlet to do some calculation or add some information to complete the view.
  * One servlet want to reuse the some methods of another servlet.

Q).How HttpServlets Handle the Client  Request?
A).HTTP Servlet is an abstract class that must be subclassed to create an HTTP servlet suitable for a Web site. A subclass of HttpServlet must override at least one method, usually one of these:
  * doDelete(HttpServletRequest req, HttpServletResponse resp) :  Called by the server (via the service method) to allow a servlet to handle a DELETE request.
  * doGet(HttpServletRequest req, HttpServletResponse resp) :  Called by the server (via the service method) to allow a servlet to handle a GET request.
  * doOptions(HttpServletRequest req, HttpServletResponse resp) :  Called by the server (via the service method) to allow a servlet to handle a OPTIONS request.
  * doPost(HttpServletRequest req, HttpServletResponse resp) :  Called by the server (via the service method) to allow a servlet to handle a POST request.
  * doPut(HttpServletRequest req, HttpServletResponse resp) :  Called by the server (via the service method) to allow a servlet to handle a PUT request.
  * doTrace(HttpServletRequest req, HttpServletResponse resp) :  Called by the server (via the service method) to allow a servlet to handle a TRACE request. etc.
 

Read more...

Q).How can we will implement singleton pattern in servlets?
A).Singleton is a useful Design Pattern for allowing only one instance of your class.you can implement singleton pattern in servlets by using using Servlet init() and <load-on-startup> in the deployment descriptor.

Q.)What is servlet Exception?
A.)ServletException is a subclass of the Exception. It defines a general exception a servlet can throw when it encounters difficulty.
ServletException class define only one method getRootCause() that returns the exception that caused this servlet exception.
It inherit the other methods like fillInStackTrace, getLocalizedMessage, getMessage, printStackTrace, printStackTrace, printStackTrace, toString etc from the Throwable class.
Packages that use ServletException :
  * javax.servlet
  * javax.servlet.http









                           
Q).What is a Servlet Filter?
A).   

A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses.
Filters typically do not themselves create responses, but instead provide universal functions that can be "attached" to any type of servlet or JSP page.
Filters provide the ability to encapsulate recurring tasks in reusable units and can be used to transform the response from a servlet or a JSP page.
Filters can perform many different types of functions:
  * Authentication
  * Logging and auditing
  * Data compression
  * Localization

The filter API is defined by the Filter, FilterChain, and FilterConfig interfaces in the javax.servlet package. You define a filter by implementing the Filter interface. A filter chain, passed to a filter by the container, provides a mechanism for invoking a series of filters. Filters must be configured in the deployment descriptor :

<!--Servlet Filter that handles site authorization.-->
<filter>
     <filter-name>AuthorizationFilter</filter-name>
     <filter-class>examples.AuthorizationFilter</filter-class>
     <description>This Filter authorizes user access to application components based upon request URI.</description>
     <init-param>
        <param-name>error_page</param-name>
        <param-value>../../error.jsp</param-value>
     </init-param>
</filter>

<filter-mapping>
     <filter-name>AuthorizationFilter</filter-name>
     <url-pattern>/restricted/*</url-pattern>
</filter-mapping>

 

Read more...

Q).Is Servlet is Thread Safe ?How to make Servlet as Thread Safe?
A.)
Servlet is not thread safe.it allows to access more than one
thread at a time.IF we want to make servlet as a thread safe
then make service method is synchronized or implement
SingleThreadModel interface.There is no methods in this
interface.
 
Q).What is difference between Forward() and sendRedirect()?
A.) The RequestDispatcher forward and include methods are 
internal to a servlet container and does not affect the 
public url of the webresource.

forward() are excute on the server side.

when a forward() is invoked,the request is sent to another 
resource on the server without the client being inform that 
a different resource is going to process the request.This 
occurs completely with in the webcontainer.

sendRedirect() excutes on the client side.

When a sendRedirect()is invoked,it causes the webcontainer 
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.
 
Q).What is Difference Between webserver and application server?  
A).1) Webserver serves pages for viewing 
in web browser, application server provides exposes businness logic for 
client applications through various protocols

(2) Webserver exclusively handles http requests.application server 
serves bussiness logic to application programs through any number of 
protocols.

(3) Webserver delegation model is fairly simple,when the request comes 
into the webserver,it simply passes the request to the program best able
 to handle it(Server side program). It may not support transactions and 
database connection pooling.

(4) Application server is more capable of dynamic behaviour than 
webserver. We can also configure application server to work as a 
webserver.Simply applic! ation server is a superset of webserver.

Q.)Can it possible to validate form fields before execution of servlet service m
    method and how if yes?
A.)We can do it, There are two validation is available

1. Form validation
2. Server side validation

1. Form Validation - This validation is perform client side,
java script used to achieve these form validation

2. Server side Validation - This type we can use predefined
server side validation method used to achieve these validate.

Note:- In perform wise we compare Form validation is better
than server side validation. it's easy to progress.
 
Q.) What is the need of session Tracking in HttpServlet? 
A).As per http protocol no user information is  pertained. 
every request is considered as a new request and there will 
not be any session maintained between requests. so to 
maintain users information we have to use session 
tracking
 
Q).What happen if we wont use destroy()?  
A). 
Think, if there is 100's of objects are utilizing the
resource(i.e Connection object). That means allocation of
those objects are stored in the internal memory of the JVM
right... If similar requests are utilizing the Connection
object.... at one time the JVM utilization memory is full...
this will degrade the application. For this reason we call
explicitly destroy()...... if not the Garbage Collector will
taken care to reclaim the memory.... by we don's say when it
will be reclaim the memory and free the JVM memory......

Read more...

What is Servlets and explain the advantages of Servlet life cycle?

Answer
Servlets are the programs that run under web server environment. A copy of Servlet class can handle numerous request threads. In servlets, JVM stays running and handles each request using a light weight thread.
Servlets life cycle involve three important methods, i.e. init, service and destroy.
Init()
Init method is called when Servlet first loaded in to the web server memory.
Service()
Once initialized, Servlets stays in memory to process requests. Servlets read the data provided in the request in the service() method.
Destroy()
When server unloads servlets, destroy() method is called to clean up resources the servlet is consuming.

What are different Authentication options available in Servlets.

Answer
There are four ways of Authentication options available in servlets
HTTP basic authentication
In this, server uses the username and password provided by the client and these credentials are transmitted using simple base64 encoding.
HTTP digest authentication
This option is same the basic authentication except the password is encrypted and transmitted using SHA or MD5.
HTTPS client authentication
This options is based on HTTP over SSL.
Form-based authentication
Form-based authentication uses login page to collect username and password.

Explain why HttpServlet is declared abstract.

Answer
The Constructor HttpServlet() does nothing because this is an abstract class. Default implementations in a few Java classes like HttpServlet don’t really do anything. Hence, they need to be overridden.
Usually one of the following methods of HttpServlet must be overridden by a subclass:
doGet, if the servlet supports HTTP GET requests
doPost, HTTP POST requests
doPut, HTTP PUT requests
doDelete, HTTP DELETE requests
init and destroy, to manage resources
getServletInfo, to provide information
However, there doesn’t seem to be any reason why the service method should be overridden because it eventually dispatches the task to one of the doXXX methods.

What is the GenericServlet class?

Answer
GenericServlet makes writing servlets easier. To write a generic servlet, all you need to do is to override the abstract service method.


What is the difference between an Applet and a Servlet?

Answer

Applets
  • Applets are applications designed to be transmitted over the network and executed by Java compatible web browsers.
  • An Applet is a client side java program that runs within a Web browser on the client machine.
  • An applet can use the user interface classes like AWT or Swing.
  • Applet Life Cycle Methods: init(), stop(), paint(), start(), destroy()
Servlets
  • Servlets are Java based analog to CGI programs, implemented by means of servlet container associated with an HTTP server.
  • Servlet is a server side component which runs on the web server.
  • The servlet does not have a user interface.
  • Servlet Methods: doGet(), doPost()

Read more...

What mechanisms are used by a Servlet Container to maintain session information?
Cookies, URL rewriting, and HTTPS protocol information are used to maintain session information
Difference between GET and POST
In GET your entire form submission can be encapsulated in one URL, like a hyperlink. query length is limited to 260 characters, not secure, faster, quick and easy.
In POST Your name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the form's output. It is used to send a chunk of data to the server to be processed, more versatile, most secure.
What is session?
The session is an object used by a servlet to track a user's interaction with a Web application across multiple HTTP requests.
What is servlet mapping?
The servlet mapping defines an association between a URL pattern and a servlet. The mapping is used to map requests to servlets.
What is servlet context ?
The servlet context is an object that contains a servlet's view of the Web application within which the servlet is running. Using the context, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use. (answer supplied by Sun's tutorial).
Which interface must be implemented by all servlets?
Servlet interface.
Explain the life cycle of Servlet.
Loaded(by the container for first request or on start up if config file suggests load-on-startup), initialized( using init()), service(service() or doGet() or doPost()..), destroy(destroy()) and unloaded.
When is the servlet instance created in the life cycle of servlet? What is the importance of configuring a servlet?
An instance of servlet is created when the servlet is loaded for the first time in the container. Init() method is used to configure this servlet instance. This method is called only once in the life time of a servlet, hence it makes sense to write all those configuration details about a servlet which are required for the whole life of a servlet in this method.
Why don't we write a constructor in a servlet?
Container writes a no argument constructor for our servlet.
When we don't write any constructor for the servlet, how does container create an instance of servlet?
Container creates instance of servlet by calling Class.forName(className).newInstance().
Once the destroy() method is called by the container, will the servlet be immediately destroyed? What happens to the tasks(threads) that the servlet might be executing at that time?
Yes, but Before calling the destroy() method, the servlet container waits for the remaining threads that are executing the servlet’s service() method to finish.
What is the difference between callling a RequestDispatcher using ServletRequest and ServletContext?
We can give relative URL when we use ServletRequest and not while using ServletContext.
Why is it that we can't give relative URL's when using ServletContext.getRequestDispatcher() when we can use the same while calling ServletRequest.getRequestDispatcher()?
Since ServletRequest has the current request path to evaluae the relative path while ServletContext does not.

Read more...

Interview question and answers in servlets?

What is Servlet?
A servlet is a Java technology-based Web component, managed by a container called servlet container or servlet engine, that generates dynamic content and interacts with web clients via a request\/response paradigm.
Why is Servlet so popular?
Because servlets are platform-independent Java classes that are compiled to platform-neutral byte code that can be loaded dynamically into and run by a Java technology-enabled Web server.
What is servlet container?
The servlet container is a part of a Web server or application server that provides the network services over which requests and responses are sent, decodes MIME-based requests, and formats MIME-based responses. A servlet container also contains and manages servlets through their lifecycle.
When a client request is sent to the servlet container, how does the container choose which servlet to invoke?
The servlet container determines which servlet to invoke based on the configuration of its servlets, and calls it with objects representing the request and response.
If a servlet is not properly initialized, what exception may be thrown?
During initialization or service of a request, the servlet instance can throw an UnavailableException or a ServletException.
Given the request path below, which are context path, servlet path and path info?
/bookstore/education/index.html

context path: /bookstore
servlet path: /education
path info: /index.html
What is filter? Can filter be used as request or response?
A filter is a reusable piece of code that can transform the content of HTTP requests,responses, and header information. Filters do not generally create a response or respond to a request as servlets do, rather they modify or adapt the requests for a resource, and modify or adapt responses from a resource.
When using servlets to build the HTML, you build a DOCTYPE line, why do you do that?
I know all major browsers ignore it even though the HTML 3.2 and 4.0 specifications require it. But building a DOCTYPE line tells HTML validators which version of HTML you are using so they know which specification to check your document against. These validators are valuable debugging services, helping you catch HTML syntax errors.
What is new in ServletRequest interface ? (Servlet 2.4)
The following methods have been added to ServletRequest 2.4 version:
public int getRemotePort()
public java.lang.String getLocalName()
public java.lang.String getLocalAddr()
public int getLocalPort()
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+)
How can I send user authentication information while making URL Connection?
You'll want to use HttpURLConnection.setRequestProperty and set all the appropriate headers to HTTP authorization.
Can we use the constructor, instead of init(), to initialize servlet?
Yes , of course you can use the constructor instead of init(). There's nothing to stop you. But you shouldn't. The original reason for init() was that ancient versions of Java couldn't dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won't have access to a ServletConfig or ServletContext.
How can a servlet refresh automatically if some new data has entered the database?
You can use a client-side Refresh or Server Push
The code in a finally clause will never fail to execute, right?
Using System.exit(1); in try block will not allow finally code to execute.

Read more...

What are implict objects?

Implicit Objects:Implicit objects in jsp are the objects that are created by the container automatically and the container makes them available to the developers, the developer do not need to create them explicitly. Since these objects are created automatically by the container and are accessed using standard variables; hence, they are called implicit objects. The implicit objects are parsed by the container and inserted into the generated servlet code. They are available only within the jspService method and not in any declaration. Implicit objects are used for different purposes. Our own methods (user defined methods) can't access them as they are local to the service method and are created at the conversion time of a jsp into a servlet. But we can pass them to our own method if we wish to use them locally in those functions.

The Implicit Objects are:
1.Out
2.Request
3.Response
4.Application
5.Session
6.Page
7.PageContext
8.Exception
9.Config
10.Object

                            Explaination of Each Object
  •  Application: These objects has an application scope. These objects are available at the widest context level, that allows to share the same information between the JSP page's servlet and any Web components with in the same application.
  • Config: These object has a page scope and is an instance of javax.servlet.ServletConfig class. Config object allows to pass the initialization data to a JSP page's servlet. Parameters of this objects can be set in the deployment descriptor (web.xml) inside the element <jsp-file>. The method getInitParameter() is used to access the initialization parameters.
  • Exception: This object has a page scope and is an instance of java.lang.Throwable class. This object allows the exception data to be accessed only by designated JSP "error pages."
  • Out: This object allows us to access the servlet's output stream and has a page scope. Out object is an instance of javax.servlet.jsp.JspWriter class. It provides the output stream that enable access to the servlet's output stream.
  • Page: This object has a page scope and is an instance of the JSP page's servlet class that processes the current request. Page object represents the current page that is used to call the methods defined by the translated servlet class. First type cast the servlet before accessing any method of the servlet through the page.
  • Pagecontext: PageContext has a page scope. Pagecontext is the context for the JSP page itself that provides a single API to manage the various scoped attributes. This API is extensively used if we are implementing JSP custom tag handlers. PageContext also provides access to several page attributes like including some static or dynamic resource.
  • Request: Request object has a request scope that is used to access the HTTP request data, and also provides a context to associate the request-specific data. Request object implements javax.servlet.ServletRequest interface. It uses the getParameter() method to access the request parameter. The container passes this object to the _jspService() method.
  • Response: This object has a page scope that allows direct access to the HTTPServletResponse class object. Response object is an instance of the classes that implements the javax.servlet.ServletResponse class. Container generates to this object and passes to the _jspService() method as a parameter.
  • Session: Session object has a session scope that is an instance of javax.servlet.http.HttpSession class. Perhaps it is the most commonly used object to manage the state contexts. This object persist information across multiple user connection.

Read more...

Different types of scopes in Jsp?

There are four Different Types of Scopes in Jsp.
1.Page
2.Request
3.Session
4.Application

Page: Objects with page scope are accessible only within the page in which they're created. The data is valid only during the processing of the current response; once the response is sent back to the browser, the data is no longer valid. If the request is forwarded to another page or the browser makes another request as a result of a redirect, the data is also lost.



Request: Objects with request scope are accessible from pages processing the same request in which they were created. Once the container has processed the request, the data is released. Even if the request is forwarded to another page, the data is still available though not if a redirect is required.
                  
  Session:Objects with session scope are accessible from pages processing requests that are in the same session as the one in which they were created. A session is the time users spend using the application, which ends when they close their browser, when they go to another Web site, or when the application designer wants (after a logout, for instance). So, for example, when users log in, their username could be stored in the session and displayed on every page they access. This data lasts until they leave the Web site or log out.
Application:
Objects with application scope are accessible from JSP pages that reside in the same application. This creates a global object that's available to all pages.
Application scope uses a single namespace, which means all your pages should be careful not to duplicate the names of application scope objects or change the values when they're likely to be read by another page (this is called thread safety). Application scope variables are typically created and populated when an application starts and then used as read-only for the rest of the application.


Read more...

Acessing data from DataBase into Jsp?

<%@ page language="java" import="java.sql.*" %>

<%
 String driver = "org.gjt.mm.mysql.Driver";
 Class.forName(driver).newInstance();
 

 Connection con=null;
 ResultSet rst=null;
 Statement stmt=null;
 

 try{
  String url="jdbc:mysql://localhost/books?user=
<user>&password=<password>";
  con=DriverManager.getConnection(url);
  stmt=con.createStatement();
 }
 catch(Exception e){
  System.out.println(e.getMessage());
 }

 if(request.getParameter("action") != null){ 
  String bookname=request.getParameter("bookname");
  String author=request.getParameter("author");
  stmt.executeUpdate("insert into books_details(book_name,
author) values('"+bookname+"','"+author+"')");
  rst=stmt.executeQuery("select * from books_details");
  %>
  <html>
  <body>
  <center>
   <h2>Books List</h2>
   <table border="1" cellspacing="0" cellpadding
="0">
   <tr>
    <td><b>S.No</b></td>
    <td><b>Book Name</b></td>
    <td><b>Author</.b></td>
   </tr>
     <%
    int no=1;
    while(rst.next()){
    %>
    <tr>
      <td><%=no%></td>
      <td><%=rst.getString("
book_name")%></td>
      <td> <%=rst.getString("author")
%> </td>
    </tr>
    <%
    no++;
 }
 rst.close();
 stmt.close();
 con.close();
%>
   </table>
   </center>
  </body>
 </html>
<%}else{%>
 <html>
 <head>
  <title>Book Entry FormDocument</title>
  <script language="javascript">
      function validate(objForm){
   if(objForm.bookname.value.length==0){
   alert("Please enter Book Name!");
   objForm.bookname.focus();
   return false;
   }
   if(objForm.author.value.length==0){
   alert("Please enter Author name!");
   objForm.author.focus();
   return false;
   }
   return true;
    }
   </script>
  </head>
  

  <body>
   <center>
<form action="BookEntryForm.jsp" method="post" 
name="entry" onSubmit="return
 validate(this)">
 <input type="hidden" value="list" name="action">
 <table border="1" cellpadding="0" cellspacing="0">
 <tr>
  <td>
   <table>
    <tr>
    <td colspan="2" align="center">
<h2>Book Entry Form</h2></td>
    </tr>
    <tr>
    <td colspan="2">&nbsp;</td>
    </tr>
    <tr>
    <td>Book Name:</td>
    <td><input name="bookname" type=
"text" size="50"></td>
    </tr>
    <tr>
    <td>Author:</td><td><input name=
"author" type="text" size="50"></td>
    </tr>
    <tr>
     <td colspan="2" align="center">
<input type="submit" value="Submit"></td>
     </tr>
    </table>
   </td>
  </tr>
 </table>
</form>
   </center>
  </body>
 </html>
<%}%>

Explanation of the above code:
Declaring Variables: Java is a strongly typed language which means, that variables must be explicitly declared before use and must be declared with the correct data types. In the above example code we declare some variables for making connection. Theses variables are- 
Connection con=null;
ResultSet rst=null;
Statement stmt=null;


The objects of type Connection, ResultSet and Statement are associated with the Java sql. "con" is a Connection type object variable that will hold Connection type object. "rst" is a ResultSet type object variable that will hold a result set returned by a database query. "stmt" is a object variable of Statement .Statement Class methods allow to execute any query.  
Connection to database: The first task of this programmer is to load database driver. This is achieved using the single line of code :-
String driver = "org.gjt.mm.mysql.Driver";
Class.forName(driver).newInstance();
The next task is to make a connection. This is done using the single line of code :-
String url="jdbc:mysql://localhost/books?user=<userName>&password=<password>";
con=DriverManager.getConnection(url);
When url is passed into getConnection() method of DriverManager class it  returns connection object. 
Executing Query or Accessing data from database:
This is done using following code :-

stmt=con.createStatement(); //create a Statement object 
rst=stmt.executeQuery("select * from books_details");
stmt is the Statement type variable name and rst is the RecordSet type variable. A query is always executed on a Statement object.
A Statement object is created by calling createStatement() method on connection object con. 
The two most important methods of this Statement interface are executeQuery() and executeUpdate(). The executeQuery() method executes an SQL statement that returns a single ResultSet object. The executeUpdate() method executes an insert, update, and delete SQL statement. The method returns the number of records affected by the SQL statement execution.
After creating a Statement ,a method executeQuery() or  executeUpdate() is called on Statement object stmt and a SQL query string is passed in method executeQuery() or  executeUpdate().
This will return a ResultSet rst related to the query string.
Reading values from a ResultSet:
while(rst.next()){

   %>

   <tr><td><%=no%></td><td><%=rst.getString("book_name")%></td><td><%=rst.getString("author")%></td></tr>

  <%

}
The ResultSet  represents a table-like database result set. A ResultSet object maintains a cursor pointing to its current row of data. Initially, the cursor is positioned before the first row. Therefore, to access the first row in the ResultSet, you use the next() method. This method moves the cursor to the next record and returns true if the next row is valid, and false if there are no more records in the ResultSet object.
Other important methods are getXXX() methods, where XXX is the data type returned by the method at the specified index, including String, long, and int. The indexing used is 1-based. For example, to obtain the second column of type String, you use the following code:
resultSet.getString(2);
You can also use the getXXX() methods that accept a column name instead of a column index. For instance, the following code retrieves the value of the column LastName of type String.
resultSet.getString("book_name");
The above example shows how you can use the next() method as well as the getString() method. Here you retrieve the 'book_name' and 'author' columns from a table called 'books_details'. You then iterate through the returned ResultSet and print all the book name and author name in the format " book name | author " to the web page.
Summary:
This article presents JDBC and shows how you can manipulate data in a relational database from your  JSP page. To do this, you need to use  the java.sql package: Driver Manager, Connection, Statement, and ResultSet. Keep in mind, however, that this is only an introduction. To create a Web application, you need  JDBC to use more features such as prepared statements and connection pooling.

Read more...

What are the Jsp Page Directives?

Defines attributes that apply to an entire JSP page.
 

JSP Syntax

<%@ page
          [ language="java" ]
          [ extends="package.class" ]
          [ import="{package.class | package.*}, ..." ]
          [ session="true | false" ]
          [ buffer="none | 8kb | sizekb" ]
          [ autoFlush="true | false" ]
          [ isThreadSafe="true | false" ]
          [ info="text" ]
          [ errorPage="relativeURL" ]
          [ contentType="mimeType [ ;charset=characterSet ]"   |   "text/html ; charset=ISO-8859-1" ]
          [ isErrorPage="true | false" ]
%>
 Description:
The <%@ page %> directive applies to an entire JSP file and any of its static include files, which together are called a translation unit. A static include file is a file whose content becomes part of the calling JSP file. The <%@ page %> directive does not apply to any dynamic include files; see <jsp:include> for more information.
You can use the <%@ page %> directive more than once in a translation unit, but you can only use each attribute, except import, once. Because the import attribute is similar to the import statement in the Java programming language, you can use a <%@ page %> directive with import more than once in a JSP file or translation unit.
No matter where you position the <%@ page %> directive in a JSP file or included files, it applies to the entire translation unit. However, it is often good programming style to place it at the top of the JSP file.
                 
ATTRIBUTES:
            
  • language="java" The scripting language used in scriptlets, declarations, and expressions in the JSP file and any included files. In this release, the only allowed value is java.
  • extends="package.class" The fully qualified name of the superclass of the Java class file this JSP file will be compiled to. Use this attribute cautiously, as it can limit the JSP container's ability to provide a specialized superclass that improves the quality of the compiled file.
  • import="{package.class | package.* }, ..." A comma-separated list of Java packages that the JSP file should import. The packages (and their classes) are available to scriptlets, expressions, and declarations within the JSP file. If you want to import more than one package, you can specify a comma-separated list after import or you can use import more than once in a JSP file.
    The following packages are implicitly imported, so you don't need to specify them with the import attribute:
    java.lang.*
    javax.servlet.*
    javax.servlet.jsp.*
    javax.servlet.http.*
    You must place the import attribute before the element that calls the imported class.
  • session="true | false" Whether the client must join an HTTP session in order to use the JSP page. If the value is true, the session object refers to the current or new session.
    If the value is false, you cannot use the session object or a <jsp:useBean> element with scope=session in the JSP file. Either of these usages would cause a translation-time error.
    The default value is true.
  • buffer="none | 8kb | sizekb" The buffer size in kilobytes used by the out object to handle output sent from the compiled JSP page to the client Web browser. The default value is 8kb. If you specify a buffer size, the output is buffered with at least the size you specified.
  • autoFlush="true | false" Whether the buffered output should be flushed automatically when the buffer is full. If set to true (the default value), the buffer will be flushed. If set to false, an exception will be raised when the buffer overflows. You cannot set autoFlush to false when buffer is set to none.
  • isThreadSafe="true | false" Whether thread safety is implemented in the JSP file. The default value is true, which means that the JSP container can send multiple, concurrent client requests to the JSP page. You must write code in the JSP page to synchronize the multiple client threads. If you use false, the JSP container sends client requests one at a time to the JSP page.
  • info="text" A text string that is incorporated verbatim into the compiled JSP page. You can later retrieve the string with the Servlet.getServletInfo() method.
  • errorPage="relativeURL" A pathname to a JSP file that this JSP file sends exceptions to. If the pathname begins with a /, the path is relative to the JSP application's document root directory and is resolved by the Web server. If not, the pathname is relative to the current JSP file.
  • isErrorPage="true | false" Whether the JSP file displays an error page. If set to true, you can use the exception object in the JSP file. If set to false (the default value), you cannot use the exception object in the JSP file.
  • contentType="mimeType [ ;charset=characterSet ]" | "text/html;charset=ISO-8859-1" The MIME type and character encoding the JSP file uses for the response it sends to the client. You can use any MIME type or character set that are valid for the JSP container. The default MIME type is text/html, and the default character set is ISO-8859-1.

Read more...

What is Jsp Action?



   




Jsp Action:Servlet container provides many built in functionality to ease the development of the applications. Programmers can use these functions in JSP applications. The JSP Actions tags enables the programmer to use these functions. The JSP Actions are XML tags that can be used in the JSP page.

Read more...

FaceBook Login

HTML/JAVASCRIPT

HTML/JAVASCRIPT

HTML/JAVASCRIPT

HTML/JAVASCRIPT

Total Pageviews

STATCOUNTER

  © Blogger template Simple n' Sweet by Ourblogtemplates.com 2009

Back to TOP