Java Servlet Code
Rules available in this category:
- Reuse_data_sources_in_servlets
- Avoid_assigning_values_to_instance_field_without_acquiring_lock
- Avoid_assigning_values_to_static_instance_field_without_acquiring_lock
- Avoid_calling_Beans_instantiate_to_create_new_bean_instances
- Minimize_use_of_System_out_println_or_System_err_println
- Always_invalidate_local_HTTP_session_objects
- Use_context_objects_to_handle_HTTP_request_parameters
- Avoid_storing_non_serializable_object_into_HttpSession
- Avoid_using_SingleThreadModel
- Avoid_using_instance_variables_in_Servlets
- Do_not_declare_service_methods_synchronized
- Define_default_public_constructor_for_servlet
- Minimize_synchronization_in_servlets
Rule 1: Reuse_data_sources_in_servlets
Severity:
Medium
Rule:
Always reuse the data sources in servlets.
Reason:
Always reuse the data sources in servlets.
Usage Example:
package com.rule;
import java.io.IOException;
import java.sql.Connection;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
public class Reuse_data_sources_in_servlets_violation extends HttpServlet
{
protected void doPost(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException
{
try
{
InitialContext ic = new InitialContext();
DataSource dataSource = (DataSource)ic.lookup("jdbc/pool/OracleDS"); // VIOLATION
Connection connection = dataSource.getConnection();
// database handling
}
catch (Exception e)
{
// handle exception
}
}
}
Should be written as:
package com.rule;
import java.io.IOException;
import java.sql.Connection;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
public class Reuse_data_sources_in_servlets_correction extends HttpServlet
{
private DataSource dataSource;
public void init() throws ServletException
{
try
{
InitialContext ic = new InitialContext();
dataSource = (DataSource)ic.lookup("jdbc/pool/OracleDS"); // CORRECTION
}
catch (Exception e)
{
// handle exception
}
}
protected void doPost(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException
{
try
{
Connection connection = dataSource.getConnection();
// database handling
}
catch (Exception e)
{
// handle exception
}
}
}
Reference:
http://www.geocities.com/javabestpractices/servlet.html
http://www-306.ibm.com/software/webservers/appserv/ws_bestpractices.pdf
Rule 2: Avoid_assigning_values_to_instance_field_without_acquiring_lock
Severity:
Medium
Rule:
Since servlet instance fields are accessed by various threads, one should acquire a lock prior to assigning the field to avoid the common race conditions and data cross-over in J2EE applications.
Reason:
Since servlet instance fields are accessed by various threads, one should acquire a lock prior to assigning the field to avoid the common race conditions and data cross-over in J2EE applications.
Usage Example:
private String userId = Smith";
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException
{
PrintWriter out = res.getWriter();
HttpSession session = req.getSession();
String user = (String)session.getAttribute("name");
setUser(user);
// ...
out.println("<HTML><HEAD><TITLE>Servlet that writes to an instance field</TITLE></HEAD><BODY>");
out.println("UserId: "+userId+"</BODY></HTML>");
out.close();
session.invalidate();
}
private void setUser(String user)
{
userId = user; // VIOLATION
}
Should be written as:
private String userId = Smith";
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException
{
PrintWriter out = res.getWriter();
HttpSession session = req.getSession();
String user = (String)session.getAttribute("name");
setUser(user);
// ...
out.println("<HTML><HEAD><TITLE>Servlet that writes to an instance field</TITLE></HEAD><BODY>");
out.println("UserId: "+userId+"</BODY></HTML>");
out.close();
session.invalidate();
}
private void setUser(String user)
{
synchronized ( userId ) // CORRECTION
{
userId = user;
}
}
Reference:
No references available.
Rule 3: Avoid_assigning_values_to_static_instance_field_without_acquiring_lock
Severity:
Medium
Rule:
Since servlet static instance fields are accessed by various threads, one should acquire a lock prior to assigning the field to avoid the common race conditions and data cross-over in J2EE applications.
Reason:
Since servlet static instance fields are accessed by various threads, one should acquire a lock prior to assigning the field to avoid the common race conditions and data cross-over in J2EE applications.
Usage Example:
private static String userId = Smith";
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException
{
PrintWriter out = res.getWriter();
HttpSession session = req.getSession();
String user = (String)session.getAttribute("name");
setUser(user);
// ...
out.println("<HTML><HEAD><TITLE>Servlet that writes to an instance field</TITLE></HEAD><BODY>");
out.println("UserId: "+userId+"</BODY></HTML>");
out.close();
session.invalidate();
}
private void setUser(String user)
{
userId = user; // VIOLATION
}
Should be written as:
private static String userId = Smith";
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException
{
PrintWriter out = res.getWriter();
HttpSession session = req.getSession();
String user = (String)session.getAttribute("name");
setUser(user);
// ...
out.println("<HTML><HEAD><TITLE>Servlet that writes to an instance field</TITLE></HEAD><BODY>");
out.println("UserId: "+userId+"</BODY></HTML>");
out.close();
session.invalidate();
}
private void setUser(String user)
{
synchronized ( userId ) // CORRECTION
{
userId = user;
}
}
Reference:
No references available.
Rule 4: Avoid_calling_Beans_instantiate_to_create_new_bean_instances
Severity:
Medium
Rule:
Each time java.beans.Beans.instantiate is called the file system is checked for a serialized version of the bean.
Reason:
Each time java.beans.Beans.instantiate is called the file system is checked for a serialized version of the bean.
Usage Example:
import javax.servlet.http.*;
import java.beans.*;
public class MyServlet extends HttpServlet {
public void doGet (HttpServletRequest request) throws ClassNotFoundException
, java.io.IOException
{
Beans b = (Beans)Beans.instantiate (this.getClass ().getClassLoader ()
, "web_prmtv.Bean");// VIOLATION
}
}
Should be written as:
import javax.servlet.http.*;
import java.beans.*;
public class MyServlet extends HttpServlet {
public void doGet (HttpServletRequest request) throws ClassNotFoundException
, java.io.IOException
{
Beans b = new Beans (); // CORRECTION
}
}
Reference:
http://www-4.ibm.com/software/webservers/appserv/ws_bestpractices.pdf
Rule 5: Minimize_use_of_System_out_println_or_System_err_println
Severity:
Low
Rule:
These calls should not be used in production unless the outputs are redirected to a log file.
Reason:
These calls should not be used in production unless the outputs are redirected to a log file.
Usage Example:
import javax.servlet.*;
import javax.servlet.http.*;
public class MyClass extends HttpServlet
{
public void service ()
{
System.out.println ("Initiating Service"); // VIOLATION
}
}
Should be written as:
import javax.servlet.*;
import javax.servlet.http.*;
public class MyClass extends HttpServlet
{
private final static boolean DEBUG_ON = false;
public void service ()
{
if (DEBUG_ON)
{
System.out.println ("starting service"); // CORRECTION
}
}
}
Reference:
http://www-4.ibm.com/software/webservers/appserv/ws_bestpractices.pdf
Rule 6: Always_invalidate_local_HTTP_session_objects
Severity:
Medium
Rule:
Always invalidate local HTTP Session objects.
Reason:
Always invalidate local HTTP Session objects.
Usage Example:
import javax.servlet.*;
import javax.servlet.http.*;
public class AlwaysInvalidateLocalHTTPSessionObjects // VIOLATION
{
public void session (HttpServletRequest request)
{
HttpSession mySession = request.getSession (false);
String id = mySession.getId ();
System.out.println ( id );
}
}
Should be written as:
import javax.servlet.*;
import javax.servlet.http.*;
public class AlwaysInvalidateLocalHTTPSessionObjects
{
public void sessionFixed (HttpServletRequest request)
{
HttpSession mySession = request.getSession (false);
if (mySession != null)
{
String id = mySession.getId ();
System.out.println ( id );
mySession.invalidate (); // CORRECTION
}
}
}
Reference:
IBM WebSphere Application Server Standard and Advanced Editions
IBM WebSphere Application Server Standard and Advanced Editions - by Harvey W. Gunther Date: September 7, 2000
Rule 7: Use_context_objects_to_handle_HTTP_request_parameters
Severity:
Medium
Rule:
Use context objects to handle HTTP request parameters for loose coupling.
Reason:
Use context objects to handle HTTP request parameters for loose coupling.
Usage Example:
package examples.rules.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
public class UCO extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response
)
{
String first_name = request.getParameter("fname"); // VIOLATION
String last_name = request.getParameter("lname"); // VIOLATION
String email = request.getParameter("email"); // VIOLATION
}
}
Should be written as:
package examples.rules.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
public class UCOFixed extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response
)
{
RequestContextFactory requestContextFactory =
RequestContextFactory.getInstance();
RequestContext requestContext =
requestContextFactory.createRequestContext(request); // CORRECTION
String first_name = requestContext.getFirstName();
String last_name = requestContext.getLastName();
String email = requestContext.getEmail();
}
}
class RequestContextFactory
{
private static RequestContextFactory _rcf;
private RequestContextFactory() { }
static RequestContextFactory getInstance()
{
if (_rcf == null)
{
_rcf = new RequestContextFactory();
}
return _rcf;
}
RequestContext createRequestContext(ServletRequest request)
{
String fn = validate(request.getParameter("fname"));
String ln = validate(request.getParameter("lname"));
String email = validate(request.getParameter("email"));
return new RequestContext(fn, ln, email);
}
}
class RequestContext
{
private String _firstName;
private String _lastName;
private String _email;
RequestContext(String fn, String ln, String email)
{
_firstName = fn;
_lastName = ln;
_email = email;
}
final String getFirstName()
{
return _firstName;
}
final String getLastName()
{
return _lastName;
}
final String getEmail()
{
return _email;
}
}
Reference:
"Core J2EE Patterns - Best Practices and Design Strategies"
"Core J2EE Patterns - Best Practices and Design Strategies"
"Core J2EE Patterns - Best Practices and Design Strategies" - by Deepak Alur, John Cupri and Dan Malks. pp. 181
Rule 8: Avoid_storing_non_serializable_object_into_HttpSession
Severity:
Medium
Rule:
Avoid storing non serializable object into HttpSession.
Reason:
Avoid storing non serializable object into HttpSession.
Usage Example:
package com.rule;
import javax.servlet.http.HttpSession;
class Avoid_storing_non_serializable_object_into_HttpSession_violation
{
Myclass obj = new Myclass();
public void method ()
{
HttpSession session = request.getSession(true);
String name = "AppPerfect";
session.setAttribute(name, obj); //Violation.
}
}
class Myclass
{
// Class Variables ...
public Myclass()
{
// Initialising Class Variables ...
}
}
Should be written as:
package com.rule;
import javax.servlet.http.HttpSession;
class Avoid_storing_non_serializable_object_into_HttpSession_violation
{
Myclass obj = new Myclass();
public void method ()
{
HttpSession session = request.getSession(true);
String name = "AppPerfect";
session.setAttribute(name, obj);
}
}
class Myclass implements Serializable //Correction.
{
// Class Variables ...
public Myclass()
{
// Initialising Class Variables ...
}
}
Reference:
Reference Not Available.
Rule 9: Avoid_using_SingleThreadModel
Severity:
Medium
Rule:
Do not use SingleThreadModel for servlets.
Reason:
Do not use SingleThreadModel for servlets.
Usage Example:
package com.rule;
import javax.servlet.SingleThreadModel;
import javax.servlet.http.HttpServlet;
public class Avoid_using_SingleThreadModel_violation // VIOLATION
extends HttpServlet
implements SingleThreadModel
{
}
Should be written as:
Use other means like synchronized blocks to handle multi threading issues in servlets.
Reference:
http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/SingleThreadModel.html
http://www-306.ibm.com/software/webservers/appserv/ws_bestpractices.pdf
Rule 10: Avoid_using_instance_variables_in_Servlets
Severity:
Medium
Rule:
Avoid_using_instance_variables_in_Servlets.
Reason:
Avoid_using_instance_variables_in_Servlets.
Usage Example:
package com.rule;
import javax.servlet.GenericServlet;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
class Avoid_using_instance_variables_in_Servlets extends GenericServlet
{
String instanceMemberString = "Instance Member Variable"; // Violation.
public void service(ServletRequest req, ServletResponse res)throws IOException
{
}
}
Should be written as:
package com.rule;
import javax.servlet.GenericServlet;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
class Avoid_using_instance_variables_in_Servlets extends GenericServlet
{
public void service(ServletRequest req, ServletResponse res)throws IOException
{
String localVariableString = "Local Variable String"; // Correction.
}
}
Reference:
Reference Not Available.
Rule 11: Do_not_declare_service_methods_synchronized
Severity:
Medium
Rule:
Declaring the service methods synchronized will cause performance issues for the servlet.
Reason:
Declaring the service methods synchronized will cause performance issues for the servlet.
Usage Example:
package com.rule;
import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Do_not_declare_service_methods_synchronized_violation extends HttpServlet
{
protected synchronized void doPost(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException // VIOLATION
{
// implementation
}
}
abstract class Do_not_declare_service_methods_synchronized_violation_2 implements Servlet
{
public synchronized void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException // VIOLATION
{
}
}
Should be written as:
package com.rule;
import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Do_not_declare_service_methods_synchronized_correction extends HttpServlet
{
protected void doPost(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException // CORRECTION
{
// implementation
}
}
abstract class Do_not_declare_service_methods_synchronized_correction_2 implements Servlet
{
public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException // CORRECTION
{
}
}
Reference:
http://www.javapractices.com/Topic111.cjp
http://www.chongluo.com/books/xml/jxslt/ch06_05.htm
http://www.unix.org.ua/orelly/java-ent/servlet/ch03_01.htm
Rule 12: Define_default_public_constructor_for_servlet
Severity:
Medium
Rule:
Always define a default constructor for servlets.
Reason:
Always define a default constructor for servlets.
Usage Example:
package com.rule;
import javax.servlet.http.HttpServlet;
public class Define_default_public_constructor_for_servlet_violation extends HttpServlet // VIOLATION
{
protected Define_default_public_constructor_for_servlet()
{
}
}
Should be written as:
package com.rule;
import javax.servlet.http.HttpServlet;
public class Define_default_public_constructor_for_servlet_correction extends HttpServlet
{
public Define_default_public_constructor_for_servlet() // CORRECTOIN
{
}
}
Reference:
Reference Not Available.
Rule 13: Minimize_synchronization_in_servlets
Severity:
Medium
Rule:
Minimize the use of synchronized code in the servlets.
Reason:
Minimize the use of synchronized code in the servlets.
Usage Example:
package com.rule;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class Minimize_synchronization_in_servlets_violation extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
synchronized(this) // VIOLATION
{
Enumeration enum = request.getAttributeNames();
while(enum.hasMoreElements())
{
String attrName = (String) enum.nextElement();
doSomething(attrName);
}
HttpSession session = request.getSession();
session.setAttribute("attr1", "val1");
ServletContext servContext = session.getServletContext();
String info = servContext.getServerInfo();
response.getWriter().print(info);
}
}
private void doSomething(String obj)
{
}
}
Should be written as:
Minimize the code inside synchronized blocks.
Reference:
http://www-306.ibm.com/software/webservers/appserv/ws_bestpractices.pdf