0% found this document useful (0 votes)
4 views

Chapter 8 Servlet-1

Java Servlets are programs that operate on web servers, acting as a bridge between client requests and server resources, enabling dynamic web page generation. They handle HTTP requests through a defined life cycle involving initialization, request processing, and destruction, utilizing methods such as doGet() and doPost() for handling different request types. The document also covers servlet architecture, setup using Tomcat, and examples of handling form data using GET and POST methods.

Uploaded by

Tesfalegn Yakob
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)
4 views

Chapter 8 Servlet-1

Java Servlets are programs that operate on web servers, acting as a bridge between client requests and server resources, enabling dynamic web page generation. They handle HTTP requests through a defined life cycle involving initialization, request processing, and destruction, utilizing methods such as doGet() and doPost() for handling different request types. The document also covers servlet architecture, setup using Tomcat, and examples of handling form data using GET and POST methods.

Uploaded by

Tesfalegn Yakob
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/ 28

Chapter 8

Introduction to Servlets
What are Servlets?
Java Servlets are programs that run on a Web or Application server and act as a middle layer between
requests coming from a Web browser or other HTTP client and databases or applications on the
HTTP server.

Using Servlets, you can collect input from users through web page forms, present records to a database
or another source, and create web pages dynamically.

Servlets Architecture:
Following diagram shows the position of Servelts in a Web Application.

Servlets Tasks:
Servlets perform the following major tasks:
 Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web
page or it could also come from an Applet or a custom HTTP client program.
 Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media
types and compression schemes the browser understands, and so forth.
 Process the data and generate the results. This process may require talking to a database,
invoking a Web service, or computing the response directly.

1
 Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent in
a variety of formats, including text (HTML or XML), GIF images, Excel, etc.
 Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or
other clients what type of document is being returned (e.g., HTML), setting cookies and caching
parameters, and other such tasks.

Servlets Packages:
Java Servlets are Java classes run by a web server that has an interpreter that supports the Java Servlet
specification.
Servlets can be created using the javax.servlet and javax.servlet.http packages, which are a standard
part of the Java's enterprise edition, an expanded version of the Java class library that supports large-
scale development projects.
These classes implement the Java Servlet and JSP specifications. Java servlets have been created and
compiled just like any other Java class. After you install the servlet packages and add them to your
computer's Classpath, you can compile servlets with the JDK's Java compiler or any other current
compiler.

Setting up Web Server: Tomcat


A number of Web Servers that support servlets are available in the market. Some web servers are freely
downloadable and Tomcat is one of them.
Apache Tomcat is an open source software implementation of the Java Servlet and JavaServer Pages
technologies and can act as a standalone server for testing servlets and can be integrated with the
Apache Web Server.

Servlets - Life Cycle


A servlet life cycle can be defined as the entire process from its creation till the destruction. The
following are the paths followed by a servlet
 The servlet is initialized by calling the init () method.
 The servlet calls service() method to process a client's request.
 The servlet is terminated by calling the destroy() method.
 Finally, servlet is garbage collected by the garbage collector of the JVM.
Now let us discuss the life cycle methods in details.

2
The init( ) method :
The init method is designed to be called only once. It is called when the servlet is first created, and not
called again for each user request. So, it is used for one-time initializations, just as with the init method
of applets.

The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you
can also specify that the servlet be loaded when the server is first started.

When a user invokes a servlet, a single instance of each servlet gets created, with each user request
resulting in a new thread that is handed off to doGet or doPost as appropriate. The init() method simply
creates or loads some data that will be used throughout the life of the servlet.

The init method definition looks like this:

public void init() throws ServletException {


// Initialization code...
}

The service() method :


The service() method is the main method to perform the actual task. The servlet container (i.e. web
server) calls the service() method to handle requests coming from the client( browsers) and to write the
formatted response back to the client.

Each time the server receives a request for a servlet, the server spawns/generates a new thread and calls
service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and
calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.

Here is the signature of this method:

public void service(ServletRequest request,ServletResponse response)


throws ServletException, IOException{
}

3
The service ( ) method is called by the container and service method invokes doGet, doPost, doPut,
doDelete, etc. methods as appropriate. So you have nothing to do with service ( ) method but you
override either doGet() or doPost() depending on what type of request you receive from the client.

