Monday, May 8, 2017

Servlet Example 1


Servlet Example: Simple servlet

  • Open eclipse 
  • Go to file -> new -> Dynamic web project
  • Provide name "ServletLoginApp" then next Check Deployment descriptor, then next -> finish
  • Create index.jsp inside WebContent

Add Tomcat to eclipse:

  • install tomcat on your system.
  • Go to server 
  • add server
  • select tomcat8
  • browser tomcat home in your machine

Index.jsp

<%@ 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>Servlet example</title>
</head>
<body>
<h1>Welcome to servlet example</h1>
<a href="login">Login</a>

</body>
</html>

Add Jar

javax.servlet-api-3.1.0.jar to WebContent/WEB-INF/lib

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"
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>ServletLoginApp</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>LoginServlet</servlet-name>
<servlet-class>com.masterjee.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>

</web-app>

Servlet: LoginServlet 

package com.masterjee;

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

public class LoginServlet extends HttpServlet{

    public void doGet(HttpServletRequest request, HttpServletResponse response){
        System.out.println("Welcome to Servlet");
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response){
        
    }
}

Write Click on your project , run as server

Eclipse:



Output on console: Welcome to servlet

Running from browser:



No comments:

Post a Comment