JavaBeat FAQs
FAVORITES
Download a movie FAQ
JAVABEAT
Home
Articles
Tips
QnA
Forums
FAQs Topics Books Topic
Java Java Books
Struts Struts Books
Spring Spring Books
Hibernate Hibernate Books
JBoss Seam Seam Books
J2EE J2EE Books
EJB EJB Books
JSF JSF Books
Servlets Servlets Books
JDBC JDBC Books
RMI RMI Books
JMS JMS Books
JNI JNI Books
Design Patterns Patterns Books
Exception Exception Books
Apache Ant Ant Books
Groovy
Cobertura
Quartz

Java Servlets Interview Questions

Java Servlet is the serverside Java programming language. We can say it as serverside applet. How applet is used for writing the client side code, servlet is used for writing the serverside programming language. Servlet programming is first created by Sun Microsystems in June 1997. The latest version is Servlet 2.5 which is released with JEE 5.0 specification. Servlet is a specification and it can be implemented by anyone who can fulfil the mandatory requirements of the specification maintained by Sun.

Servlet Articles

What is servlet?

Servlet Life Cycle

New Features in Servlet 3.0

 
Servlets FAQs - 1 | Servlets FAQs - 2 | Servlets FAQs - 3 | Servlets FAQs - 4 | Servlets FAQs - 5
Servlets FAQs - 6 | Servlets FAQs - 7 | Servlets FAQs - 8 | Servlets FAQs - 9 | Servlets FAQs - 10

41) How do I handle FORMs with multiple form elements (e.g. radio buttons) using the same name?
 

For radio buttons, the HTML spec assumes that a given group of buttons will have the same NAME and different VALUEs; the browser makes sure that only one button per group name will be selected (at most). So you can just call request.getParameter("groupname").

<input type="radio" name="topping" value="cheese" checked>Cheese



<input type="radio" name="topping" value="pepperoni">Pepperoni



<input type="radio" name="topping" value="anchovies">Anchovies



If the user selects "Pepperoni" then request.getParameter("topping") will return the string "pepperoni".

For lists using the <select multiple> FORM tag, multiple values can be returned for the same parameter name. When that can happen, use request.getParameterValues("param") which returns a String[] you can iterate through.

It's bad form (so to speak), but you can also duplicate other element types, like

Name 1: <input type="text" name="name" value="Dick">



Name 2: <input type="text" name="name" value="Jane">



These also get returned in an array by request.getParameterValues().

42) How do I separate presentation (HTML) from business logic (Java) when using servlets?
 

Almost anybody who has ever written a servlet can identify with this one. We all know it's bad for to embed HTML code in our java source; it's lame to have to recompile and re-deploy every time you want an HTML element to look a bit different. But what are our choices here? There are two basic options;

1. Use JSP: Java Server Pages allows you to embed Java code or the results of a servlet into your HTML. You could, for instance, define a servlet that gives a stock quote, then use the <servlet> tag in a JSP page to embed the output. But then, this brings up the same problem; without discipline, your content/presentation and program logic are again meshed. I think the ideal here is to completely separate the two.

2. Use a templating/parsing system: Hmm...I know you're about to rant about re-inventing the wheel, but it's not that bad (see below). Plus, it really does pay to take this approach; you can have a group of programmers working on the Java code, and a group of HTML producers maintaining the interface. So now you probably want to know how to do it...so read on.

Use SSI!
Remember SSI? It hasn't gotten much attention in recent years because of embeddable scripting languages like ASP and JSP, but it still remains a viable option. To leverage it in the servlet world, I believe the best way is to use an API called SSI for Java from Areane. This API will let you emulate SSI commands from a templating system, and much more. It will let you execute any command on any system, including executing java classes! It also comes with several utility classes for creating stateful HTML form elements, tables for use with iteration, and much more. It's also open source, so it's free and you can tweak it to your heart's content! You can read the SSI for Java documentation for detailed info, but the following is an example of its use.
Here's the servlet:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import com.areane.www.ssi.*;
 
public class SSITemplatingServlet extends HttpServlet {
   private String        templateFilesDirectory = "d:\\projects\\idemo\\templates\\"; //Holds path to template files
 
   /**Handles GET requests; defers every request to the POST processor*/
   public void doGet(HttpServletRequest req, HttpServletResponse res) 
                   throws ServletException, IOException, FileNotFoundException {doPost(req, res);}
 
   /**Handles all requests. Processes the request, 
     *saves the values, parses the file, then feeds the file to the out stream*/
   public void doPost(HttpServletRequest req, HttpServletResponse res) 
                   throws ServletException, IOException, FileNotFoundException {
                   HttpSession         ses                        = req.getSession(true);
                   
                   Properties context              = null;
                   if((context = (Properties)ses.getValue("user.context")) == null) { //if properties doesn't already exist, create it.
                                  context   = new Properties();
                   }
                   
                   //Write parameters to Properties object
                   Enumeration paramNames              = req.getParameterNames();
                   String curName, curVal;
                   while(paramNames.hasMoreElements()) {
                                  curName               = (String)paramNames.nextElement();
                                  curVal    = req.getParameter(curName);
                                  context.setProperty(curName, curVal);
                   }
 
                   //Save the values to the session
                   ses.putValue("user.context", context);
 
                   //Parse the page and stream to the client
                   String templateName         = req.getParameter("template"); // Get the file name of the template to use
                   res.setContentType("text/html");
                   SsiPage               page      = SsiParser.parse(this.templateFilesDirectory + templateName); //Parsing occurs here
                   page.write(res.getWriter(), context); //Stream to the client
                   
                   page = null; //clean up
   }
}


Now, just create a template file, pass the servlet the template file name, and have at it!

 

