Friday, August 21, 2009
How do you communicate in between Applets & Servlets ?
We can use the java.net.URLConnection and java.net.URL classes to open a standard HTTP connection and "tunnel" to the web server. The server then passes this information to the servlet in the normal way. Basically, the applet pretends to be a web browser, and the servlet doesn't know the difference. As far as the servlet is concerned, the applet is just another HTTP client.
What is the order of method invocation in an Applet ?
public void init() : Initialization method called once by browser.
public void start() : Method called after init() and contains code to start processing. If the user leaves the page and returns without killing the current browser session, the start () method is called without being preceded by init ().
public void stop() : Stops all processing started by start (). Done if user moves off page.
public void destroy() : Called if current browser session is being terminated. Frees all resources used by applet.
public void start() : Method called after init() and contains code to start processing. If the user leaves the page and returns without killing the current browser session, the start () method is called without being preceded by init ().
public void stop() : Stops all processing started by start (). Done if user moves off page.
public void destroy() : Called if current browser session is being terminated. Frees all resources used by applet.
Wednesday, August 12, 2009
What is jGuard
jGuard is a java security framework based on JAAS. this framework is written for web applications, to resolve simply, access control problems.
Features
Features
- relies only on java 1.4 and j2ee 1.3 or higher
- can be adapted on any webapp, on any application server
- permit to a user to have more than one role simultaneously
- does not depend on a web framework, or an AOP framework
- build on top of the standard and very secure and flexible JAAS
- authentications and authorizations are handled by pluggable mechanisms
- handle authentication data stored in a database, an XML file, a JNDI datasource, an LDAP directory, Kerberos...
- changes take effects 'on the fly' (dynamic configuration)
- permissions, roles,and their associations can be created, updated,deleted on the fly through a webapp (an API is provided too)
- each webapp has its own authentications and authorizations configuration
- a taglib is provided to protect jsp fragment
- support security manager
How list all loaded JDBC drivers and gets information about each one?
This example lists all loaded JDBC drivers and gets information about each one.
List drivers = Collections.list(DriverManager.getDrivers());
for (int i=0; i < drivers.size(); i++) {
Driver driver = (Driver)drivers.get(i);
// Get name of driver
String name = driver.getClass().getName();
// Get version info
int majorVersion = driver.getMajorVersion();
int minorVersion = driver.getMinorVersion();
boolean isJdbcCompliant = driver.jdbcCompliant();
}
List drivers = Collections.list(DriverManager.getDrivers());
for (int i=0; i < drivers.size(); i++) {
Driver driver = (Driver)drivers.get(i);
// Get name of driver
String name = driver.getClass().getName();
// Get version info
int majorVersion = driver.getMajorVersion();
int minorVersion = driver.getMinorVersion();
boolean isJdbcCompliant = driver.jdbcCompliant();
}
How to connect to a SQL Server database using JDBC?
This example connects to a SQLServer database using the NetDirect JDBC driver.
Connection connection = null;
try {
String driverName = "com.jnetdirect.jsql.JSQLDriver"; // NetDirect JDBC driver
String serverName = "127.0.0.1";
String portNumber = "1433";
String mydatabase = serverName + ":" + portNumber;
String url = "jdbc:JSQLConnect://" + mydatabase; // a JDBC url
String username = "username";
String password = "password";
// Load the JDBC driver
Class.forName(driverName);
// Create a connection to the database
connection = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
// Could not find the database driver
} catch (SQLException e) {
// Could not connect to the database
}
Connection connection = null;
try {
String driverName = "com.jnetdirect.jsql.JSQLDriver"; // NetDirect JDBC driver
String serverName = "127.0.0.1";
String portNumber = "1433";
String mydatabase = serverName + ":" + portNumber;
String url = "jdbc:JSQLConnect://" + mydatabase; // a JDBC url
String username = "username";
String password = "password";
// Load the JDBC driver
Class.forName(driverName);
// Create a connection to the database
connection = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
// Could not find the database driver
} catch (SQLException e) {
// Could not connect to the database
}
How to export a MySQL Table to a Flat File?
The default format of a file exported from MySQL is as follows: the fields are separated by tabs, the lines terminated by 'n', and backslashes(), newlines (n), and tabs (t) escaped by a backslash. NULL is exported as N.
This example exports the data in a table called mysql_table2 to a file named outfile.txt.
try {
// Create the statement
Statement stmt = connection.createStatement();
// Export the data
String filename = "c:tempoutfile.txt";
String tablename = "mysql_2_table";
stmt.executeUpdate("SELECT * INTO OUTFILE "" + filename + "" FROM " + tablename);
} catch (SQLException e) {
}
This example exports the data in a table called mysql_table2 to a file named outfile.txt.
try {
// Create the statement
Statement stmt = connection.createStatement();
// Export the data
String filename = "c:tempoutfile.txt";
String tablename = "mysql_2_table";
stmt.executeUpdate("SELECT * INTO OUTFILE "" + filename + "" FROM " + tablename);
} catch (SQLException e) {
}
How to list all the files in a directory?
File dir = new File("directoryName");
String[] children = dir.list();
if (children == null) {
// Either dir does not exist or is not a directory
} else {
for (int i=0; i < children.length; i++) {
// Get filename of file or directory
String filename = children[i];
}
}
// It is also possible to filter the list of returned files.
// This example does not return any files that start with `.'.
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return !name.startsWith(".");
}
};
children = dir.list(filter);
// The list of files can also be retrieved as File objects
File[] files = dir.listFiles();
// This filter only returns directories
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
files = dir.listFiles(fileFilter);
String[] children = dir.list();
if (children == null) {
// Either dir does not exist or is not a directory
} else {
for (int i=0; i < children.length; i++) {
// Get filename of file or directory
String filename = children[i];
}
}
// It is also possible to filter the list of returned files.
// This example does not return any files that start with `.'.
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return !name.startsWith(".");
}
};
children = dir.list(filter);
// The list of files can also be retrieved as File objects
File[] files = dir.listFiles();
// This filter only returns directories
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
files = dir.listFiles(fileFilter);
How to load a flat file in a MySQL database?
The default format of a file to load into a MySQL table is as follows: the fields must be separated by tabs, the input lines terminated by 'n', and backslashes(), newlines (n), and tabs (t) escaped by a backslash. The MySQL documentation explains how to change these defaults.
This example loads a flat file called infile.txt to a MySQL table named mysql_2_table with an INT and a VARCHAR(20) column.
try {
// Create the statement
Statement stmt = connection.createStatement();
// Load the data
String filename = "c:tempinfile.txt";
String tablename = "mysql_2_table";
stmt.executeUpdate("LOAD DATA INFILE "" + filename + "" INTO TABLE " + tablename);
// If the file is comma-separated, use this statement
stmt.executeUpdate("LOAD DATA INFILE "" + filename + "" INTO TABLE "
+ tablename + " FIELDS TERMINATED BY ','");
// If the file is terminated by rn, use this statement
stmt.executeUpdate("LOAD DATA INFILE "" + filename + "" INTO TABLE "
+ tablename + " LINES TERMINATED BY 'rn'");
} catch (SQLException e) {
}
This example loads a flat file called infile.txt to a MySQL table named mysql_2_table with an INT and a VARCHAR(20) column.
try {
// Create the statement
Statement stmt = connection.createStatement();
// Load the data
String filename = "c:tempinfile.txt";
String tablename = "mysql_2_table";
stmt.executeUpdate("LOAD DATA INFILE "" + filename + "" INTO TABLE " + tablename);
// If the file is comma-separated, use this statement
stmt.executeUpdate("LOAD DATA INFILE "" + filename + "" INTO TABLE "
+ tablename + " FIELDS TERMINATED BY ','");
// If the file is terminated by rn, use this statement
stmt.executeUpdate("LOAD DATA INFILE "" + filename + "" INTO TABLE "
+ tablename + " LINES TERMINATED BY 'rn'");
} catch (SQLException e) {
}
How to append a text to a file?
try {
BufferedWriter out = new BufferedWriter(new FileWriter("filename", true));
out.write("aString");
out.close();
} catch (IOException e) {
}
BufferedWriter out = new BufferedWriter(new FileWriter("filename", true));
out.write("aString");
out.close();
} catch (IOException e) {
}
How to read text from a file?
Here is the code to read text from the file
try {
BufferedReader in = new BufferedReader(new FileReader("infilename"));
String str;
while ((str = in.readLine()) != null) {
process(str);
}
in.close();
} catch (IOException e) {
}
try {
BufferedReader in = new BufferedReader(new FileReader("infilename"));
String str;
while ((str = in.readLine()) != null) {
process(str);
}
in.close();
} catch (IOException e) {
}
Sending e-mail using JavaMail API
The JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications. The JavaMail API is implemented as a Java platform optional package and is also available as part of the Java platform, Enterprise Edition.
You can use the following code to send a textual e-mail message to a single recipient from your Java program. Note that you need to download JavaMail API and put required jars into your classpath to be able to run this program.
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendApp {
public static void send(String smtpHost, int smtpPort,
String from, String to,
String subject, String content)
throws AddressException, MessagingException {
// Create a mail session
java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.port", ""+smtpPort);
Session session = Session.getDefaultInstance(props, null);
// Construct the message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject(subject);
msg.setText(content);
// Send the message
Transport.send(msg);
}
public static void main(String[] args) throws Exception {
// Send a test message
send("hostname", 25, " xxx@xyz.com ", " xyz@abc.com",
"Hello", "Hello, \n\n How are you ?");
}
}
You can use the following code to send a textual e-mail message to a single recipient from your Java program. Note that you need to download JavaMail API and put required jars into your classpath to be able to run this program.
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendApp {
public static void send(String smtpHost, int smtpPort,
String from, String to,
String subject, String content)
throws AddressException, MessagingException {
// Create a mail session
java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.port", ""+smtpPort);
Session session = Session.getDefaultInstance(props, null);
// Construct the message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject(subject);
msg.setText(content);
// Send the message
Transport.send(msg);
}
public static void main(String[] args) throws Exception {
// Send a test message
send("hostname", 25, " xxx@xyz.com ", " xyz@abc.com",
"Hello", "Hello, \n\n How are you ?");
}
}
Retrieving values from HTML form input elements in JSP
To retrieve any value from an HTML Form element on a jsp page you need to use the implicit HttpServletRequest object's getParameter(String s) method. The HttpServletRequest object is available to all jsp pages and is named request. The String argument of the method getParameter(String s) is the elements name whose value you want to retrieve.
The result of this method will differ according to what type of element you are querying. For instance a checkbox element might return "on" if it has been selected, or it might return "null" if it hasn't been selected. Where a text element will return the text/value that was part of the element at the time the form was submitted. A radio button will return the value of the selected radio button in the button group. If you try and query an element that never existed in the form and therefore was never submitted to the JSP page in the HttpServletRequest object will return null.
Example HTML Form:
form name="myForm" action="result.jsp" method="post"
input type="checkbox" name="inputCheckbox"
input type="radio" value="0" name="inputRadio"
input type="radio" value="1" name="inputRadio"
input name="inputText"
input type="submit" value="Submit Query"
Example JSP page (This will only display the values recieved from the submitted form):
= request.getParameter("inputCheckbox")
= request.getParameter("inputRadio")
= request.getParameter("inputText")
The result of this method will differ according to what type of element you are querying. For instance a checkbox element might return "on" if it has been selected, or it might return "null" if it hasn't been selected. Where a text element will return the text/value that was part of the element at the time the form was submitted. A radio button will return the value of the selected radio button in the button group. If you try and query an element that never existed in the form and therefore was never submitted to the JSP page in the HttpServletRequest object will return null.
Example HTML Form:
form name="myForm" action="result.jsp" method="post"
input type="checkbox" name="inputCheckbox"
input type="radio" value="0" name="inputRadio"
input type="radio" value="1" name="inputRadio"
input name="inputText"
input type="submit" value="Submit Query"
Example JSP page (This will only display the values recieved from the submitted form):
= request.getParameter("inputCheckbox")
= request.getParameter("inputRadio")
= request.getParameter("inputText")
How can I print the stack trace of an Exception out to my JSP page?
To print a stack trace out to your JSP page, you need to wrap the implicit object 'out' in a printWriter and pass the object to the printStackTrace method in Exception. ie:
// JSP scriptlet
try{
// An Exception is thrown
}catch(Exception e){
e.printStacktrace(new java.io.PrintWriter(out));
}
// JSP scriptlet
try{
// An Exception is thrown
}catch(Exception e){
e.printStacktrace(new java.io.PrintWriter(out));
}
What is the difference between HttpSession mySession=request.getSession(true) and HttpSession mySession=request.getSession()
request.getSession() will return the current session and if one does not exist, a new session will be cretaed.
request.getSession(true) will return the current session if one exists, if one doesn't exits a new one will be created.
So there is actually no difference between the two methods HOWEVER, if you use request.getSession(false), it will return the current session if one exists and if one DOES NOT exist a new one will NOT be cretaed.
request.getSession(true) will return the current session if one exists, if one doesn't exits a new one will be created.
So there is actually no difference between the two methods HOWEVER, if you use request.getSession(false), it will return the current session if one exists and if one DOES NOT exist a new one will NOT be cretaed.
I want to run JSP files using the Tomcat server, where should I place my JSP files?
Under the Tomcat root directory there will be a sub-directory named web-apps, all web applications running on this Tomcat server will reside there. Each web application will have it's own sub-directory under web-apps, so you could create a directory for your web application under the web-apps directory like so /web-apps/. JSP pages can be placed insisde the directory you have created or in other sub-directories you might like to create, however please note that for each new sub-directory you place your JSP files in the URL to access them will need to include each directory.
Inside the directory you created there needs to be another directory named WEB-INF, this directory will contain the web.xml file which contains configuration information for your web application such as the welcome file for your application, all servlet mappings, filters, etc...
Under the WEB-INF directory you can create another directory named classes, all your java classes used in your web application should be placed in here, in a tree structure that resembles their packages, for example: if you have a class named MyClass whose package is com.xyz then the class should be placed in/web-apps//WEB-INF/classes/com/xyz/MyClass.class. Another alternative to handling classes in this way is to package them all in a jar file, the jar file can be placed in a directory named lib also under the WEB-INF directory, for example: say you have a jar file named myLibrary.jar, it can be placed in /web-apps//WEB-INF/lib/myLibrary.jar. By placing classes and jar files in these directories Tomcat ensures they are on the CLASSPATH when you run your application.
An alternative to repeating this procedure each time you want to deploy some JSP pages to your Tomcat server is to simply create a WAR file and use the Tomcat manager (which can be accessed through a browser window) to deploy the WAR file to the server
Inside the directory you created there needs to be another directory named WEB-INF, this directory will contain the web.xml file which contains configuration information for your web application such as the welcome file for your application, all servlet mappings, filters, etc...
Under the WEB-INF directory you can create another directory named classes, all your java classes used in your web application should be placed in here, in a tree structure that resembles their packages, for example: if you have a class named MyClass whose package is com.xyz then the class should be placed in
An alternative to repeating this procedure each time you want to deploy some JSP pages to your Tomcat server is to simply create a WAR file and use the Tomcat manager (which can be accessed through a browser window) to deploy the WAR file to the server
How can I avoid making multiple HTTP calls for content that hasn't changed? Is it possible to cache it? Is there a way to set this in the header?
This can be achieved by using a filter. You can setup the filter in your web.xml to intercept the response and edit the HTTP headers for the specified content type. An example filter could look like:
package com.xyz
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
public class CacheFilter implements javax.servlet.Filter {
FilterConfig filterConfig = null;
public void init(FilterConfig filterConfig){
this.filterConfig = filterConfig;
}
public void doFilter(ServletRequest req,
ServletResponse res,
FilterChain chain)
throws IOException, ServletException {
String sCache = filterConfig.getInitParameter("cache");
if(sCache != null){ ((HttpServletResponse)res).setHeader("Cache-Control", sCache);
}
chain.doFilter(req, res);
}
public void destroy(){
this.filterConfig = null;
}
}
Now to set up this filter to act on all jpg requests you need to add the following to your web.xml file:
Cache
com.xyz.CacheFilter
cache
public, max-age=2592000
Cache
*.jpg
This filter will now instruct the client to store the specified content (jpg) in it's cache for 2592000 seconds from when this request was processed and no requests for this resource will be necessary till the time has elapsed.
package com.xyz
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
public class CacheFilter implements javax.servlet.Filter {
FilterConfig filterConfig = null;
public void init(FilterConfig filterConfig){
this.filterConfig = filterConfig;
}
public void doFilter(ServletRequest req,
ServletResponse res,
FilterChain chain)
throws IOException, ServletException {
String sCache = filterConfig.getInitParameter("cache");
if(sCache != null){ ((HttpServletResponse)res).setHeader("Cache-Control", sCache);
}
chain.doFilter(req, res);
}
public void destroy(){
this.filterConfig = null;
}
}
Now to set up this filter to act on all jpg requests you need to add the following to your web.xml file:
This filter will now instruct the client to store the specified content (jpg) in it's cache for 2592000 seconds from when this request was processed and no requests for this resource will be necessary till the time has elapsed.
What is the difference between Multiple Instances of Browser and Multiple Windows. How does this affect Sessions ?
From the current Browser window, if we open a new Window, then it referred to as Multiple Windows. Sessions properties are maintained across all these windows, even though they are operating in multiple windows.
Instead, if we open a new Browser, by either double clicking on the Browser Shortcut icon or shortcut link, then we are creating a new Instance of the Browser. This is referred to as Multiple Instances of Browser. Here each Browser window is considered as different client. So Sessions are not maintained across these windows.
Instead, if we open a new Browser, by either double clicking on the Browser Shortcut icon or shortcut link, then we are creating a new Instance of the Browser. This is referred to as Multiple Instances of Browser. Here each Browser window is considered as different client. So Sessions are not maintained across these windows.
What is Server Side Push and how is it implemented and when is it useful ?
Server Side push is useful when data needs to change regularly on the clients application or browser , without intervention from client. Standard examples might include apps like Stock's Tracker, Current News etc. As such server cannot connect to client's application automatically. The mechanism used is, when client first connects to Server, (Either through login etc..), then Server keeps the TCP/IP connection open.
It's not always possible or feasible to keep the connection to Server open. So another method used is, to use the standard HTTP protocols ways of refreshing the page, which is normally supported by all browsers.
META HTTP-EQUIV="Refresh" CONTENT="5;URL=/servlet/stockquotes/"
This will refresh the page in the browser automatically and loads the new data every 5 seconds.
It's not always possible or feasible to keep the connection to Server open. So another method used is, to use the standard HTTP protocols ways of refreshing the page, which is normally supported by all browsers.
META HTTP-EQUIV="Refresh" CONTENT="5;URL=/servlet/stockquotes/"
This will refresh the page in the browser automatically and loads the new data every 5 seconds.
How can i limit the number of Simultaneous connections to the same Servlet?
This option is configurable on the Server. For example JRun allows you to setup the number of maximum concurrent connections from Admin option.
How can i make sure User had logged in when accessing Secure Pages ?
At the beginning of each page , place this small code, or include it in a common file
HttpSession session =request.getSession(true);
if (session.getValue("username") == null) {
response.sendRedirect (response.encodeRedirectUrl("LoginPage.jsp?currentURL=productdata.jsp"));
}
else
{
// Go ahead and show the page
}
In LoginPage.jsp once the user has provided the correct logon credentials:
session.putValue("username",currentuser);
response.sendRedirect(response.encodeRedirectUrl(request.getParameter("currentURL")));
HttpSession session =request.getSession(true);
if (session.getValue("username") == null) {
response.sendRedirect (response.encodeRedirectUrl("LoginPage.jsp?currentURL=productdata.jsp"));
}
else
{
// Go ahead and show the page
}
In LoginPage.jsp once the user has provided the correct logon credentials:
session.putValue("username",currentuser);
response.sendRedirect(response.encodeRedirectUrl(request.getParameter("currentURL")));
What is Servlet Changing ?
Servlet Chaining is the process of chaining the output of one Servlet to another Servlet.
You need to configure your servlet engine Java Web server, JRun, , JServ ... for this process to work.
For example to configure JRun for servlet chaining,
Select the JSE service (JRun servlet engine) to access to the JSE Service Config panel. You have just to define a new mapping rule where you define your chaining servlet.
Let's say /servlets/TicketChainServlet for the virtual path and a comma separated list of servlets as CustomerServlet ,TicketServlet.
So when you invoke a request like http://javacommerce.com/servlets/chainServlet, internally the servlet CustomerServlet will be invoked first and its results will be piped into the servlet TicketServlet.
The CustomerServlet servlet code should look like:
public class CustomerServletextends HttpServlet {
public void doGet (HttpServletRequest request, HttpServletResponseresponse) {
PrintWriter out =res.getWriter();
rest.setContentType("text/html");
...
out.println("Customer Name : Tom");
}
}
TicketServlet has to do is to open an inputstream to the request object and read the data into a BufferedReader object.
BufferedReader b = newBufferedReader( new InputStreamReader(req.getInputStream() ) );
String data = b.readLine();
b.close();
Here in data variable you would get "CustomerName : Tom"
Note : Not many Servlet Engines support ServletChaining. Also it has been removed from the standard specifications for Servlets.
You need to configure your servlet engine Java Web server, JRun, , JServ ... for this process to work.
For example to configure JRun for servlet chaining,
Select the JSE service (JRun servlet engine) to access to the JSE Service Config panel. You have just to define a new mapping rule where you define your chaining servlet.
Let's say /servlets/TicketChainServlet for the virtual path and a comma separated list of servlets as CustomerServlet ,TicketServlet.
So when you invoke a request like http://javacommerce.com/servlets/chainServlet, internally the servlet CustomerServlet will be invoked first and its results will be piped into the servlet TicketServlet.
The CustomerServlet servlet code should look like:
public class CustomerServletextends HttpServlet {
public void doGet (HttpServletRequest request, HttpServletResponseresponse) {
PrintWriter out =res.getWriter();
rest.setContentType("text/html");
...
out.println("Customer Name : Tom");
}
}
TicketServlet has to do is to open an inputstream to the request object and read the data into a BufferedReader object.
BufferedReader b = newBufferedReader( new InputStreamReader(req.getInputStream() ) );
String data = b.readLine();
b.close();
Here in data variable you would get "CustomerName : Tom"
Note : Not many Servlet Engines support ServletChaining. Also it has been removed from the standard specifications for Servlets.
How can i read data from any URL, which can bea binary data or from a Active Server Page ?
Using the Following code, you can download any data. If it connects to either Servlet or ASP page, then the data get's processed if required and the resultant data is read back.
//Connect to any URL, can be to a image, to a static URL like www.yahoo.com or any ASP page.
URL url = new URL("http://www.aspkit.com/jdata/transaction/transact.asp");
URLConnection connection = url.openConnection();
InputStream stream = connection.getInputStream();
BufferedInputStream in = new BufferedInputStream(stream);
FileOutputStream file = new FileOutputStream("result.txt");
BufferedOutputStream out = new BufferedOutputStream(file);
//Reading Data from the above URL
int i; while ((i = in.read()) != -1){
out.write(i);
}
//Connect to any URL, can be to a image, to a static URL like www.yahoo.com or any ASP page.
URL url = new URL("http://www.aspkit.com/jdata/transaction/transact.asp");
URLConnection connection = url.openConnection();
InputStream stream = connection.getInputStream();
BufferedInputStream in = new BufferedInputStream(stream);
FileOutputStream file = new FileOutputStream("result.txt");
BufferedOutputStream out = new BufferedOutputStream(file);
//Reading Data from the above URL
int i; while ((i = in.read()) != -1){
out.write(i);
}
How do i know when user Session has expired or removed?
Define a class, say SessionTimeoutIndicator,which implements javax.servlet.http.HttpSessionBindingListener. Create a SessionTimeoutIndicator object and add it to the user session. When the session is removed, SessionTimeoutIndicator.valueUnbound() will be called by the Servlet engine. You can implement valueUnbound() to do the required operation.
How do i download a binary file from a Servlet or JSP page ?
Use the Normal Anchor Tag from your page. This is the most preferred way and let the browser handle the downloading part. Here is the Simple syntax for it,
DownloadFile From Here
Another way to have Servlet do this would be, provide a link to Servlet, and from the Servlet call this function ,
response.sendRedirect("/downloads/Profiler.zip");
DownloadFile From Here
Another way to have Servlet do this would be, provide a link to Servlet, and from the Servlet call this function ,
response.sendRedirect("/downloads/Profiler.zip");
What are Application Servers , Servlet Engines and Web Servers ? How are they different from each other ?
Initially when the Web started, then all it needed was a Server which would receive the requests for HTML pages or images and send them back to browsers. These are called Web Servers. Then came requests for handling high capacity Database Transactions, supporting latest Java Features like Servlets, JSP, EJB etc. These requests are handled by Application Servers. Normally for a Application Server to exists and process client requests, they need to come through Web servers. All the static data like plain HTML pages etc are placed on Web Server. All the Dynamic Content generators like Servlets, EJB are placed on application server.
Servlet Engines are similar to Application servers, except they support only Servlets and JSP.
Here is the Servlet Engines which support Servlets and JSP , http://java.sun.com/products/servlet/industry.html. Also here is a the list of All Web Servers and Application Servers.
Applications servers are just another level above Servlet Engines. Normally all the Application servers support Servlets and JSP. Not all Servlet Engines support other features like EJB etc, which Application Servers support.
Servlet Engines are similar to Application servers, except they support only Servlets and JSP.
Here is the Servlet Engines which support Servlets and JSP , http://java.sun.com/products/servlet/industry.html. Also here is a the list of All Web Servers and Application Servers.
Applications servers are just another level above Servlet Engines. Normally all the Application servers support Servlets and JSP. Not all Servlet Engines support other features like EJB etc, which Application Servers support.
How can i write Data submitted from a Applet into a different file , then show users this data on a new page ?
This is one of the most frequently used techniques. From your applet create a URL connection the Servlet and send the data using DataOutputStream. Next in the Service method of Servlet, using PrintWriter, create a new File. On the other end Applet will be waiting for response from Servlet, using DataInputStream. Pass the newly created filename to the Applet. Next From applet call ShowDocument() method with new URL.
Here is some sample code,
URL ticketservlet = new URL( "http://jcom.com/servlet/Ticketservlet ");
URLConnection servletConnection = ticketservlet.openConnection();
// inform the connection that we will send output and accept input
servletConnection.setDoInput(true);
servletConnection.setDoOutput(true);
// Don't use a cached version of URL connection.
servletConnection.setUseCaches (false);
servletConnection.setDefaultUseCaches (false);
// Specify the content type that we will send binary data
servletConnection.setRequestProperty ("Content-Type", "application/octet-stream");
// send the student object to the servlet using serialization
ObjectOutputStream ticketOutputToServlet = new ObjectOutputStream(servletConnection.getOutputStream());
// serialize the object , and sending it to servlet , ticketData should implement Serializable interface.
ticketOutputToServlet .writeObject(ticketData);
ticketOutputToServlet .flush();
ticketOutputToServlet .close();
//reading back data from servlet
ObjectInputStream inputFromServlet = new ObjectInputStream(servletConnection.getInputStream());
Vector resultantData = (Vector) inputFromServlet.readObject();
String filename = (String) resultantData.elementAt(0)
//Showing the newly created page from Applet
getAppletContext().showDocument(new URL("http://www.jcom.com/profiles/" + filename));
Here is some sample code,
URL ticketservlet = new URL( "http://jcom.com/servlet/Ticketservlet ");
URLConnection servletConnection = ticketservlet.openConnection();
// inform the connection that we will send output and accept input
servletConnection.setDoInput(true);
servletConnection.setDoOutput(true);
// Don't use a cached version of URL connection.
servletConnection.setUseCaches (false);
servletConnection.setDefaultUseCaches (false);
// Specify the content type that we will send binary data
servletConnection.setRequestProperty ("Content-Type", "application/octet-stream");
// send the student object to the servlet using serialization
ObjectOutputStream ticketOutputToServlet = new ObjectOutputStream(servletConnection.getOutputStream());
// serialize the object , and sending it to servlet , ticketData should implement Serializable interface.
ticketOutputToServlet .writeObject(ticketData);
ticketOutputToServlet .flush();
ticketOutputToServlet .close();
//reading back data from servlet
ObjectInputStream inputFromServlet = new ObjectInputStream(servletConnection.getInputStream());
Vector resultantData = (Vector) inputFromServlet.readObject();
String filename = (String) resultantData.elementAt(0)
//Showing the newly created page from Applet
getAppletContext().showDocument(new URL("http://www.jcom.com/profiles/" + filename));
How can i call another Servlet or JSP from the current Servlet ?
One of the previous methods for calling another servlet was
HelloServlet hello = (HelloServlet)getServletConfig().getServletContext().getServlet("hello");
From Servlet API version 2.1, this method has been deprecated and the preferred method is to use RequestDispatcher. Here is the syntax for it,
getServletContext().getRequestDispatcher("/jsp/hello/hello.jsp").forward(req, res);
HelloServlet hello = (HelloServlet)getServletConfig().getServletContext().getServlet("hello");
From Servlet API version 2.1, this method has been deprecated and the preferred method is to use RequestDispatcher. Here is the syntax for it,
getServletContext().getRequestDispatcher("/jsp/hello/hello.jsp").forward(req, res);
How can i reduce the number of writes to Client from Servlet ?
It is always recommended to use StringBuffer instead of String even for Concatenating a group of Strings. Avoid writing every small string to client. Instead store all the strings into a StringBuffer and after sufficient data is available, send this data to Browser.
Here is some sample code,
PrintWriter out =res.getWriter();
StringBuffer sb = new StringBuffer();
//concatenate all text to StringBuffer
sb.append("............. ")
res.setContentLength(sb.length());
out.print(sb);
Here is some sample code,
PrintWriter out =res.getWriter();
StringBuffer sb = new StringBuffer();
//concatenate all text to StringBuffer
sb.append("............. ")
res.setContentLength(sb.length());
out.print(sb);
How can i prevent Browser from Caching the Page content ?
Before sending the data to the browser, write thefollowing statements,
response.setHeader("Cache-Control","no-store");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0);
This also helps in case, when user should not beable to see previous pages by clicking the Back button in the browser. (Whenvery sensitive information is being displayed and someone else comes back tomachine and tries to see what data was entered)
response.setHeader("Cache-Control","no-store");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0);
This also helps in case, when user should not beable to see previous pages by clicking the Back button in the browser. (Whenvery sensitive information is being displayed and someone else comes back tomachine and tries to see what data was entered)
What are Good Ways of Debugging a Servlet ? Are are IDE's which support Servlet Debugging ?
There are couple of Methods. Firstly servers like JRun and others provide separate logs where all your Print requests will print their data into. For example requests to System.out. and System.err go to different log files. If this features is not available or you want to maintain logs separately for each module then you can create a static class called "LogWriter" and call the method inside the try catch loop. The print method in Log Writer will be writing to a custom defined Log File.
try
{ ....
}
catch(Exception exp)
{
LogWriter.print("Debug : The following error occurred at function .... ')
}
Also Inprise JBuilder supports Servlet Debugging. Please refer to JBuilder documentation for details.
Just as a Cautionary note, from your Servlets, never call System.exit(0). The results might be unpredictable. Might close down the entire Server. The Best way is to catch the Exception and either send resultant Error Page to the Browser or Write to a Log file and inform user about the Error.
try
{ ....
}
catch(Exception exp)
{
LogWriter.print("Debug : The following error occurred at function .... ')
}
Also Inprise JBuilder supports Servlet Debugging. Please refer to JBuilder documentation for details.
Just as a Cautionary note, from your Servlets, never call System.exit(0). The results might be unpredictable. Might close down the entire Server. The Best way is to catch the Exception and either send resultant Error Page to the Browser or Write to a Log file and inform user about the Error.
What is URL Encoding and URL Decoding ?
URL encoding is the method of replacing all the spaces and other extra characters into their corresponding Hex Characters and Decoding is the reverse process converting all Hex Characters back their normal form.
For Example consider this URL, /ServletsDirectory/Hello'servlet/
When Encoded using URLEncoder.encode("/ServletsDirectory/Hello'servlet/") the output is
http%3A%2F%2Fwww.javacommerce.com%2FServlets+Directory%2FHello%27servlet%2F
This can be decoded back using
URLDecoder.decode("http%3A%2F%2Fwww.javacommerce.com%2FServlets+Directory%2FHello%27servlet%2F")
For Example consider this URL, /ServletsDirectory/Hello'servlet/
When Encoded using URLEncoder.encode("/ServletsDirectory/Hello'servlet/") the output is
http%3A%2F%2Fwww.javacommerce.com%2FServlets+Directory%2FHello%27servlet%2F
This can be decoded back using
URLDecoder.decode("http%3A%2F%2Fwww.javacommerce.com%2FServlets+Directory%2FHello%27servlet%2F")
How do I get the name of the currently executing script?
Use req.getRequestURI() or req.getServletPath(). The former returns the path to the script including any extra path information following the name of the servlet; the latter strips the extra path info. For example:
URL http://www.javasoft.com/servlets/HelloServlet/jdata/userinfo?pagetype=s3&pagenum=4
getRequestURI ------------ servlets/HelloServlet/jdata/userinfo
getServletPath ------------ servlets/HelloServlet/
getPathInfo ------------ /jdata/userinfo
getQueryString ------------ pagetype=s3&pagenum=4
URL http://www.javasoft.com/servlets/HelloServlet/jdata/userinfo?pagetype=s3&pagenum=4
getRequestURI ------------ servlets/HelloServlet/jdata/userinfo
getServletPath ------------ servlets/HelloServlet/
getPathInfo ------------ /jdata/userinfo
getQueryString ------------ pagetype=s3&pagenum=4
Can you provide a sample Servlet ?
Here's the sample implementation of a Servlet to print "Welcome to the World of Servlets." on to the browser
class HelloServlet extends HttpServlet
{
/**
* Handle the HTTP GET method bybuilding a simple web page.
*/
public void doGet (HttpServletRequestrequest, HttpServletResponse response) throws
ServletException,IOException
{
PrintWriterout;
String title= "Hello Servlet";
//set content type and other response header fields first
response.setContentType("text/html");
// then write the data of the response
out =response.getWriter();
out.println("");
out.println(title);
out.println(" ");
out.println("
out.println("
class HelloServlet extends HttpServlet
{
/**
* Handle the HTTP GET method bybuilding a simple web page.
*/
public void doGet (HttpServletRequestrequest, HttpServletResponse response) throws
ServletException,IOException
{
PrintWriterout;
String title= "Hello Servlet";
//set content type and other response header fields first
response.setContentType("text/html");
// then write the data of the response
out =response.getWriter();
out.println("
out.println(title);
out.println("
out.println("
"+ title + "
");out.println("
Welcometo the World of Servlets.");
out.println("");
out.close();
}
}
How can i set Class Path for my Servlets ?
For developing servlets, just make sure that the JAR filecontaining javax.servlet.* is in your CLASSPATH, and use your normal development tools
How do I pass arguments to the Servlets?
Arguments to the servlets can be passed at two levels.
When a client is invoking the servlet, the client can pass the arguments as part of a URL in form of name/value pairs in the query string portion of the URL. If a tag is used in the html language to invoke the servlet, the arguments can be passed through the param name construct:
The server administrator/web-master can pass arguments to the servlet at loading/intialization time by specifying the arguments as part of the server configuration. For Tomcat and JSWDK, edit the conf/web.xml file.
The required argument (parameter1 in this example ) can be retrieved this way, getServletContext().getAttribute( "paramater1")
When a client is invoking the servlet, the client can pass the arguments as part of a URL in form of name/value pairs in the query string portion of the URL. If a tag is used in the html language to invoke the servlet, the arguments can be passed through the param name construct:
The server administrator/web-master can pass arguments to the servlet at loading/intialization time by specifying the arguments as part of the server configuration. For Tomcat and JSWDK, edit the conf/web.xml file.
The required argument (parameter1 in this example ) can be retrieved this way, getServletContext().getAttribute( "paramater1")
How do I send email from my Servlet?
You have two options. The first is to write or find a Simple Mail Transfer Protocol (SMTP) implementation in Java. The second is to use the JavaMail API. You can Download the JavaMail from this site at http://java.sun.com/products/javamail
What are different methods in HttpServlet ? Also what are advantages of Get and POST methods?
There are two main methods by which data can be sent to Servlets. They are GET and POST. Here is the over view of sample Servlet and the methods youshould be over riding.
public abstract synchronized class HttpServlet extendsGenericServlet implements Serializable
{
protected void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// If from the Form, the data is submitted using GET method then this method
// is called. Also by default when this Servlet is called from Browser then this
// method is called.
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// If from the Form, the data is submitted using PUT method then this method is called
}
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// If you must respond to requestsmade by a client that is not using the
// HTTP protocol, you must use service(). You normally should never need
// to override this method, except in special cases.
}
}
If you want to support doPost and doGet from same servlet, then in either doPost or doGet method, which ever is getting called, call the other method using doGet(request, response) or doPost(request,response)
For security reasons if the data being submitted is sensitive, then it's always preferred to use POST method so that the elements don't shown up in URL. When submitted using GET, then all the elements get appended to the URL. If user clicks on a third party click and if that server is logging the Referrer, then the entire URL is saved, which will also have sensitive information.
Also there are limitations of amount of data that can be sent through GET method. Some Operating Systems have a limitation on the Max Length of the URL, which is normally 255 characters. If sending through GET method, then the total length of the target Servlet name and all parameters dataneed to be less than 255 characters.
public abstract synchronized class HttpServlet extendsGenericServlet implements Serializable
{
protected void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// If from the Form, the data is submitted using GET method then this method
// is called. Also by default when this Servlet is called from Browser then this
// method is called.
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// If from the Form, the data is submitted using PUT method then this method is called
}
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// If you must respond to requestsmade by a client that is not using the
// HTTP protocol, you must use service(). You normally should never need
// to override this method, except in special cases.
}
}
If you want to support doPost and doGet from same servlet, then in either doPost or doGet method, which ever is getting called, call the other method using doGet(request, response) or doPost(request,response)
For security reasons if the data being submitted is sensitive, then it's always preferred to use POST method so that the elements don't shown up in URL. When submitted using GET, then all the elements get appended to the URL. If user clicks on a third party click and if that server is logging the Referrer, then the entire URL is saved, which will also have sensitive information.
Also there are limitations of amount of data that can be sent through GET method. Some Operating Systems have a limitation on the Max Length of the URL, which is normally 255 characters. If sending through GET method, then the total length of the target Servlet name and all parameters dataneed to be less than 255 characters.
How can get the entire URL of the current Servlet ?
The following code fragment will return the entire URL of the current Servlet
String currentFile = request.getRequestURI();
if (request.getQueryString() != null)
{
currentFile = currentFile + '?' + request.getQueryString();
}
URL currentURL = new URL(request.getScheme(),
request.getServerName(), request.getServerPort(), currentFile);
out.println(URL.toString());
String currentFile = request.getRequestURI();
if (request.getQueryString() != null)
{
currentFile = currentFile + '?' + request.getQueryString();
}
URL currentURL = new URL(request.getScheme(),
request.getServerName(), request.getServerPort(), currentFile);
out.println(URL.toString());
What are the Servlets Equivalents of CGI for commonly requested variables?
SERVER_NAME =request.getServerName();
SERVER_SOFTWARE =request.getServletContext().getServerInfo();
SERVER_PROTOCOL =request.getProtocol();
SERVER_PORT =request.getServerPort()
REQUEST_METHOD =request.getMethod()
PATH_INFO =request.getPathInfo()
PATH_TRANSLATED =request.getPathTranslated()
SCRIPT_NAME =request.getServletPath()
DOCUMENT_ROOT =request.getRealPath("/")
QUERY_STRING =request.getQueryString()
REMOTE_HOST =request.getRemoteHost()
REMOTE_ADDR =request.getRemoteAddr()
AUTH_TYPE =request.getAuthType()
REMOTE_USER =request.getRemoteUser()
CONTENT_TYPE =request.getContentType()
CONTENT_LENGTH =request.getContentLength()
HTTP_ACCEPT =request.getHeader("Accept")
HTTP_USER_AGENT =request.getHeader("User-Agent")
HTTP_REFERER = request.getHeader("Referer")
SERVER_SOFTWARE =request.getServletContext().getServerInfo();
SERVER_PROTOCOL =request.getProtocol();
SERVER_PORT =request.getServerPort()
REQUEST_METHOD =request.getMethod()
PATH_INFO =request.getPathInfo()
PATH_TRANSLATED =request.getPathTranslated()
SCRIPT_NAME =request.getServletPath()
DOCUMENT_ROOT =request.getRealPath("/")
QUERY_STRING =request.getQueryString()
REMOTE_HOST =request.getRemoteHost()
REMOTE_ADDR =request.getRemoteAddr()
AUTH_TYPE =request.getAuthType()
REMOTE_USER =request.getRemoteUser()
CONTENT_TYPE =request.getContentType()
CONTENT_LENGTH =request.getContentLength()
HTTP_ACCEPT =request.getHeader("Accept")
HTTP_USER_AGENT =request.getHeader("User-Agent")
HTTP_REFERER = request.getHeader("Referer")
How can i delete or set max duration for which Cookie exists?
You can set the maximum age of a cookie with the cookie.setMaxAge(int seconds) method: Here are different options to this method,
Zero means to delete the cookie
A positive value is the maximum number of seconds the cookie will live, before it expires
A negative value means the cookie will not be stored beyond this browser session (deleted on browser close)
Here is a sample code to delete cookie.
private void deleteCookie(String cookieName)
{
Cookie[] cookies =request.getCookies();
if (cookies != null)
{
for (int i=0; i {
if (cookies[i].getName().equals(cookieName));
cookies[i].setMaxAge(0);
}
}
}
Zero means to delete the cookie
A positive value is the maximum number of seconds the cookie will live, before it expires
A negative value means the cookie will not be stored beyond this browser session (deleted on browser close)
Here is a sample code to delete cookie.
private void deleteCookie(String cookieName)
{
Cookie[] cookies =request.getCookies();
if (cookies != null)
{
for (int i=0; i
if (cookies[i].getName().equals(cookieName));
cookies[i].setMaxAge(0);
}
}
}
How to confirm that user's browser accepted the Cookie ?
There's no direct API to directly verify that user's browser accepted the cookie. But the quick alternative would be, after sending the required data tothe users browser, redirect the response to a different Servlet which would try to read back the cookie. If this Servlet is able to read back the cookie, then it was successfully saved, else user had disabled the option to accept cookies.
What are Cookies and how to use them?
A cookie is a bit of information sent by the Web server that can later be read back from the browser. Limitations for cookies are, browsers are only required to accept 20 cookies per site, 300 total per user , and they can limit each cookie's size to 4096 bytes (4K).
Cookie cookie = new Cookie("userId", "28764"); //Creating new Cookie
response.addCookie (cookie); // sending cookie to the browser
// Printing out all Cookies
Cookie[] cookies = request.getCookies();
if (cookies != null)
{
for (int i=0; i {
String name = cookies[i].getName();
String value = cookies[i].getValue();
}
}
Note : If you want to save special characters like "=", or spaces, in the value of the cookie, then makesure you URL encode the value of the cookie , before creating a cookie.
Cookie cookie = new Cookie("userId", "28764"); //Creating new Cookie
response.addCookie (cookie); // sending cookie to the browser
// Printing out all Cookies
Cookie[] cookies = request.getCookies();
if (cookies != null)
{
for (int i=0; i
String name = cookies[i].getName();
String value = cookies[i].getValue();
}
}
Note : If you want to save special characters like "=", or spaces, in the value of the cookie, then makesure you URL encode the value of the cookie , before creating a cookie.
What is the Max amount of information that canbe saved in a Session Object ?
As such there is no limit on the amount of information that can be saved in a Session Object. Only the RAM available on the server machine is the limitation. The only limit is the Session ID length(Identifier) , which should not exceed more than 4K. If the data to be store is very huge, then it's preferred to save it to a temporary file onto hard disk, rather than saving it in session. Internally if the amount of data being saved in Session exceeds the predefined limit, most of the servers write it to a temporary cache on Hard disk.
How to create Session object and use it for storing information ?
This code will get the Session context for the current user and place values of count1 and count2 into MyIdentifier1 and MyIdentifier2 respectively
HttpSession session = req.getSession(true); //Creating a Session instance
session.putValue ("MyIdentifier1",count1); // Storing Value into session Object
session.putValue ("MyIdentifier2", count2);
session.getValue(MyIdentifier1); // Prints value of Count
session.removeValue(MyIdentifier1); // Removing Valuefrom Session Object
HttpSession session = req.getSession(true); //Creating a Session instance
session.putValue ("MyIdentifier1",count1); // Storing Value into session Object
session.putValue ("MyIdentifier2", count2);
session.getValue(MyIdentifier1); // Prints value of Count
session.removeValue(MyIdentifier1); // Removing Valuefrom Session Object
What is a Session Object ?
Session Object is used to maintain a user session related information on the Server side. You can store , retrieve and remove information from a Session object according to your program logic. A session object created for each user persists on the server side, either until user closes the browser or user remains idle for the session expiration time, which is configurable on each server.
How do I get authentication with myServlet?
Many popular Servlet engines offer Servlet authentication and the API has a call HttpServletRequest.getUserName() which is responsible for returning the username of an authenticated user.
How do I connect to a database from my Servlet?
Java includes support for databases, using Java Database Connectivity (JDBC). Most modern databases offer JDBC drivers, which allow you to connect any Java application (including Servlets) directly to your database.
If your database vendor does not offer a JDBC driver, and there are no third party drivers available, you may like to use a JDBC bridge. For example, the ODBC-JDBC bridge allows you to connect to any ODBC data source, which many databases support. Also there are four type of Drivers
Type I : JDBC-ODBC bridge
Type II : native-API partly JavaTM technology-enabled driver
Type III : net-protocol fully Java technology-enabled driver
Type IV : native-protocol fully Java technology-enabled driver
For a list of currently available Database drivers, please visit this page http://industry.java.sun.com/products/jdbc/drivers
Creating a new Connection to Database frequently could slow down your application. Most of the projects use a concept called Connection Pooling. Here when the Servlet starts up, in the init method , a pool of connections are created and are stored in memory (Mostly in a Vector). When a transaction with Database is required, then the next free available connection is retrieved from this Vector and used for that purpose. Once it's work is done, it is again put back into Connections Pool, indicating it is available. Today most of the JDBC Drivers support this feature have inbuilt connection pooling mechanisms.
Please Note : If you are creating your own Connection Pooling, it is strongly recommended to close all the open connections in the destroy method. Else there are chances of your data getting corrupted.
If your database vendor does not offer a JDBC driver, and there are no third party drivers available, you may like to use a JDBC bridge. For example, the ODBC-JDBC bridge allows you to connect to any ODBC data source, which many databases support. Also there are four type of Drivers
Type I : JDBC-ODBC bridge
Type II : native-API partly JavaTM technology-enabled driver
Type III : net-protocol fully Java technology-enabled driver
Type IV : native-protocol fully Java technology-enabled driver
For a list of currently available Database drivers, please visit this page http://industry.java.sun.com/products/jdbc/drivers
Creating a new Connection to Database frequently could slow down your application. Most of the projects use a concept called Connection Pooling. Here when the Servlet starts up, in the init method , a pool of connections are created and are stored in memory (Mostly in a Vector). When a transaction with Database is required, then the next free available connection is retrieved from this Vector and used for that purpose. Once it's work is done, it is again put back into Connections Pool, indicating it is available. Today most of the JDBC Drivers support this feature have inbuilt connection pooling mechanisms.
Please Note : If you are creating your own Connection Pooling, it is strongly recommended to close all the open connections in the destroy method. Else there are chances of your data getting corrupted.
Where can i find a good tutorial and more details on Servlets?
These URL's are a good starting point if you want to know more about Servlets.
http://java.sun.com/products/servlet/
http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets.html
Developing Applications using Servlets (Tutorial)
http://java.sun.com/products/servlet/
http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets.html
Developing Applications using Servlets (Tutorial)
What is the Jakarta Project ?
The goal of the Jakarta Project is to provide commercial-quality server solutions based on the Java Platform that are developed in an open and cooperative fashion. The flagship product, Tomcat, is a world-class implementation of the Java Servlet 2.2 and JavaServer Pages 1.1Specifications. This implementation will be used in the Apache Web Server as well as in other web servers and development tools." (The Apache Software Foundation).
What is the Advantage of using Servlets over CGI programming?
Servlets are only instantiated when the client first accesses the program. That is, the first time any client hits the URL that is used to access the Servlet, the Servlet engine instantiates that object. All subsequent accesses are done to that instance. This keeps the response time of Servlets lower than that of CGI programs, which must be run once per hit. Also, because a Servlet is instantiated only once, all accesses are put through that one object. This helps in maintaining objects like internal Connection Pooling or user session tracking and lots of other features.
Here are a few more of the many applications for Servlets:
1. Allowing collaboration between people. A Servlet can handle multiple requests concurrently, and can synchronize requests. This allows Servlets to support systems such as on-line conferencing.
2. Forwarding requests. 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 type or organizational boundaries.
Here are a few more of the many applications for Servlets:
1. Allowing collaboration between people. A Servlet can handle multiple requests concurrently, and can synchronize requests. This allows Servlets to support systems such as on-line conferencing.
2. Forwarding requests. 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 type or organizational boundaries.
What are Servlets and how can they help in developing Web Applications?
"Servlets are modules that extend request/response-oriented servers, such as Java-enabled web servers. For example, a servlet might 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 to servers what applets are to browsers. Unlike applets, however, servlets have no graphical user interface. Servlets can be embedded in many different servers because the servlet API, which you use to write servlet assumes nothing about the server's environment or protocol. Servlets have become most widely used within HTTP servers; many web servers support the Servlet API.
Subscribe to:
Posts (Atom)