Servlet is a web technology that is used to develop server-side web components.
Web components reside in server and perform the following:
Receive the incoming request data
Process the request
Prepare the HTML response
Servlets will be used to develop Dynamic Web application
One web application can have one or more web components like Servlets and JSPs.
One web container can have one or more web applications
One web server will have only one web container.
Client-Server |
Steps to develop and run the first Servlet 4.x based Web App.
1. Consider the login requirement.
Assignment |
2. Create the Dynamic Web Project in STS/eclipse as follows:
Select File->New->Dynamic Web Project
Project Name: Lab1
Click on New Runtime button (for the first time)
Select Apache Tomcat v9.0 and click on Next button
Browse the Tomcat Home Directory i.e D:\apache-tomcat-9.0.30
Click on the finish button
Click on the finish button
3. Observe the following Directory structure of Dynamic Web Project in STS.
4. Create login.html under the WebContent folder.
5. Create a package com.demo.servlets under Java Rsources>src
6. Create LoginServlet.java file in package com.demo.servlets.
7. Deploy into Tomcat 9 as follows
Right-click on Lab1
Select Run As->Run on Server
8. Open the Browser
9. Provide the following URL
http://localhost:8080/Lab1/login.html
Required Files
login.html
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="ISO-8859-1">
- <title>Insert title here</title>
- </head>
- <body>
- <form action="login.do">
- <h1>Account Login</h1>
- <p>Username</p>
- <input type="text" name="username"/>
- <p>Password</p>
- <input type="password" name="password"/>
- <p><input type ="submit" value="Login"/></p>
- </form>
- </body>
- </html>
- import java.io.IOException;
- import java.io.PrintWriter;
- import javax.servlet.ServletException;
- import javax.servlet.annotation.WebServlet;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- @WebServlet("/login.do")
- public class LoginServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
- protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- String username= request.getParameter("username");
- String password= request.getParameter("password");
- System.out.println(username);
- String message="";
- if(username.equals(password)) {
- message ="<h1>Welcome"+username+"<h1>";
- }else {
- message="<h1> Invalid username or password</h1>";
- }
- PrintWriter out = response.getWriter();
- out.write(message);
- out.flush();
- out.close();
- }
- }