43) For an HTML FORM with multiple SUBMIT buttons, how can a servlet ond differently for each button?
 

The servlet will respond differently for each button based on the html that you have placed in the HTML page. Let's explain.

For a submit button the HTML looks like <input type=submit name="Left" value="left">. A servlet could extract the value of this submit by using the getParameter("Left") from the HttpRequest object. It follows then that if you have HTML within a FORM that appears as:

<input type=submit name="Direction" value="left"><br>
<input type=submit name="Direction" value="right"><br>
<input type=submit name="Direction" value="up"><br>
<input type=submit name="Direction" value="down"><br>

Then the getParameter("Direction") from the HttpRequest would extract the value pressed by the user, either "left", "right", "up" or "down". A simple comparision in the servlet with the these values could occur and processing based on the submit button would be performed.

Similiarly,for submit buttons with different names on a page, each of these values could be extracted using the getParameter() call and acted on. However, in a situation where there are multiple buttons, common practice would be to use one name and multiple values to identify the button pressed.

44) What is meant by the term "business logic"?
 

"Business logic" is just a fancy way of saying "code." :-)

More precisely, in a three-tier architecture, business logic is any code that is not specifically related to storing and retrieving data (that's "data storage code"), or to formatting data for display to the user (that's "presentation logic"). It makes sense, for many reasons, to store this business logic in separate objects; the middle tier comprises these objects. However, the divisions between the three layers are often blurry, and business logic is more of an ideal than a reality in most programs. The main point of the term is, you want somewhere to store the logic and "business rules" (another buzzword) of your application, while keeping the division between tiers clear and clean.

45) How can I explicitly unload a servlet or call the destroy method?
 

In general, you can't. The Servlet API does not specify when a servlet is unloaded or how the destroy method is called. Your servlet engine (ie the implementation of the interfaces in the JSDK) might provide a way to do this, probably through its administration interface/tool (like Webshpere or JWS). Most servlet engines will also destroy and reload your servlet if they see that the class file(s) have been modified.

46) What is a servlet bean?
 

A servlet bean is a serializable servlet that follows the JavaBeans component architecture, basically offering getter/setter methods.

As long as you subclass GenericServlet/HttpServlet, you are automatically Serializable.

If your web server supports them, when you install the servlet in the web server, you can configure it through a property sheet-like interface.

47) Why do we need to call super.init(config) in the init method of a servlet?
 

Just do as you're told and you won't get hurt! :-)

Because if you don't, then the config object will get lost. Just extend HttpServlet, use init() (no parameters) and it'll all work ok.

From the Javadoc: init() - A convenience method which can be overridden so that there's no need to call super.init(config).

48) What is a servlet engine?
 

A "servlet engine" is a program that plugs in to a web server and runs servlets. The term is obsolete; the preferred term now is "servlet container" since that applies both to plug-in engines and to stand-alone web servers that support the Servlet API.

49) Which is the most efficient (i.e. processing speed) way to create a server application that accesses a database: A Servlet using JDBC; a JSP page using a JavaBean to carry out the db access; or JSP combined with a Servlet? Are these my only choices?
 

Your question really should be broken in two.

1-What is the most efficient way of serving pages from a Java object?. There you have a clear winner in the Servlet. Althought if you are going to change the static content of the page often is going to be a pain because you'll have to change Java code. The second place in speed is for JSP pages. But, depending on your application, the difference in speed between JSP pages and raw servlets can be so small that is not worth the extra work of servlet programming.

2-What is the most efficient way of accessing a database from Java?. If JDBC is the way you want to go the I'd suggest to pick as many drivers as you can (II,III,IV or wathever) and benchmark them. Type I uses a JDBC/ODBC bridge and usually has lousy performance. Again, go for the simplest (usually type IV driver) solution if that meets you performance needs.

For database applications, the performance bottleneck is usually the database, not the web server/engine. In this case, the use of a package that access JDBC with connection pooling at the application level used from JSP pages (with or withouth beans as middleware) is the usual choice. Of course, your applications requirements may vary.

50) How can I change the port of my Java Web Server from 8080 to something else?


It is very simple. JAVA WEB SERVER comes with remote Web administration tool. You can access this with a web browser.

Administration tool is located on port 9090 on your web server. To change port address for web server:

1. Access tool (http://hostname:9090)
2. Enter User Id/Password (by default it is admin/admin)
3. Select service (Web service)
4. Click on "manage" button. You will get a popup screen with all settings.
5. Click on network tree node, On right hand side you will get text box for entering port no.
6. Change port number with desire one.
7. click on restart button.

Related Articles
JAX-WS Web Services in NetBeans 6.1
JPA in NetBeans 6.1
EJB 3.0 and WebServices
Types of Managed Bean scopes in Spring Framework
OpenCms 7 Development
Liferay Portal Enterprise Intranets
ZK Developer’s Guide : Online Media Library
The BIRT Environment and Your First Report
AJAX - The Complete Reference
The Java 6.0 Compiler API
more articles
java6 ejb3 jsf hibernate eclipse ajax groovy spring seam java struts webservice j2me guice java5 jca tapestry soa linux ria books

Favorites
Buy movies
Access Control
Busby seo challenge contest
Sohbet
Chat
Webmaster Hosting Forum
Java Jobs
MyVideoLib
India News
Internet Advances
Sohbet
chat
Latest QnA
SCJD Tips
When we start a thread by applying start() method on it ,how does it knows that to execute run()method?
About Wrapper class in Java
How to configure weblogic 7.0 in MyEclipse?
Static Block and Static Initializer in Java

JavaBeat Website (2004-2008), India
javabeat | about us | planetoss
Copyright (2004 - 2008), JavaBeat