Archive for the ‘Java’ Category

Request Dispatching In Servlets Servlets / Request Dispatcher RequestDispatcher Vs SendRedirect What Is A Request Dispatcher And How Does It Work What Is A Request Dispatcher And How Do I Use It Include Forward Redirect

Servlet Request Dispatching

Delegating the request from one servlet to another or transfer of excution from one servlet to another is known as request dispatching in servlet.

In another ways we can define it as interservlet communication,which means one servlet calling another servlet.This concept can be used in cases where some piece of code is needed to be written in different servlets.Thus, in such cases we can write that code in a single servlet and keep on calling that code from different servlets.

There are three ways in which request delegation can be done. These ways are as follows :

 

1.Include

2.Forward

3.Redirect

 

1. Include : This method suggests that the response from the another servlet be included in the response of the first  servlet. This is equivalent to copy pasting the response of one servlet into another.In case of inclusion,the response which the client receives is the append of both including and the included servlets.However,for the client it appears that the including servlet only has responded.Following line of code is used to include a servlet response into another servlet :

RequestDispatcher rd = request.getRequestDispatcher("url-pattern of the servlet");
rd.include(request,response);

 

Here RequestDispatcher object is needed .We can see that request and response objects of the first servlet are passed to the servlet which we wish to include through include method so that request remains the same and the included servlet can write to the response of the including servlet and it appears that including servlet itself has processed the request.

2. Forward : It works same as  include except for the difference that the reponse from the first servlet is flushed out and the reponse from the second servlet only is visible.Example code is :

RequestDispatcher rd = request.getRequestDispatcher("url-pattern of the servlet");
rd.forward(request,response);

 

Here also it appears to the client that the first servlet only has processed the request.

3. Redirect : In the case of redirect the first servlet issues a new request to a another servlet to which redirection has happened.In this case client sees a new request in the browser url bar and can realize that the response comes from the second servlet.Example code is :

response.sendRedirect("url-pattern of the servlet");

 

Here we can see that response object is used.This done for the reason that the issuing of the new request at the client side,in the browser url bar has to be done by the first servlet.

 

Number of View :1015

Tags: , , , , , , , ,

No Comments


Driver Registration In JDBC JDBC Connection Using the JDBC Driver Registering the JDBC driver Registering A JDBC driver JDBC Database Connections Basics Of JDBC How To Establish A JDBC Connection

Driver Registration In JDBC

An interface links two unrelated objects.A driver in JDBC context is an interface which links java code to database for communication.

Before ever the connection is established between the java programming end and the database end,the driver needs to be registered with the JVM by the means of DriverManager class.The DriverManager class has a vector of drivers registered to it.Once the entry has been made in the vector of the DriverManager class the driver is said to be registered.Each driver has the implementation and is capable of registering itself with the DriverManager class.This implementation is written in the static initialization block of the driver class.

We know that the static initialization block for a class is executed every time we load the class in the class loader. So, in order to run the static initialization block in the class loader we need to run the following line of code so that the driver registers itself with the DriverManager class :

Class.forName("DriverClass");

We can load or compile a class in class loader by calling the Class.forName(“class name”) method of the reflection concept in java.

Now let us have a look at how  the static initialization block in the driver class looks like :

 

class Driver{

 static{
    --------
    DriverManager.registerDriver(Driver Class);
    ----
    ----
    ----
    }
}

 

The function registerDriver() of the DriverManager class takes driver class as one of the parameters and looks for an entry ofr that driver in the vector it has. If an entry is found it means that the driver is already registered and the reference is returned from the vector.UIf entry is not available in the vector,the entry is made and reference is returned.This way we say that the driver is registered and connection can be made with the database as follows :

DriverManager.getConnection("Connection String","username","password");

Here connection String is depenedent on what database we are using.A typical example is :

jdbc:postgresql://host:port/database

Here ,username and password are username and password for the database.

Number of View :1001

Tags: , , , , , , , ,

No Comments


Transaction Locking And Isolation In JDBC Transaction isolation levels Using Transactions JDBC Isolation Example JDBC Guide Basics Of JDBC

Transaction Locking And Isolation In JDBC

Transaction is a set of instructions which follow atomicity,consistency,Integrity and durability.

1. Atomicity : This states that either all actions should complete or none should occur.

2. Consistency : This imposes certain business rule.

3. Integrity : This states that the two actions shall not interfere with each other or access each others data.

4. Durability : This states that the changes occurred due to a certain action or transaction must be stored in a durable persistent storage.

 

When we talk about the Transaction Locking And Isolation In JDBC, following are the issues we need to address when to concurrent transactions are taking place :

1. Dirty read : This happens when uncommitted data is read.Typical example is :

a. Transaction 1 inserts a row into a table.

