In: Computer Science
How do you schedule a Servlet to run, from an HTML file, when the User clicks on the Submit button? Show html code here
To run a Servlet from HTML page Request have to mapped to a backend (Servlet in our case). In HTML Page there will be button that will be used as a trigger to run the servlet. When you click Run servlet button request will be made to /MyServlet to resolve this mapping we have to make the entry to the web.xml with /MyServlet and map it to servlet named MyServlet. In MyServlet.java GET request will be received and the Output page will be generated as per output.print("...") statements written as HTML format. That page will be displayed by the Servlet file
>> INDEX.HTML:-
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content= "width=device-width">
<title>Running Servlet from HTML</title>
</head>
<body>
<h1>Scheduling a servlet from HTML Page</h1>
<hr>
<h3>This is a dummy form</h3>
<form action="MyServlet" method="get">
<input type="text" name="username" id="username"
placeholder="User Name"/> <br/><br/>
<input type="submit" Value="Run Servlet"></submit>
<br/><br/>
</form>
<hr>
</body>
</html>
>> 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_2_5.xsd" id="WebApp_ID"
version="2.5">
<display-name>index</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>MyServlet</display-name>
<servlet-name>MyServlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
</web-app>
>> MyServlet.java:-
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 MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter
output=response.getWriter(); //used to Write on a web
page
String
name=request.getparameter("username");
//Getting input from User Form Entry
output.print("<html><body>");
output.print("<h3>Hello "+
name+", this is called from a servlet</h3>");
output.print("</body></html>");
}
}
>> Output:-
.