mudah servlet example

contoh mudah servlet example The welcome Servlet class
Copy the following code into WelcomeServlet.java file and save it under servlet-example/WEB-INF/src/jsptube/tutorials/servletexample directory.
Note: it is not necessary to crate /src directory under WEB-INF directory and you can safely exclude WEB-INF/src directory when creating WAR file. You can put the source files any where you want, but don’t forget to put the compiled classes into WEB-INF/classes directory before creating the WAR file.
package jsptube.tutorials.servletexample;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class WelcomeServlet extends HttpServlet {

@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
* Get the value of form parameter
*/
String name = request.getParameter("name");
String welcomeMessage = "Welcome "+name;
/*
* Set the content type(MIME Type) of the response.
*/
response.setContentType("text/html");

PrintWriter out = response.getWriter();
/*
* Write the HTML to the response
*/
out.println("");
out.println("");
out.println("");
out.println("");
out.println("");
out.println("

"+welcomeMessage+"

");
out.println(""+"Click here to go back to input page "+"");
out.println("");
out.println("");
out.close();

}


public void destroy() {

}
}
Now compile the servlet class as explained below.
Open the command prompt and change the directory to the servlet-example/WEB-INF/src/jsptub/tutorials/servletexample directory. Compile the WelcomeServlet.java using the following command. javac WelcomeServlet.java It will create the file WelcomeServlet.class in the same directory. Copy the class file to classes directory. All the Servlets and other classes used in a web application must be kept under WEB-INF/classes directory.
Note: to compile a servlet you need to have servlet-api.jar file in the class path.
Bookmark and Share

0 comments:

Post a Comment