How To Create Servlet

How to create Servlet or call servlet
step 1:
create a index.jsp file or index.html file and make a form.
index.jsp
<%@ page language=”java” contentType=”text/html; charset=UTF-8″
pageEncoding=”UTF-8″%>
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>Insert title here</title>
</head>
<body>
<form action=”Display” method=”post”>
first name:<input type=”text” name=”firstName”><br>
last name:<input type=”text” name=”lastName” ><br>
<input type=”submit” value=”submit”>
</form>
</body>
</html>
 
Step 2:
Now create a servlet display.java
Display.java

package com.jsp.test;

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

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

public class Display extends HttpServlet{

/**
*
*/
private static final long serialVersionUID = 5346650776384140650L;

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String firstNAme=request.getParameter(“firstName”);
String lastName=request.getParameter(“lastName”);
PrintWriter out=response.getWriter();
out.print(“Welcome”+”  “+firstNAme+”  “+lastName);
out.close();
}

}

Step 3:
configure web.xml
web.xml

<?xml version=”1.0″ encoding=”UTF-8″?>
<web-app xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns=”http://java.sun.com/xml/ns/javaee” xmlns:web=”http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd” xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd” id=”WebApp_ID” version=”3.0″>
<display-name>JSP</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>Display</servlet-name>
<servlet-class>com.jsp.test.Display</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Display</servlet-name>
<url-pattern>/Display</url-pattern>
</servlet-mapping>

</web-app>

Leave a Reply

Your email address will not be published. Required fields are marked *

+ 63 = 68