Simple Example of Servlet and JSP
Just try out this basic servlet and JSP code. Follow the snippets below.
- <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
- <!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=ISO-8859-1">
- <title>Insert title here</title>
- </head>
- <body>
- <form action="Login" method="post">
- <table border=0>
- <tr><td><p>Username</p></td><td><input type="text" name="name"></td></tr>
- <tr><td><p>Password</p></td><td><input type="password" name="pass"></td></tr>
- <tr><td></td><td><input type="submit" value="Login"></td></tr>
- </table>
- </form>
- </body>
- </html>
Login.java
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.util.Date;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- public class Login extends HttpServlet {
- private static final long serialVersionUID = 1L;
- public Login() {
- super();
- }
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- // TODO Auto-generated method stub
- }
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- response.setContentType("text/html");
- String name=request.getParameter("name");
- String pass=request.getParameter("pass");
- PrintWriter out=response.getWriter();
- if(name.equals("admin")&&pass.equals("admin"))
- {
- Date dt=new Date();
- out.println("<h1>Welcome : "+name);
- out.println("</h1>");
- out.println("<br>"+dt);
- }
- else
- {
- out.println("Username and password incorrect");
- request.getRequestDispatcher("default.jsp").include(request, response);
- }
- out.close();
- }
- }
That's it. Keep programming and enjoy :)
Pre-Requisites:
1.Eclipse - Download
2.Apache Tomcat Server - Download
Comments
Post a Comment