b.Transaction 2 reads the new row.

c.Transaction 1 rolls back.

2. Non-repeatable read : This happens when data reads from the same table for the same row are not same.Typical example is

a. Transaction 1 reads a row.

b. Transaction 2 updates the row.

c. Transaction 1 reads the same row a second time and gets a different  results.

 

3. Phantom Read : This occurs due to appearing of new records when same query is run at different times.Typical example is :

a. Transaction 1 reads all rows that satisfy a WHERE clause.

b. Transaction 2 inserts additional rows that satisfies the WHERE clause.

c. Transaction 1 executes  the WHERE condition and picks up the additional row.

There are different transaction isolation levels used from JDBC coding to address these issues.The function to set isolation level is :

 

con.setTranscationIsolationLevel(intvalue);

Different integer values can be provided as follows :

0 – JDBC_TRANSACTION_NONE
1 – JDBC_TRANSACTION_READ_UNCOMMITTED
2 – JDBC_TRANSACTION_READ_COMMITTED
4 – JDBC_TRANSACTION_REPEATABLE_READ
8 – JDBC_TRANSACTION_SERIALIZABLE

Once we set the isolation levels using the above function,we can address the issues of transaction level in JDBC connection.As the isolation     level increases it gets stricter and lower level problems are also addressed.If we have set the value to 8 ,the isolation level with value lesser than 8 ,ie. 0,1,2,4, are also taken  care of.

Number of View :1047

Tags: , , , , , , , , ,

No Comments


How Container Does The Cookie Work in J2EE Define Cookie Cookies Explained Session In Servlet What Is Cookie How Apache Tomcat Handles Cookies Cookies Explained How Cookies Work Cookie Guide

How container does the cookie work?

 

A Cookie is a key value pair primarily used by the container to pass the session id in order to maintain session between client and server. There can be user defined cookies as well to use cookie as attributes to pass values from one part of the web application to another.

The user only requests for the session,creating a session object,attaching the session id with the session object and sending it to the client side or the browser with the response is done by the server at the back end. These things the code has nothing to bother about,the code asks for the session and these things happen automatically.

 

The code below shows how to get a session object in servlet :

HttpSession sess = request.getSession();

 

With the help of the above written code,the session can be retrieved from the server.Following are the steps covered by the server as soon as this line of code executes :

1. HttpSession object is created

2. Unique Session id is created

3. A new cookie object is created.

4. Session id is associated with cookie

5. Cookie is set Into the response to be sent to client side

 

These are the steps involved in sending the cookie with the response if session does not exist .

The same code when executed does the work of retrieving a session object from request if it exists.If session already exists,the server finds the session id from the request(since cookie will be sent to the server from client side as part of the url).The server finds out the unique session id from the cookie and retrieves the session object with the matching Session id.

Thus all the cookie work happens behind the scene.

To know whether the session already existed or was just created,we can ask the session object itself as :

sess.isNew();

If it returns true ,it means session is created otherwise it is a preexisting session.

Number of View :1192

Tags: , , , , , ,

No Comments


Concept Of Session In J2EE Session Tracking In J2EE Session Management Seesion Concept Servlet Basics Servlet Guide Session Tracking

Sessions In J2EE(How to maintain session in java web applications)

Session in J2EE application is the time of interaction between the client and the server.A session in used to retain the state of a client.As we know that http is connectionless protocol,after each request and response cycle between the client and the server,the connection is broken. It seems logical to break the connection as bandwidth is an expensive resource and needs to be relinquished so that the same can be used for another request.This is the reason http is the protocol used to access the web application in any web technology.

With the advantage of releasing the bandwidth comes the issue of maintaining the session in J2EE ,as after the request response cycle,the server does not remember the client.

So some extra work is needed in order to maintain the session.

The code to get a session object in servlet is as follows :

request.getSession(TRUE);

or

request.getSession(FALSE);

 

The difference between the two overloaded functions is that the function with ‘ TRUE’ as parameter returns a new session object even if a session does not  exist otherwise it will return the preexisting session object but in the later case the function will return the existing session object if it exists or if not existing a null  will be returned.

As we have got the session in a servlet now,it will be lost after a request response cycle.So,in order to maintain session we need to follow either of the approaches from:

1. Hidden parameters

2. Cookies

3. URL rewriting

1. Hidden parameter : In this case we pass the session id allotted by the server to the session object via parameters

2. Cookies : In this case the browser downloads the cookies at the client side,so that it can append the session id with each request.Creating a cookie ,attaching session id to it and sending it to the client side is all done implicitly by the server as soon as we execute the code

request.getSession(TRUE/FALSE);

 

3. URL rewriting is something to fall upon if the browser at the client side doe snot accept cookies.In such cases we encode the URL with an extra info called sessionid as the parameter.