The doGet() and doPost() are most frequently used methods within each service request. Here is the
signature of these two methods.

The doGet() Method


A GET request results from a normal request for a URL or from an HTML form that has no METHOD
specified and it should be handled by doGet() method.

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// Servlet code

The doPost() Method


A POST request results from an HTML form that specifically lists POST as the METHOD and it should
be handled by doPost() method.

public void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}

The destroy() method :


The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your
servlet a chance to close database connections, halt background threads, write cookie lists or hit counts
to disk, and perform other such cleanup activities.

After the destroy() method is called, the servlet object is marked for garbage collection. The destroy
method definition looks like this:

public void destroy() {


// Finalization code...
}

4
Architecture Digram:
The following figure depicts a typical servlet life-cycle scenario.

 First the HTTP requests coming to the server are delegated to the servlet container.
 The servlet container loads the servlet before invoking the service( ) method.
 Then the servlet container handles multiple requests by spawning multiple threads, each thread
executing the service( ) method of a single instance of the servlet.

Servlets - Examples

Servlets are Java classes which service HTTP requests and implement the javax.servlet.Servlet
interface. Web application developers typically write servlets that extend javax.servlet.http.HttpServlet,
an abstract class that implements the Servlet interface and is specially designed to handle HTTP
requests.

5
Sample Code for Hello World:
Following is the sample source code structure of a servlet example to write Hello World:

// Import required java libraries


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

// Extend HttpServlet class


public class HelloWorld extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse


response)throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
// TODO output your page here
out.println("<html>");
out.println("<head>");
out.println("<title>Welcome to java servlet</title>");
out.println("</head>");
out.println("<body>");

out.println("<h1> This is my first java servlet program</h1>");

out.println("<a href=\"http://www.google.co.za\">google</a>");
out.println("</body>");
out.println("</html>");

} finally {
out.close();
}
} }

6
Servlets Form Data/query data

Before looking into how a servlet can read data submitted via a form, it is necessary to understand how
data from an HTML form is passed to the web server by the browser.

There are two common ways of passing data from the web browser to the web server. They are called
POST and GET methods. Both of these methods pass the data in a 'key=value' format. The key for each
data field is specified as part of the tag describing the relevant field.

GET method:

The GET method sends the encoded user information appended to the page request. The page and the
encoded information are separated by the ? character as follows:

http://www.test.com/hello?key1=value1&key2=value2

The GET method is the default method to pass information from browser to web server and it
produces a long string that appears in your browser's Location: box. Never use the GET method if you
have password or other sensitive information to pass to the server. The GET method has size limitation:
only 1024 characters can be in a request string.

This information is passed using QUERY_STRING header and will be accessible through
QUERY_STRING environment variable and Servlet handles this type of requests using doGet()
method.

POST method:
A generally more reliable method of passing information to a backend program is the POST method.
This packages the information in exactly the same way as GET methods, but instead of sending it as a
text string after a ? in the URL it sends it as a separate message. This message comes to the backend
program in the form of the standard input which you can parse and use for your processing. Servlet
handles this type of requests using doPost() method.

7
Reading Form Data using Servlet:
Servlets handles form data parsing automatically using the following methods depending on the
situation:

 getParameter(): You call request.getParameter() method to get the value of a form parameter.
 getParameterValues(): Call this method if the parameter appears more than once and returns
multiple values, for example checkbox.

GET Method Example Using URL:


Below is Formdatausinggetmethod.java servlet program to handle input given by web browser. We are
going to use getParameter() method which makes it very easy to access passed information:

// Import required java libraries


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

