Make delicious recipes!

Compiling Servlet based classes

Servlet based classes have the following form:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;


public class SendRedirectServlet extends HttpServlet {

    protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html");

        PrintWriter pw  = response.getWriter();
        String name     = request.getParameter("username");
        String password = request.getParameter("password");
        if (name.equals("James") && password.equals("abc"))
        {
            response.sendRedirect("/SendRedirect/ValidUserServlet");
        } else 
        {
            pw.println("You are not a valid user");
        }
    }

}

The javax packages are not part of standard JDK.
So to compile them, CLASSPATH for them have to be explicitly added.
Search for servlet-api.jar file and add its path to CLASSPATH, if you are using Tomcat.

For other webservers, path of following files should be looked up:

Sun Application Server : j2ee.jar
Bea Systems - Web Logic : weblogic.jar
WebSphere App. Server : j2ee.jar



Directory structure for placing (deploying) a new Servlet into Web-Server
Create a folder “my_new_servlet” under .../Tomcat 6.0/webapps/ and make sure it has the following structure:
 my_new_servlet
 |--- WEB-INF
 |----- web.xml (Copy an existing one and make changes for current servlet)
 |----- classes (Folder which contains compiled servlet classes)


A simple application using HTML and Servlets Client HTML form:

<form method="GET" action="/htmlform/LoginServlet">

    <p>
    Username  <input type="text" name="username" size="20">
    </p>

    <p>
    Password  <input type="text" name="password" size="20">
    </p>

    <p>
    <input type="submit" value="Submit" name="B1">
    </p>

</form>

Servlet Code
public class LoginServlet extends HttpServlet{

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html");

        PrintWriter out = response.getWriter();
        String name = request.getParameter("username");
        String pass = request.getParameter("password");

        out.println("<html>");
        out.println("<body>");
        out.println("Thanks Mr." + " " + name + " " + "for visiting <br>" );
        out.println("</body></html>");

    }
}





Like us on Facebook to remain in touch
with the latest in technology and tutorials!


Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Name:
Email: (Your email is not shared with anybody)
Comment:

Facebook comments:

Site Owner: Sachin Goyal