Few Tips and Trick on Jsp and Servlet

On a web technology development using java programming language, we knew Servlet and Jsp. Servlet and Jsp came as presentation layer of a web application structure. Presentation layer is a layer which has responsibility to present view of processing result as the end of data flow process. When choosing servlet or jsp as a presentation layer, there’s must be some proper and suitable consideration referred to the purpose

Even though it’s just a presentation layer on a web application, Servlet and Jsp are also have some interest things to explore and use on our web application. Below are some tips and tricks which can be used on a Servlet and Jsp.

  1. Get parameter value from deployment descriptor(web.xml) using init Servlet method.

  2. Chek out this codes:

    public class SendMailServlet extends HttpServlet {
        private String smtpHost;
    
      public void init(ServletConfig config) throws ServletException {
        super.init(config);
        smtpHost = config.getInitParameter("smtpHost");
      }
     …………………………
    }
    

    Above code is a sample of a Send mail Servlet application. The process of send mail, must be need a SMTP Host as a server to send email in order to make email can be received to whom its send. In order to preventing hard-code, SMTP host name put it on a deployment descriptor (web.xml), so if there’s a change of a SMTP host name we don’t need to recode the source, recompile and redeploy the application, what we do is only change the value of a smtpHost parameter on web.xml and the application can run normally with a little modification.

    And of course below is cut code of a web.xml where the value of this parameter defined.

    <servlet>
            <servlet-name>sendMessage</servlet-name>
            <servlet-class>org.mojo.mail.web.servlet.SendMailServlet</servlet-class>
            <init-param>
                <param-name>smtpHost</param-name>
                <param-value>smtp.speed.net.id</param-value>
            </init-param>
    </servlet>
    

    And for the process flow are, when the first time this Servlet initialized and the application server will call the init method on this Servlet, and then this method will fill up the smtpHost variable with the value taken from the deployment descriptor where the Servlet defined.

  3. Using RequestDispatcher Interface to throw a process to another servlet.

  4. Its become an interesting chosen, when we made a scenario that each servlet will handling each different task. Such as there’s a Servlet which only handle send mail process, or a Servlet which only handle displaying error message, etc. with this type of scenario, we will be able to trace error, that’s possible to happen on a process flow, because each process have a different module.

    With this kind of scenario, we must need a throw of a process from one servlet to another servlet.To throw a process from one servlet to another servlet, we can use a RequestDispatcher interace. Chek out these codes:

    public class Test1Servlet extends HttpServlet{
    
         public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
            System.out.println("doGetInvoked");
            throwToServlet(req, res);
           }
        public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
            System.out.println("doPost Invoked");
            throwToServlet(req,res);
           }
        private void throwToServlet(HttpServletRequest req, HttpServletResponse res)
             throws IOException, ServletException {
            System.out.println("This Process wil throw to another servlet");
            RequestDispatcher rd = getServletContext().getNamedDispatcher("Test2");
            rd.forward(req,res);
          }
    }
    

    On above servlet class codes we can see there’s a line

    RequestDispatcher rd = getServletContext().getNamedDispatcher(“Test2”);

    This line is a line where the servlet will get ServletContext that declared on web.xml, and this line followed by below line

    rd.forward(req,res);

    and this line is a line which telling the application to throw a process to another servlet named Test2.

    Practically, don’t forget to add servlet Test2 definition on web.xml

    And if we want to throw the process flow to another servlet, but the thrown came from jsp, we do little modification of the line, so the changes will be look like below:

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <%
      RequestDispatcher rd = getServletConfig().getServletContext().getNamedDispatcher("Test2");
      rd.forward(request,response);
    %>
    

    There’s an addition of a getServletConfig methods on initialized line of RequestDispatcher interface, and for the parameter of forward method is fill up with request and response that default on jsp class.

  5. Using sendRedirect method to throw a process to another URL.

    If on 2nd trick we used RequestDispatcher interface to throw a process to another servlet, in this trick we will use sendRedirect method to throw a process to another URL. The differences about this trick with 2nd trick is the 2nd trick only throw a process to a servlet that located at the same web-app context, while this trick it’s not just throwing a process to same web-app context but also throw using cross URL or different URL.

    To throw a process to another URL, please take a look below codes:

    public class Test1Servlet extends HttpServlet{
    
         public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
            System.out.println("doGetInvoked");
            throwToURL(req,res);
           }
        public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
            System.out.println("doPost Invoked");
            throwToURL(req,res);
           }
         private void throwToURL (HttpServletRequest req, HttpServletResponse res)
             throws IOException, ServletException {
            System.out.println("This Process wil throw to another URL");
            res.sendRedirect("Test2");
          }
    }
    

    On the above code, a line that telling the system to throw a process to another URL is appeared on res.sendRedirect(“Test2”);

    And if we want to do it on jsp, just modify the word res.sendRedirect into response.sendRedirect. Because once again, response variable already set by default on jsp file type, so we don’t have to make a variable for the ServletReponse class. The last but not least, of course, the URL-Mapping for this Test2 have to be declared on web.xml, except the target URL is not on our web-app context.

    Notes : The differences between 2nd tips and this tips from browser side is: the URL address on the 2nd trick didn’t change when the throwing process executed, while in this trick the URL address will change.

  6. Handling Null Value when parse out the parameter on HTTP Method.

  7. On HTTP Post or HTTP Get process, jsp will parse all the parameter that thrown from a form and then the other process will be executed after all the parameters defined. Some times when we parse the parameter on Jsp, we often have Null Value and that can cause the process is unable to continue, because jsp catch NullPointerException. Practically Null Value happens because the parameter that will parse didn’t bring a value form its feeder. So when the parse process executed, NullPointerException Error catch. To prevent this, we can make a default value for a variable that will responsible to carry out the value of parsed parameter.

    Please take a look below codes:

    <%
    String sId = request.getParameter("ID") == null ? "1" : request.getParameter("ID").trim();
    String sName= request.getParameter("Name") == null ? "" : request.getParameter("Name");
    %>
    

    On the above codes, we can see that String sId will be filled up by the value of parsed ID parameter, if the thrown ID parameter have Null value, then by default sId variable will be filled up with value 1. And its also happen with a catching process of Name parameter, but this parameter will fill up with the “” value if the value is not bound in the Name parameter.

And that’s it, few tips and tricks on servlet and jsp which become our discussion this time. I hope this helpful, and please you can use it for your own need.

 

Menteng, 18 Januari 2008

I Hope this will helpfull.

 

Josescalia.

One thought on “Few Tips and Trick on Jsp and Servlet

  1. Pingback: Few Tips and Trick on Jsp and Servlet | XML Developer

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s