public class Formdatausinggetmethod extends HttpServlet {

/* Processes requests for both HTTP <code>GET</code> and <code>POST</code>


methods.
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
// TODO output your page here

out.println( "<html>");
out.println( "<head><title> Using GET Method to Read Form Data </title></head>");
out.println( "<body bgcolor=pink");

out.println("<form action=Formdatausinggetmethod method=GET>");

out.println("First Name: <input type=text name=first_name>");


out.println("<br />");
out.println("Last Name: <input type=text name=last_name />");
out.println("<input type=submit value=Submit />");
out.println("</form>");

out.println( "<h1 align=center> Using GET Method to Read Form Data </h1>");
out.println( "<ul>");
out.print( " <li><b>First Name</b>: ");
out.println( request.getParameter("first_name"));
out.print( " <li><b>Last Name</b>: ");
out.println( request.getParameter("last_name"));

8
out.println( "</ul>");
out.println( "</body></html>");

} finally {
out.close();
}
}

After running, try to enter First Name and Last Name and then click submit button to see the result on
your local machine where tomcat is running. Based on the input provided, it will generate similar result
as shown below.

If you click submit button you will get the query data at the URL address as follows

http://localhost:8085/Servletexamples12/Formdatausinggetmethod?first_name=Selam&last_name=Taye

If everything goes fine, above compilation would produce Formdatausinggetmethod.class file. Next you
would have to copy this class file in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes

9
and create following entries in web.xml file located in <Tomcat-installation-
directory>/webapps/ROOT/WEB-INF/

<servlet>
<servlet-name> Formdatausinggetmethod </servlet-name>
<servlet-class> Formdatausinggetmethod </servlet-class>
</servlet>

<servlet-mapping>
<servlet-name> Formdatausinggetmethod </servlet-name>
<url-pattern>/ Formdatausinggetmethod </url-pattern>
</servlet-mapping>

POST Method Example Using Form:


Let us do little modification in the above servlet, so that it can handle GET as well as POST methods.
Below is Formdatausingpostmethod.java servlet program to handle input given by web browser using
GET or POST methods.

// Import required java libraries


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

public class Formdatausingpostmethod extends HttpServlet {

/*Processes requests for both HTTP <code>GET</code> and <code>POST</code>


methods. */

protected void processRequest(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {

10
// TODO output your page here

out.println( "<html>");
out.println("<head><title> Using POST Method to Read Form Data </title></head>");
out.println( "<body bgcolor=pink");

out.println("<form action=Formdatausingpostmethod method=POST>");


out.println("First Name: <input type=text name=first_name>");
out.println("<br />");
out.println("Last Name: <input type=text name=last_name />");
out.println("<input type=submit value=Submit />");
out.println("</form>");

out.println("<h1 align=center> Using POST Method to Read Form Data </h1>");


out.println( "<ul>");
out.print( " <li><b>First Name</b>: ");
out.println( request.getParameter("first_name"));
out.print( " <li><b>Last Name</b>: ");
out.println( request.getParameter("last_name"));
out.println( "</ul>");
out.println( "</body></html>");
} finally {
out.close();
}
}

Based on the input provided, it would generate similar result as mentioned in the above examples.

11
Passing Checkbox Data to Servlet Program
Checkboxes are used when more than one option is required to be selected.

Here is example HTML code, CheckBox.htm, for a form with two checkboxes

<html>
<body>
<form action="CheckBox" method="POST" target="_blank">
<input type="checkbox" name="maths" checked="checked" /> Maths
<input type="checkbox" name="physics” /> Physics
<input type="checkbox" name="chemistry" checked="checked" />
Chemistry
<input type="submit" value="Select Subject" />
</form>
</body>
</html>

The result of this code is the following form

Maths Physics Chemistry

12
Below is CheckBox.java servlet program to handle input given by web browser for checkbox button.

// Import required java libraries


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

public class Formdatacheckbox extends HttpServlet {

/* Processes requests for both HTTP <code>GET</code> and <code>POST</code>


methods
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
// TODO output your page here
out.println("<html>");
out.println ("<head><title> Reading checkbox data</title></head>");
out.println ("<body bgcolor=#f0f0f0>");
out.println("<form action=Formdatacheckbox method=POST>");
out.println("<input type=checkbox name=maths checked=checked /> Maths");
out.println("<input type=checkbox name=physics /> Physics");
out.println("<input type=checkbox name=chemistry checked=checked />Chemistry");

out.println("<input type=submit value=Select Subject />");


out.println("</form>");
out.println("<h1 align=center> Reading data checkbox data</h1>");
out.println("<ul>");
out.print("<li><b>Maths Flag : </b> ");
out.println( request.getParameter("maths"));
out.print(" <li><b>Physics Flag : </b> ");
out.println( request.getParameter("physics"));
out.print("<li><b>Chemistry Flag : </b> ");
out.println( request.getParameter("chemistry"));
out.println("</ul>");

out.println(" </body>");
out.println(" </html>");

} finally {
out.close();
}
}

13
Reading All Form Parameters:
Following is the generic example which uses getParameterValues() method of HttpServletRequest to
read all the available form parameters. This method returns an Enumeration that contains the parameter
names in an unspecified order.

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

public class checkbox extends HttpServlet {

protected void processRequest(HttpServletRequest req, HttpServletResponse res) throws


ServletException, IOException {

res.setContentType("text/html");
PrintWriter out = res.getWriter();
try {

// TODO output your page here


out.println("<html>");
out.println("<head>");
out.println("<title>Check Box Example</title>");
out.println("</head>");
out.println("<body bgcolor=pink>");
out.println("<form method=post action=checkbox>");
out.println("<h3>Select Courses</h3>");
out.println("<p><input type=checkbox name=course value=VB.net /> VB.net");
out.println("<p><input type=checkbox name=course value=C++ /> C++ ");
out.println("<p><input type=checkbox name=course value=PHP /> PHP");
out.println("<p><input type=submit value=Submit /> </p>");
out.println("</form> ");
String[] courses;
courses= req.getParameterValues("course");
if(courses!=null)
{
out.println("Selected course(s) is/are:");
out.println("<ul>");

14
for(int i=0; i<courses.length; i++){
out.println("<li>"+(courses[i]));
}
out.println("</ul>");

}
else
out.println("<p><font color=red>not selected</font></p>");

out.println("</body></html>");
} finally { out.close(); }
}
}

Retrieving Data from the table using Statement

Let we have a database called stud and table dept1 (with fields did and dname)

In this program we are going to fetch the data from the database table to our java servlet pages.
To accomplish our goal we first have to make a class named as dbconnection which must extends the
abstract HttpServlet class, the name of the class should be such that the other person can understand
what this program is going to perform. The logic of the program will be written inside the
processRequest() method which takes two arguments, first is HttpServletRequest interface and the
second one is the HttpServletResponse interface and this method can throw ServletException.

Inside this method call the getWriter() method of the PrintWriter class. We can retrieve the data from the
database only and only if there is a connectivity between our database and the java program. Now use
the static method getConnection() of the DriverManager class. This method takes three arguments and
returns the Connection object. SQL statements are executed and results are returned within the context
of a connection. Now your connection has been established. Now use the method createStatement() of
the Connection object which will return the Statement object. This object is used for executing a static
SQL statement and obtaining the results produced by it. As we need to retrieve the data from the table so
we need to write a query to select all the records from the table. This query will be passed in the
executeQuery() method of Statement object, which returns the ResultSet object. Now the data will be
retrieved by using the getString() method of the ResultSet object.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class dbconnection extends HttpServlet {
Connection con;Statement stmt; ResultSet rs;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

15
response.setContentType("text/html");
PrintWriter out = response.getWriter();

try {

DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "stud", "stud");
stmt=con.createStatement();

out.println("Deriver loaded ");

rs=stmt.executeQuery("select * from dept1");

out.println("<html>");
out.println("<head>");
out.println("<title>Servlet dbconnection</title>");
out.println("</head>");
out.println("<body>");
out.println("<table border= 2> ");
out.println("<tr> ");
out.println("<td> did </td> <td> dname </td> ");
out.println("</tr> ");
out.println("<br>");

while(rs.next()){
out.println("<tr> ");
out.println("<td>"+rs.getString(1) + "</td> <td>" +rs.getString(2)+"</td>" );
out.println("<br>");
}

}
catch(Exception e){
System.out.println(e);
}

16
Inserting data from the HTML page to the database

Let we have a database called stud and table dept1 (with fields did and dname)

In this program we are going to make servlet program in which we are going to insert the values in the
database table from the html form.

To make our program working we need to make one html form in which we will have two fields, one is
for the department name and the other one is for entering the department id. And we will have the
submit button, clicking on which the values will be passed to the the database dserver.

The values which we have entered in the Html form will be retrieved by the server side program which
we are going to write. To accomplish our goal we first have to make a class named as
Servletinsertingdatatodb which must extends the abstract HttpServlet class, the name of the class
should be such that the other person can understand what this program is going to perform. The logic of
the program will be written inside the processRequest() method which takes two arguments, first is
HttpServletRequest interface and the second one is the HttpServletResponse interface and this method
can throw ServletException.

We can insert the data in the database only and only if there is a connectivity between our database and
the java program. To establish the connection between our database and the java program the static
method getConnection() of the DriverManager class takes three arguments and returns the Connection
object. SQL statements are executed and results are returned within the context of a connection. Now
your connection has been established. Now use the method prepareStatement() of the Connection
object which will return the PreparedStatement object to submit query to database. The values which we
have got from the html will be set in the database by using the setString() method of the
PreparedStatement object.

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.sql.*;

public class Servletinsertingdatatodb extends HttpServlet {

Connection con; Statement stmt; ResultSet rs;

protected void processRequest(HttpServletRequest request, HttpServletResponse response)

17
throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println(" <html>");

out.println(" <head>");

out.println("<title>Wel come to data insertion page</title> </head>");

out.println("<body>");

out.println("<form method=POST action=Servletinsertingdatatodb >");

out.println(" <p>Enter Dept ID: <input type=text name=did size=20></p>");

out.println(" <p>Enter Dept Name: <input type=text name=dname size=20 </p>");

out. out.println("<input type=submit value=save ></p>");

println("<input type=reset value=clear ></p>");

out.println("</form>");

try { DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "stud", "stud");

stmt=con.createStatement();

out.println("<h1> Deriver loaded </h1>");

String id = request.getParameter("did");

String name = request.getParameter("dname");

PreparedStatement pst = con.prepareStatement("insert into dept1 values(?,?)");

pst.setString(1,id);

pst.setString(2,name);

int i = pst.executeUpdate();

if(i!=0){

18
out.println("<br>Record has been inserted");

} else

{ out.println("failed to insert the data");

out.println("</body>");

out.println("</html>");

} catch (Exception e){

out.println(e); }

Example: Create the following servlet pages

//Home .java

try { out.println("<html>");
out.println("<head>");
out.println("<title>Well Come To DMU Student Registration</title>");
out.println("</head>");
out.println("<body bgcolor=#66CCFF>");
out.println("<center><table>");
out.println("<tr><th colspan=5><h1 style=color:#cc6600>Debre Markos University<br>Online student
Registration System</h1></th></tr>");
out.println("<tr><td><a href=Home style=color:white;font-size:26><input type=submit value=Home
style=color:white;font-size:20;background-color:#cc6600></a></td>");

out.println("<td><a href=ContactUs style=color:white;font-size:26><input type=submit value='Contact Us'


style=color:white;font-size:20;background-color:#cc6600></a> </td>");

out.println("<td><a href=AboutUs style=color:white;font-size:26><input type=submit value='About Us'


style=color:white;font-size:20;background-color:#cc6600></a> </td>");

out.println("</tr>");

out.println("</table></center>");

out.println("</br></br></br></br></br></br></br>");

out.println("<div style=height:100;width:200;margin-top:8;margin-right:1000");

19
out.println("<tr><td><form method=post action=Validateuser>"

+ "<h1>Login</h1>"

+ " Enter User Name:<input type=text name=username></br>"

+ "Enter Password:<input type=password name=password></br>"

+ "<input type=submit value=Login><input type=Reset value=Reset> </td></tr></form>");

out.println("</div>");

out.println("</body>");

out.println("</html>");

} finally { out.close(); }

//Validateuser.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter pw = response.getWriter();

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

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

RequestDispatcher rd; //used for page redirection

if(name.equals("") && password.equals("")){

pw.println(" User name and password can't be empty");

rd=request.getRequestDispatcher("/Home"); //return to Home page

rd.include(request, response);

else if (name.equals("stud") && password.equals("123")) {

rd=request.getRequestDispatcher("/DataAccesshomepage"); //redirect to DataAccesshomepage

rd.forward(request, response);

} else{

pw.println(" Try to enter correct user name or password");

rd=request.getRequestDispatcher("/Home");

rd.include(request, response);

} }

//DataAccesspagehome

protected void processRequest(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();

try { out.println("<html>");
out.println("<head>");
out.println("<title>Well Come To DMU Student Registration</title>");
out.println("</head>");
out.println("<body bgcolor=#66CCFF>");
out.println("<center><table>");
out.println("<tr><th colspan=5><h1 style=color:#cc6600>Debre Markos University<br>Online student
Registration System</h1></th></tr>");

21
out.println("<tr><td><a href=Home style=color:white;font-size:26><input type=submit value=Home
style=color:white;font-size:20;background-color:#cc6600></a></td>");

out.println("<td><a href=StudentManagement style=color:white;font-size:26><input type=submit


value='Student Management' style=color:white;font-size:20;background-color:#cc6600></a> </td>");

out.println("<td><a href=CourseManagement style=color:white;font-size:26><input type=submit


value='Course Management' style=color:white;font-size:20;background-color:#cc6600></a> </td>");

out.println("<td><a href=ResultManagement style=color:white;font-size:26><input type=submit


value='Result Management' style=color:white;font-size:20;background-color:#cc6600></a> </td>");

out.println("</tr>");

out.println("</table></center>");

out.println("</br></br></br></br></br></br></br>");

out.println("</div>");

out.println("<div style=height:100;width:200;margin-top:-200;margin-left:1100");

out.println("<a href=Home.java><input type=submit value=Logout></a>");

out.println("</div>");

out.println("</body>");

out.println("</html>");

} finally {

out.close();

} }

22
//StudentManagement.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();

try {

out.println("<html>");

out.println("<head>");

out.println("<title>Well Come To DMU Student Registration</title>");

out.println("</head>");

out.println("<body bgcolor=#66CCFF>");

out.println("<center><table>");

out.println("<tr><th colspan=5><h1 style=color:#cc6600>Debre Markos University<br>Online student


Registration System</h1></th></tr>");

out.println("<tr><td><a href=Home style=color:white;font-size:26><input type=submit value=Home


style=color:white;font-size:20;background-color:#cc6600></a></td>");

23
out.println("<td><a href=DataAccesshomepage style=color:white;font-size:26><input type=submit
value='Data access home' style=color:white;font-size:20;background-color:#cc6600></a> </td>");

out.println("<td><a href=Addnewstudent style=color:white;font-size:26><input type=submit value='Add


new student' style=color:white;font-size:20;background-color:#cc6600></a> </td>");

out.println("<td><a href=Updatestudentprofile style=color:white;font-size:26><input type=submit


value='Update student Profile' style=color:white;font-size:20;background-color:#cc6600></a> </td>");

out.println("<td><a href=DeleteStudent style=color:white;font-size:26><input type=submit value='Delete


student Profile' style=color:white;font-size:20;background-color:#cc6600></a> </td>");

out.println("<td><a href=Searchstudent style=color:white;font-size:26><input type=submit value='Search


student' style=color:white;font-size:20;background-color:#cc6600></a> </td>");

out.println("</tr>");

out.println("</table></center>");

out.println("</br></br></br></br></br></br></br>");

out.println("</div>");

out.println("<div style=height:100;width:200;margin-top:-200;margin-left:1100");

out.println("&nbsp;&nbsp;<a href=Logout ><input type=submit value='Logout' ></a>");

out.println("</div>");

out.println("</body>");

out.println("</html>");

} finally {

out.close();

//StudentManagement.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();


try {

24
out.println("<html>");
out.println("<head>");
out.println("<title>Well Come To DMU Student Registration</title>");
out.println("</head>");
out.println("<body bgcolor=#66CCFF>");
out.println("<center><table>");
out.println("<tr><th colspan=5><h1 style=color:#cc6600>Debre Markos University<br>Online student
Registration System</h1></th></tr>");
out.println("<tr><td><a href=Home style=color:white;font-size:26><input type=submit value=Home
style=color:white;font-size:20;background-color:#cc6600></a></td>");

out.println("<td><a href=DataAccesshomepage style=color:white;font-size:26><input type=submit


value='Data access home' style=color:white;font-size:20;background-color:#cc6600></a> </td>");

out.println("<td><a href=Addnewstudent style=color:white;font-size:26><input type=submit value='Add


new student' style=color:white;font-size:20;background-color:#cc6600></a> </td>");

out.println("<td><a href=Updatestudentprofile style=color:white;font-size:26><input type=submit


value='Update student Profile' style=color:white;font-size:20;background-color:#cc6600></a> </td>");

out.println("<td><a href=DeleteStudent style=color:white;font-size:26><input type=submit value='Delete


student Profile' style=color:white;font-size:20;background-color:#cc6600></a> </td>");

out.println("<td><a href=Searchstudent style=color:white;font-size:26><input type=submit value='Search


student' style=color:white;font-size:20;background-color:#cc6600></a> </td>");

out.println("</tr>");
out.println("</table></center>");
out.println("</br></br></br></br></br></br></br>");
out.println("</div>");
out.println("<div style=height:100;width:200;margin-top:-200;margin-left:1100");
out.println("&nbsp;&nbsp;<a href=Logout ><input type=submit value='Logout' ></a>");
out.println("</div>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
} }

25
//AddNewStudent.java ,let we have studentdb database and student table(sis,sname,dname)

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.sql.*;

public class AddNewStudent extends HttpServlet {

Connection con; Statement stmt; ResultSet rs;

protected void processRequest(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
out.println("<html>");
out.println("<head>");
out.println("<title>Well Come To DMU Student Registration</title>");
out.println("</head>");
out.println("<body bgcolor=#66CCFF>");
out.println("<center><table>");

26
out.println("<tr><th colspan=5><h1 style=color:#cc6600>Debre Markos University<br>Online student
Registration System</h1></th></tr>");
out.println("<tr><td><a href=Home style=color:white;font-size:26><input type=submit value=Home
style=color:white;font-size:20;background-color:#cc6600></a></td>");
out.println("<td><a href=DataAccesshomepage style=color:white;font-size:26><input type=submit
value='Data access home' style=color:white;font-size:20;background-color:#cc6600></a> </td>");
out.println("<td><a href=Addnewstudent style=color:white;font-size:26><input type=submit value='Add
new student' style=color:white;font-size:20;background-color:#cc6600></a> </td>");
out.println("<td><a href=Updatestudentprofile style=color:white;font-size:26><input type=submit
value='Update student Profile' style=color:white;font-size:20;background-color:#cc6600></a> </td>");
out.println("<td><a href=DeleteStudent style=color:white;font-size:26><input type=submit value='Delete
student Profile' style=color:white;font-size:20;background-color:#cc6600></a> </td>");
out.println("<td><a href=Searchstudent style=color:white;font-size:26><input type=submit value='Search
student' style=color:white;font-size:20;background-color:#cc6600></a> </td>");

out.println("</tr>");
out.println("</table></center>");
out.println("</br></br></br></br></br></br></br>");
out.println("</div>");
out.println("<div style=height:100;width:200;margin-top:-200;margin-left:1100");
out.println("&nbsp;&nbsp;<a href=Home ><input type=submit value='Logout' ></a>");
out.println("</div>");
out.println("<center>");
out.println("<table>"); out.println("<tr><th colspan=2>Student Registration Form</th></tr>");
out.println("<tr><td><form method=post action=AddNewStudent>");

out.println("<tr><td>Student ID:</td><td><input type=text name=id></td></tr>");

out.println("<tr><td>Student Name:</td><td><input type=text name=name></td></tr>");

out.println("<tr><td>Student Department:</td><td><input type=text name=dept></td></tr>");

out.println("<tr><td></td><td><input type=submit value=Save><input type=Reset value=Reset></td></tr>");

out.println("</form>");

out.println("</center>");

{ DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "stududentdb",
"stududentdb");

stmt=con.createStatement();

out.println("<h1> Deriver loaded </h1>");

27
String id = request.getParameter("sid");

String name = request.getParameter("sname");

String dept = request.getParameter("dname");

PreparedStatement ps= con.prepareStatement("insert into student values(?,?,?)");

ps.setString(1,id);

ps.setString(2,name);

ps.setString(3,dept);

int i = ps.executeUpdate();

if(i!=0){

out.println("<br>Record has been inserted");

} else

{ out.println("failed to insert the data");

out.println("</body>");

out.println("</html>");

} finally {

out.close();

} }

28

You might also like