The code for url rewriting is as follows :

response.encodeRedirectUrl("url-pattern");

 

Number of View :1525

Tags: , , , , , , , ,

No Comments


Difference Between Parameters And Attributes In Servlets/JSP Parameter vs. Attribute

Parameters and Attributes in Servlets And JSPs

 

Parameters and attributes in servlets and JSPs in java web applications are ways of communication among various entities(servlets and JSPs). However, there are differences between parameters and attributes.

The differences are as follows :

 

Attributes in Servlets and JSPs:

Attributes in servlets and JSPs can be of various scope.e.g.-request,session,servlet context(Application)

When attributes in servlets and JSPs are obtained in the code the return type is object of an “Object” class.

Attributes  in servlets and JSPs can be set or got from the code of the of servles and JSPs.

 

Parameters in servlets and JSPs:

Parameters  in servlets and JSPs are valid till the request response cycle only.

The return type of he code for obtaining  the parameters  in servlets and JSPs  is an object of  the  type String.

Parameters  in servlets and JSPs can only be read from the code.

Parameters  in servlets and JSPs can be set only through web.xml or appended in url from html parameters(text boxes etc.)

 

 

Code for getting a parameter is::

request.getParameter("paramname");

code for  seting an attribute is ::

scope.setAttribute("name","value");

code of getting an attribute value is ::

scope.getAttribute("name");

Here scope symbolizes different scopes(Request,Session or Application))

 

Parameters can be set from web.xml file as follows:

 

<servlet>
<servlet-name>myservlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
 <init-param> <param-name>pname</param-name>
<param-value>pvalue</param-value>
</init-param>
</servlet> 

or 

<web-app> 

<context-param>
 <param-name>pname</param-name>
<param-value>pvalue</param-value>
</context-param>
 ...
 </web-app>

 

Conceptually Parameters in servlets and JSPs are used to capture user input/s in the application or to read from some configuration file.

Attributes in servlets and JSPs are used to pass data from one servlets or JSP to another servlet or JSP.Since attributes in servlets and JSPs can be associated to various scopes,its usage spans form maintaining session to maintain request attributes or maintain or get a value across the application itself. It is the concept  of usage which itself describes the differences between the two.

 

 

Number of View :1375

Tags: , , , , , , , ,

No Comments


How To Get The Parameters From One Servlet To Another Using Request

Access Parameters From One Servlet To Another

Parameters can only be set from the web.xml file or can be input from a user input through a view. It cannot be set from the servlet code. Once we have accessed the required parameter/parameters in one servlet,we can set a particular attribute and set that very attribute with the accessed value of parameter and it can be accessed through out various pages depending upon the type and nature and scope of the attributes .Here it must be noted that attributes and only attributes can be set with a value from code and not the parameters. So if we want to access a parameter from one one servlet to another,we must first access it in one servlet ,set an attribute with its value and then we can access it in other servlet.If the scope of attribute is request it will exist till request exists,if session then till session and if servletcontext then once set it can be accessed through the application. But the parameters can be read only once when taken from user input. The following code demonstrates this :

<servlet>

<servlet-name>FirstServlet</servlet-name>

<servlet-class>myjobs.FirstServlet</servlet-class>

<init-param>

<param-name>username</param-name>

<param-value>john</param-value>

</init-param>

</servlet>

<servlet>

<servlet-name>SecondServlet</servlet-name>

<servlet-class>myjobs.SecondServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>NewServlet</servlet-name>

<url-pattern>/NewServlet</url-pattern>

</servlet-mapping>

FirstServlet :

public class FirstServlet extends HttpServlet {

/**

* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.

* @param request servlet request

* @param response servlet response

* @throws ServletException if a servlet-specific error occurs

* @throws IOException if an I/O error occurs

*/

protected void processRequest(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType(“text/html;charset=UTF-8”);

PrintWriter out = response.getWriter();

try {

String uname=getServletConfig().getInitParameter(“username”);

request.setAttribute(“usrname”,uname);

request.getRequestDispatcher(“SecondServlet”).forward(request, response);

} finally {

out.close();

}

}

}

Second Servlet :

public class SecondServlet extends HttpServlet {

/**

* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.

* @param request servlet request

* @param response servlet response

* @throws ServletException if a servlet-specific error occurs

* @throws IOException if an I/O error occurs

*/

protected void processRequest(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType(“text/html;charset=UTF-8”);

PrintWriter out = response.getWriter();

try {

/* TODO output your page here*/

out.println(“<html>”);

out.println(“<head>”);

out.println(“<title>Servlet SecondServlet</title>”);

out.println(“</head>”);

out.println(“<body>”);

out.println(“<h1>Parameter from first servlet is ” + request.getAttribute(“usrname”) + “</h1>”);

out.println(“</body>”);

out.println(“</html>”);

} finally {

out.close();

}

}

}

