Simple Example of Servlet and JSP

Just try out this basic servlet and JSP code. Follow the snippets below.

default.jsp


  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  3. <html>
  4. <head>
  5. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  6. <title>Insert title here</title>
  7. </head>
  8. <body>
  9. <form action="Login" method="post">
  10. <table border=0>
  11. <tr><td><p>Username</p></td><td><input type="text" name="name"></td></tr>
  12. <tr><td><p>Password</p></td><td><input type="password" name="pass"></td></tr>
  13. <tr><td></td><td><input type="submit" value="Login"></td></tr>
  14. </table>
  15. </form>
  16. </body>
  17. </html>
Login.java

  1. import java.io.IOException;
  2. import java.io.PrintWriter;
  3. import java.util.Date;

  4. import javax.servlet.ServletException;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;


  8. public class Login extends HttpServlet {
  9. private static final long serialVersionUID = 1L;
  10.        
  11.   
  12.     public Login() {
  13.         super();
  14.       
  15.     }


  16. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  17. // TODO Auto-generated method stub
  18. }

  19. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  20. response.setContentType("text/html");
  21. String name=request.getParameter("name");
  22. String pass=request.getParameter("pass");
  23. PrintWriter out=response.getWriter();
  24. if(name.equals("admin")&&pass.equals("admin"))
  25. {
  26. Date dt=new Date();
  27. out.println("<h1>Welcome : "+name);
  28. out.println("</h1>");
  29. out.println("<br>"+dt);
  30. }
  31. else
  32. {
  33. out.println("Username and password incorrect");
  34. request.getRequestDispatcher("default.jsp").include(request, response);
  35. }
  36. out.close();
  37. }

  38. }
That's it. Keep programming and enjoy :)

Pre-Requisites:

1.Eclipse - Download
2.Apache Tomcat Server - Download



Comments

Popular posts from this blog

How to Run Python Script in PM2 Server

Handling Performance Bottlenecks in Spring Applications

Retry in SprinBoot Application