0% found this document useful (0 votes)
9 views8 pages

Servlet Examples

The document outlines the creation of three web applications using servlets in Java. The first application demonstrates the servlet lifecycle with a LifeCycleDemoServlet, the second greets users with a GreetingServlet, and the third implements a login system using a LoginServlet with initialization parameters for database connection. Each application includes necessary HTML forms, servlet configurations in web.xml, and Java servlet code for handling requests and responses.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views8 pages

Servlet Examples

The document outlines the creation of three web applications using servlets in Java. The first application demonstrates the servlet lifecycle with a LifeCycleDemoServlet, the second greets users with a GreetingServlet, and the third implements a login system using a LoginServlet with initialization parameters for database connection. Each application includes necessary HTML forms, servlet configurations in web.xml, and Java servlet code for handling requests and responses.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Program 9:

Write an web application to show the servlet lifecycle

/servletlifecycle/WEB-INF/web.xml:

<web-app>
<servlet>
<servlet-name>LCDS</servlet-name>
<servlet-class>LifeCycleDemoServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>LCDS</servlet-name>
<url-pattern>/lifecycle</url-pattern>
</servlet-mapping>
</web-app>

/servletlifecycle/WEB-INF/classes/ LifeCycleDemoServlet.java:

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;

public class LifeCycleDemoServlet implements Servlet {

private ServletConfig config;


// Initialization method

public void init(ServletConfig config) throws


ServletException {
this.config = config;
System.out.println("Servlet is being initialized using
init()");
}

// Service method - called for each request

public void service(ServletRequest request,


ServletResponse response)
throws ServletException, IOException {
System.out.println("Request is being serviced using
service()");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h2>Hello from
LifeCycleDemoServlet</h2>");
out.println("<p>This servlet demonstrates the life
cycle methods.</p>");
out.println("</body></html>");
}

// Destruction method

public void destroy() {


System.out.println("Servlet is being destroyed using
destroy()");
}
public ServletConfig getServletConfig() {
return this.config;
}
public String getServletInfo() {
return "LifeCycleDemoServlet version 1.0";
}

}Compilation:

Javac LifeCycleDemoServlet.java
Program 10:

Write an web application to greet the user

/wishex/greeting.html:

<!DOCTYPE html>
<html>
<head>
<title>Greeting Form</title>
</head>
<body>
<h2>Enter your name</h2>
<form action="greet" method="get">
<label for="username">Name:</label>
<input type="text" id="username" name="username"
required>
<br><br>
<input type="submit" value="Greet Me">
</form>
</body>
</html>
/wishex/WEB-INF/web.xml:

<web-app>
<servlet>
<servlet-name>GS</servlet-name>
<servlet-class>GreetingServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>GS</servlet-name>
<url-pattern>/greet</url-pattern>
</servlet-mapping>
</web-app>

/wishex/WEB-INF/classes/ GreetingServlet.java:

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;

public class GreetingServlet extends GenericServlet {

// Service method - called for each request

public void service(ServletRequest request,


ServletResponse response)throws ServletException, IOException
{
System.out.println("Request is being serviced using
service()");
// Get the username from the request
String name = request.getParameter("username");

// Set response content type


response.setContentType("text/html");

// Generate dynamic response


PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h2>Hello, " + name + "!</h2>");
out.println("<p>Welcome to the Greeting Servlet
Example.</p>");
out.println("</body></html>");
}

Compilation:

Javac GreetingServlet.java
Program 11:
Write an web application which uses servlet init parameters

/ loginex/login.html:

<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>User Login</h2>
<form action="login" method="get">
<label for="username">Username:</label>
<input type="text" name="username" id="username"
required><br><br>

<label for="password">Password:</label>
<input type="password" name="password" id="password"
required><br><br>

<input type="submit" value="Login">


</form>
</body>
</html>

/loginex/WEB-INF/web.xml:

<web-app>
<servlet>
<servlet-name>LS</servlet-name>
<servlet-class>LoginServlet</servlet-class>
<init-param>
<param-name>drivername</param-name>
<param-value>oracle.jdbc.driver.OracleDriver</param-
value>
</init-param>
<init-param>
<param-name>url</param-name>
<param-
value>jdbc:oracle:thin:@localhost:1521:XE</param-value>
</init-param>
<init-param>
<param-name>username</param-name>
<param-value>system</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>Password123</param-value>
</init-param>
</servlet>

<servlet-mapping>
<servlet-name>LS</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>

/loginex/WEB-INF/classes/ LoginServlet.java:

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class LoginServlet extends HttpServlet {

private Connection conn;


public void init() throws ServletException {
try {
// Read init parameters from web.xml
ServletConfig config = getServletConfig();
String driver =
config.getInitParameter("drivername");
String dbUrl = config.getInitParameter("url");
String dbUser =
config.getInitParameter("username");
String dbPassword =
config.getInitParameter("password");

// Load JDBC driver


Class.forName(driver);

// Establish connection
conn = DriverManager.getConnection(dbUrl, dbUser,
dbPassword);
System.out.println("Connection created in
init()");
} catch (Exception e) {
throw new ServletException("Database connection
failed: " + e.getMessage());
}
}

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {

String username = request.getParameter("username");


String password = request.getParameter("password");
response.setContentType("text/html");
PrintWriter out = response.getWriter();

try {
// Prepare SQL query
String query = "SELECT COUNT(*) FROM users WHERE
username = ? AND password = ?";
PreparedStatement ps =
conn.prepareStatement(query);
ps.setString(1, username);
ps.setString(2, password);

ResultSet rs = ps.executeQuery();
rs.next();
int count = rs.getInt(1);

if (count == 1) {
out.println("<html><body>");
out.println("<h2>Welcome, " + username +
"!</h2>");
out.println("</body></html>");
} else {
out.println("<html><body>");
out.println("<h2 style='color:red;'>Incorrect
username or password.</h2>");
out.println("<p><a href='login.html'>Try
again</a></p>");
out.println("</body></html>");
}

} catch (SQLException e) {
out.println("<h2>Database error: " +
e.getMessage() + "</h2>");
}
}

public void destroy() {


// Close DB connection
try {
if (conn != null && !conn.isClosed()) {
conn.close();
System.out.println("Database connection closed
in destroy()");
}
} catch (SQLException e) {
System.out.println("Error closing DB connection: "
+ e.getMessage());
}
}
}
Compilation:

Javac LoginServlet.java

You might also like