Here we are getting the paramter in FirstServlet setting an attribute and accessing in another servlet called SecondServlet.

Number of View :5719

Tags:

3 Comments


How To Redirect From One Servlet To Another Servlet Basics Servlet Redirect

Redirect to Other Servlets

Here we will talk about how to redirect from one servlet to another.Redirecting to a servlet is something like someone calls one for some work and the approached guy asks the person to call some other as he doesnot have the solution. It must be noted that the aproachee has to send the request to that other guy.The same thing happens in servlet redirecting as the request url changes and response comes form the servlet where request has been redirected. So,what can be done is write that very code in a servlet and that can be used at various places .The response object gives the method for redirect.The RequestDispacher class as the name suggests is the request delegater as it delegates the request but in redirect the request itself changes,so we can redirect the response to be given by another servlet.Iinside the doPost or doGet method.we can write the code to redirect in which the url for the servlet has to be given as a string..The example code is written below :

import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ResponseRedirect extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      ServletContext sc = this.getServletContext();
      response.senRedirect(“login”)
      }
      PrintWriter out = response.getWriter();
      out.print("Output after the content of login");
   }
}

Here we can see that redirection is occurring to login servlet in the ResponseRedirect servlet.In the redirection from one servlet to another we need to give the entry in <url-pattern> tag for the servlet as string.Once redirection happens the new request goes to login servlet,that means that client url changes and response comes from the login servlet as opposed to in the case of include or forward.With redirection we can move across applications and even across containers.Inside the servlet where redirection is happening,the rest of the code for the servlet will not be executed as the execution goes to the new redirected servlet.In the case of redirection we donot pass the request and response objects from the first servlet because new request and response is generated.

Number of View :2253

Tags:

No Comments


how to forward from one servlet to another Servlet Essentials Servlet Forward

Forward to Servlets

Here we will talk about how to forward from one servlet to another.Forwarding to a servlet is something like someone calls one for some work and the approached guy asks some one for help and returns the result to the approachee. It must be noted that the aproachee always sees the response from the that same guy only whom he called.The same thing happens in servlet forwarding as the request url doesnot change and response always comes as it has come from the first servlet and not the forwarded one. So,what can be done is write that very code in a servlet and that can be used at various places.The forward basically is a dynamic .The RequestDispatcher class gives the method for forward.The RequestDispacher class as the name suggests is the request delegater. The RequestDispatcher instance can be get from the request object inside the doPost or doGet method.Here the request and response objects are passed as paramters from the servlet code where forward code is written.The example code is written below :

import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class RequestDispatch extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      ServletContext sc = this.getServletContext();
      RequestDispatcher rDis = sc.getRequestDispatcher("/login");
      if (rDis != null){
          rDis.forward(request, response);
      }
      PrintWriter out = response.getWriter();
      out.print("Output after the content of login");
   }
}

Here we can see that request is forwarded to login servlet in the RequestDispatch servlet.In the getting of RequestDispatch instance from the request object we need to give the entry in <url-pattern> tag for the servlet as string.

Number of View :2117

Tags:

No Comments


how to include one servlet into another Servlet Essentials Servlet Include

Include Servlets

Here we will talk about how to include one servlet into another.Including a servlet is as same as include that servlet`s code into the servlet in which it is included. This concept is used in places where we need to have reusable servlet codes which can be used at multiple places.Suppose we have some common code like login or some other logic which can be used at various places.So,what can be done is write that very code in a servlet and that can be used at various places.The inclusion basically is a dynamic inclusion which means the response of the included servlet is included in the includer servlet.The RequestDispatcher class gives the method for inclusion.The RequestDispacher class as the name suggests is the request delegater. The RequestDispatcher instance can be get from the request object inside the doPost or doGet method.Here the request and response objects are passed as paramters from the servlet code where inclusion code is written.The example code is written below :

import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class RequestDispatch extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      ServletContext sc = this.getServletContext();
      RequestDispatcher rDis = sc.getRequestDispatcher("/login");
      if (rDis != null){
          rDis.include(request, response);
      }
      PrintWriter out = response.getWriter();
      out.print("Output after the content of login");
   }
}

Here we can see that login is included in the RequestDispatch servlet.In the getting if RequestDispatch instance from the request object we need to give the entry in <url-pattern> tag for the servlet.Then we can find that if we are printing anything from the included the servlet it will appear when we run RequestDispatch servlet as the login servlet is included.

Number of View :2308

Tags:

No Comments



SetPageWidth
Content Protected Using Blog Protector By: PcDrome.

Mahol Dot Org is Stephen Fry proof thanks to caching by WP Super Cache