Sunday, 9 March 2008

develop, deploy and run java servlet

///////////1. Java Class ///////////////////////////
If you are not using Java EE SDK, you must download Java Servlet Api:servlet-2_5-api.jar, than put it in the classpath.

// HW.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HW extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<-html->");
out.println("<-head->");
out.println("<-title->Hello World!<-/title->");
out.println("<-/head->");
out.println("<-body->");
out.println("<-h1->Hello World!<-/h1->");
out.println("<-h1->By Cross<-/h1->");
out.println("<-/body->");
out.println("<-/html->");
}
}


/////////// Deploy it ///////////////////////////////
Put the class in \Tomcat\webapps\ROOT\WEB-INF\classes
Edit web.xml by append following 'xml' element.

// web.xml in \Tomcat\webapps\ROOT\WEB-INF
<-servlet->
<-servlet-name->myHelloWorld<-/servlet-name->
<-servlet-class->HW<-/servlet-class->
<-/servlet->
<-servlet-mapping->
<-servlet-name->myHelloWorld<-/servlet-name->
<-url-pattern->/myHello<-/url-pattern->
<-/servlet-mapping->

////////// Run it ///////////////////////////////////
Start Tomcat, then run it like this:
http://localhost/myHello

P.S.: use '<' and '>' to replace '<-' and '->' to escape Blogspot parsing html tag.
How getParameters from request, see here:
http://java.sun.com/developer/technicalArticles/RMI/rmi/
http://www.experts-exchange.com/Programming/Languages/Java/J2EE/Servlets/Q_22996074.html?eeSearch=true

No comments:

My photo
London, United Kingdom
twitter.com/zhengxin

Facebook & Twitter