Servlet Simple Example

 

Create the HTML file: index.html


<html>
 <head>
 <title>The servlet example </title>
 </head>
 <body>
  <h1>A simple web application</h1>
  <form method="POST" action="WelcomeServlet">
   <label for="name">Enter your name </label>
   <input type="text" id="name" name="name"/><br><br>
   <input type="submit" value="Submit Form"/>
   <input type="reset" value="Reset Form"/>
  </form>
 </body>
</html>

The welcome Servlet class

package nkpack.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("<html>");
out.println("<head>");
out.println("<title> A very simple servlet example</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>"+welcomeMessage+"</h1>");
out.println("<a href="/servletexample/index.html">"+"Click here to go back to input page "+"</a>");
out.println("</body>");
out.println("</html>");
out.close();
 
}
 
 
public void destroy() {
 
}
} 

The deployment descriptor (web.xml) file.

Copy the following code into web.xml file and save it directly under servlet-example/WEB-INF directory.
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 
 <servlet>
  <servlet-name>WelcomeServlet</servlet-name>
  <servlet-class>nkpack.servletexample.WelcomeServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>WelcomeServlet</servlet-name>
  <url-pattern>/WelcomeServlet</url-pattern>
 </servlet-mapping>
 <welcome-file-list>
  <welcome-file> /index.html </welcome-file>
 </welcome-file-list>
</web-app>
 
Know deploy and run

No comments:

Post a Comment