0% found this document useful (0 votes)
27 views39 pages

JSP (Part II)

Uploaded by

cexabiv801
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)
27 views39 pages

JSP (Part II)

Uploaded by

cexabiv801
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/ 39

Advanced Java

Actions tag in JSP

It is necessary to control the servlet engine's behavior, which can be controlled dynamically by
inserting the file by reusing the JavaBeans components or redirecting or forwarding the user to
another page., i.e., by forwarding the request to another resource, which will possibly be a JSP,
HTML, or other resources.

The JSP specification provides a standard tag called Action tag used within JSP code and is used to
remove or eliminate Scriptlet code from your JSP code as JSP Scriptlets are obsolete and are not
considered nowadays. There are many JSP action tags or elements, and each of them has its own
uses and characteristics. Each JSP action tag is implemented to perform some precise tasks.

The action tag is also implemented to streamline flow between pages and to employ a Java Bean. As
it coincides with the XML standard, the syntax for the action element is:

<jsp:action_name attribute = "attribute_value" />

The list of JSP Actions:

 jsp:forward: is used for forwarding the request and response to other resources.
 jsp:include: is used for including another resource.
 jsp:body: is used for defining dynamically-defined body of XML element.
 jsp:useBean: is used for creating or locating bean objects.
 jsp:setProperty: is used for setting the value of property in the bean object.
 jsp:getProperty: is used for printing the value of the property of the bean.
 jsp:element: is used for defining XML elements dynamically.
 jsp:plugin: is used for embedding other components (applets).
 jsp:param: is used for setting the parameter for (forward or include) value.
 jsp:text: is used for writing template text in JSP pages and documents.
 jsp:fallback: is used for printing the message if plugins are working.
 jsp:attribute: is used for defining attributes of dynamically-defined XML element.
Advanced Java
Two basic attributes are commonly used for all action tags. These are:

id: The id attribute defines unique action elements and allows actions to be referenced within the
JSP page. When the action creates an object's instance, the id attribute is used to refer to it.

Scope: The scope attribute is used for identifying an action's life cycle. It correlates with the id
attribute because the scope attribute is used to establish that particular object's lifespan associated
with the ID.

Here the syntax and implementation of some actions are described below:

This "include action" allows you to include another resource in the page being generated.

<jsp:include page = "Page URL" flush = "Boolean Value" />

<!DOCTYPE html>

<html>

<head>

<title>JSP include Action</title>

</head>

<body>

<h2>JSP page: with include</h2>

<jsp:include page="header.jsp" flush="false" />

</body>

</html>

This "forward action" terminates the current page and allows you to forward the request to other
resources.

<jsp:forward page = "URL of another static, JSP, OR Servlet page" />

<!DOCTYPE html>
Advanced Java
<html>

<head>

<title>Example for Forward Action</title>

</head>

<body>

<h2>JSP page: Demo forward</h2>

<jsp:forward page="forward_eg.jsp" />

</body>

</html>

It is to be noted that this JSP file and forward_eg.jsp file should have to reside in the same directory
to make it work.

This "param action" is used for setting the parameter for (forward or include) value.

<jsp: param name = "param_name" value = "value_of_parameter" />

<!DOCTYPE html>

<html>

<head>

<title>Example of param Action</title>

</head>

<body>

<h2>JSP page: Param with forward</h2>

<jsp:forward page="forward_eg.jsp">

<jsp:param name="date" value="06-09-2019" />


Advanced Java
<jsp:param name="time" value="10:30PM" />

<jsp:param name="data" value="GKR" />

</jsp:forward>

</body>

</html>

This "useBean action": is used for creating or locating bean objects.

<jsp: useBean id="unique_name_to_identify_bean" class="package_name.class_name" />

<!DOCTYPE html>

<html>

<head>

<title>JSP Page for showing use of useBean action</title>

</head>

<body>

<h2>UseBean Action</h2>

<jsp:useBean id="teacher" class="packageName.Teacher" />

<jsp:setProperty name="teacher" property="*" />

<h2>

name:<jsp:getProperty name="teacher" property="t_name" /> <br />

empno:<jsp:getProperty name="teacher" property="dept" /> <br />

</h2>

</body>

</html>
Advanced Java
package samplePackageName;

public class Teacher {

public Teacher() {}

private String t_name;

private int deptno;

public void setName(String t_name) {

this.t_name = t_name;

public String getName() {

return t_name;

public void setDept(int deptno) {

this.deptno = deptno;

public int getDept() {

return deptno;

}
Advanced Java
}

Expression tags

Expression tags are one of the most useful scripting elements of JSP. Expression tags use special
tags to print the different java expressions and output directly on the client-side. You can also use
this for displaying information on your client browser.

The expression tag is used to evaluate Java's expression within the JSP, which then converts the
result into a string and forwards the result back to the client browser via the response object.
Essentially, it is implemented for printing the result to the client (browser). An expression tag can
hold any java language expression that can be employed as an argument to the out.print()
method.
The syntax of the expression tag in JSP looks something like:
Syntax:
<%= expression %>

This is how the JSP container sees this when it encounters the above expression:
<%= (6*4) %>

It turns out to be:


out.print((6*4));

It is to be noted that you will never terminate an expression using semicolon within Expression Tag.
Like this:
<%= (6*4); %>

Here is an example of an Expression tag:


Example:
<!DOCTYPE html>

<html>

<head>

<title>Expression Tag in JSP</title>


Advanced Java
</head>

<% int rollNo = 02; %>

<body>

The next roll number is: <%= ++rollNo %>

</body>

</html>

Different Expression Tags with Different Expression Types:

Expression of Values

In this chase, you have to pass the expression of values within the expression tag.
Example:
<!DOCTYPE html>

<html>

<head>

<title>JSP expression tag example1</title>

</head>

<body>

<%= 2+4*5 %>

</body>

</html>
Advanced Java
Expression of Variables

In this case, you have to initialize a few variables, which can then be passed as the expression of
variables within the expression tag in order to evaluate the result.
Example:
<!DOCTYPE html>

<html>

<head>

<title>JSP expression tag example2</title>

</head>

<body>

<% int g = 60; int k = 40; int r = 20; %>

<%= g+k+r %>

</body>

</html>

String with Implicit Object Output

Here, you have to set an attribute using an application implicit object and then display it with a
simple string on another JSP page via an expression tag.
Example(start.jsp):
<!DOCTYPE html>

<html>

<head>

<title>Example of JSP expression tag</title>


Advanced Java
</head>

<body>

<% application.setAttribute("EmpName", "Alex"); %>

<a href="show.jsp"> Click to See </a>

</body>

</html>

Example(show.jsp):
<!DOCTYPE html>

<html>

<head>

<title>Show Employee Name Page</title>

</head>

<body>

<%="A String value:" %> <br />

<%= application.getAttribute("EmpName") %>

</body>

</html>

Difference Between Scriptlet Tag and Expression Tag


Advanced Java
1. In Scriptlet tag, it evaluates your Java expression but does not print or show your result in
conjunction with the HTML created. The declared variables have a local scope only and hence
can't take access from another place in the .jsp. In contrast, the Expression Tag has the capability
to evaluate the Java expression. It is used for inserting the result in the form of a string in
conjunction with the HTML in the JSP.

2. You don't have to write the out.println in the expression tag to print the expression based output
because these are changed into out.print() statement (as shown above the process of
transformation of expression), which gets inserted by the container in the _jspService(-, -) of the
servlet class.

JSP implicit objects

There is another concept of JSP, which are Java objects made available by the developers for each
page, allowing developers to call them directly without any explicit declaration. JSP implicit objects
are essential components used in this regard.

The JSP engine produces these objects during the translation phase (i.e., at the time of translation
from JSP to Servlet). They are being formed within the service method so that JSP developers can
use them directly in Scriptlet without declaration and initialization.
There are a total of nine implicit objects supported by the JSP. These are:

1. out: javax.servlet.jsp.JspWriter

2. request: javax.servlet.http.HttpServletRequest

3. response: javax.servlet.http.HttpServletResponse

4. session: javax.servlet.http.HttpSession

5. application: javax.servlet.ServletContext

6. exception: javax.servlet.jsp.JspException

7. page: java.lang.Object

8. pageContext: javax.servlet.jsp.PageContext

9. config: javax.servlet.ServletConfig
Advanced Java
The brief information about the implicit objects are given below:

The out Implicit Object

 An out object is an implicit object for writing data to the buffer and sending output as a response
to the client's browser.

 The out implicit object is an instance of a javax.servlet.jsp.jspWriter class.

Example (HTML file):


<!DOCTYPE html>

<html>

<head>

<title>Please insert a User name and a password</title>

</head>

<body>

<% out.println("Today's date-time: "+java.util.Calendar.getInstance().getTime()); %>

</body>

</html>

Output:
Today's date-time: Nov 01 12:10:05 IST 2020

The request Implicit Object

 A request object is an implicit object that is used to request an implicit object, which is to receive
data on a JSP page, which has been submitted by the user on the previous JSP/HTML page.
Advanced Java
 The request implicit object used in Java is an instance of
a javax.servlet.http.HttpServletRequest interface where a client requests a page every time
the JSP engine has to create a new object for characterizing that request.

 The container creates it for every request.

 It is used to request information such as parameters, header information, server names, cookies,
and HTTP methods.

 It uses the getParameter() method to access the request parameter.

Here is an example of a JSP request implicit object where a user submits login information, and
another JSP page receives it for processing:
Example (HTML file):
<!DOCTYPE html>

<html>

<head>

<title>Please insert a User name and a password</title>

</head>

<body>

<form action="login.jsp">

Please insert Username: <input type="text" name="u_name" /> <br />

Please insert Password: <input type="text" name="passwd" /> <br />

<input type="submit" value="Submit Details" />

</form>

</body>

</html>
Advanced Java
Example (login.jsp):
<%@ page import = " java.util.* " %>

<%

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

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

out.print("Name: "+username+" Password: " +passwd);

%>.

The response Implicit Object

 A response object is an implicit object implemented to modify or deal with the reply sent to the
client (i.e., browser) after processing the request, such as redirect responding to another resource
or an error sent to a client.

 The response implicit object is an instance of


a javax.servlet.http.HttpServletResponse interface.

 The container creates it for every request.

The session Implicit Object

 A session object is the most commonly used implicit object implemented to store user data to
make it available on other JSP pages until the user's session is active.

 The session implicit object is an instance of a javax.servlet.http.HttpSession interface.

 This session object has different session methods to manage data within the session scope.

 You will learn more about the use of the session in subsequent chapters.

The application Implicit Object

An application object is another implicit object implemented to initialize application-wide


parameters and maintain functional data throughout the JSP application.
Advanced Java
The exception Implicit Object

 An exception implicit object is implemented to handle exceptions to display error messages.

 The exception implicit object is an instance of the java.lang.Throwable class.

 It is only available for JSP pages, with the isErrorPage value set as "True". This means Exception
objects can only be used in error pages.

Example (HTML file):


<!DOCTYPE html>

<html>

<head>

<title>Enter two Integers for Division</title>

</head>

<body>

<form action="submit.jsp">

Insert first Integer: <input type="text" name="numone" /><br />

Insert second Integer: <input type="text" name="numtwo" /><br />

<input type="submit" value="Get Results" />

</form>

</body>

</html>

Example (submit.jsp):
<%@ page errorPage="exception.jsp" %>
Advanced Java

<%

String num1 = request.getParameter("numone");

String num2 = request.getParameter("numtwo");

int var1= Integer.parseInt(num1);

int var2= Integer.parseInt(num2);

int r= var1 / var2;

out.print("Output is: "+ r);

%>

Example (exception.jsp):
<%@ page isErrorPage='true' %>

<%

out.print("Error Message : ");

out.print(exception.getMessage());

%>

The page Implicit Object

A page object is an implicit object that is referenced to the current instance of the servlet. You can
use it instead. Covering it specifically is hardly ever used and not a valuable implicit object while
building a JSP application.
<% String pageName = page.toString();
Advanced Java
out.println("The current page is: " +pageName);%>

The config Implicit Object

A config object is a configuration object of a servlet that is mainly used to access and receive
configuration information such as servlet context, servlet name, configuration parameters, etc. It
uses various methods used to fetch configuration information.

JSP request:

In dynamic web application development, client and server interactions are essential for sending
and receiving information over the Internet. When the browser requests a webpage, a lot of
information is sent to the webserver. Such information cannot be read directly because such
information is part of an HTTP header request.

The JSP request can be defined as an implicit object is an instance of "HttpServletRequest" and is
formed for all JSP requests through the web container. This JSP request gets request information
like a parameter, remote address, header information, server port, server name, character
encoding, content type, etc.

JSP request Implicit Object

 A request object is an implicit object that is used to request an implicit object, which is to receive
data on a JSP page, which has been submitted by the user on the previous JSP/HTML page.

 The request implicit object used in Java is an instance of


a javax.servlet.http.HttpServletRequest interface where a client requests a page every time the
JSP engine has to create a new object for characterizing that request.

 The container creates it for every request.

 It is used to request information such as parameters, header information, server names, cookies,
and HTTP methods.

 It uses the getParameter() method to access the request parameter.


Advanced Java
Here is an example of a JSP request implicit object where a user submits login information, and
another JSP page receives it for processing:
Example (HTML file):
<!DOCTYPE html>

<html>

<head>

<title>User login form</title>

</head>

<body>

<form action="login.jsp">

Please insert Username: <input type="text" name="u_name" /> <br />

Please insert Password: <input type="text" name="passwd" /> <br />

<input type="submit" value="Submit Details" />

</form>

</body>

</html>

Example (login.jsp):
<%@ page import = " java.util.* " %>

<%

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

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


Advanced Java
out.print("Name: "+username+" Password: " +passwd);

%>

Methods of request Implicit Object

 Enumeration getAttributeNames(): is used for returning an Enumeration that contains the


attribute names presented to this request.

 Cookie[] getCookies(): is used for returning an array that contains all of the cookie-objects of the
client sent associated with a particular request.

 Enumeration getParameterNames(): is used for returning an enumeration of String-objects that


contain the names of the parameters rested in this request.

 Enumeration getHeaderNames(): is used for returning an enumeration of all the header names
associated with the request.

 HttpSession getSession(): It is used to return the current session connected with your request or
create a session if it does not have any session.

 HttpSession getSession(boolean create): is used to return the current HttpSession linked with
the request or create a new session if there is no current session.

 Locale getLocale(): is used for returning the chosen Locale that will be accepted by the client,
based upon the Accept-Language header.

 Object getAttribute(String name): is used for returning the value of the named attribute as an
Object or set as null.

 ServletInputStream getInputStream(): is used to retrieve the body of the request in the form of
binary data through a ServletInputStream.

 String getAuthType(): is used for returning the name of the authentication scheme (BASIC, SSL,
or null) implemented for protecting the servlet.

 String getCharacterEncoding(): is used for returning the name of the character encoding
implemented in the body of a request.

 String getContentType(): is used for returning the MIME type of the requested content body.
Advanced Java
 String getContextPath(): is used for returning the portion of the request URI, which is used for
indicating the context of the request.

 String getHeader(String name): is used for returning the value of the specified request header in
the form of a String.

 String getMethod(): is used for returning the name of the HTTP method (GET, PUT, and POST)
through which this request was made.

 String getPathInfo(): is used for returning any extra path information connected to the URL sent
by the client when the request is made.

 String getProtocol(): is used for returning the name and the version of the protocol.

 String getQueryString(): is used for returning the query string contained in the request URL
following the path.

 String getRemoteAddr(): is used for returning the Internet Protocol (IP) address of the client,
which is used by all websites.

 String getRemoteHost(): is used for returning the fully qualified name of the client who sent the
request.

 String getRemoteUser(): is used to return the user's login, making an authenticated request or
null if the user has not yet authenticated.

 String getRequestURI(): is used for returning the part of a request's URL from the protocol name
till the starting line of the HTTP request.

 String getRequestedSessionId():is used for returning the particular session ID of the client.

 String getServletPath(): is used for returning the part of this request's URL, which calls the JSP.

 String[] getParameterValues(String name): is used for returning an array of String objects that
will contain all of the values of a requested parameter or otherwise returns null.

 boolean isSecure(): is used for returning a Boolean value indicating if a request was made
through a secure channel (HTTPS, FTPS) or not.

 int getContentLength(): is used for returning the length of a request body.

 int getIntHeader(String name): is used for returning the value of a particular request header as
an int.
Advanced Java
 int getServerPort(): is used for returning the port number on which a request was received.

JSP response:-

As you know, in dynamic web application development, client and server interactions are necessary
to send and receive information over the Internet. When the browser requests a webpage, a lot of
information is sent to the webserver, and the webserver responds after processing the HTTP
request. Such a response is part of an HTTP header response and cannot be read directly.

The JSP response can be defined as an implicit object is an instance of "HttpServletResponse"


and is formed for each JSP request created by the JSP container.

The response Implicit Object

 A response object is an implicit object implemented to modify or deal with the reply sent to the
client (i.e., browser) after processing the request, such as redirect responding to another resource
or an error sent to a client.

 The response implicit object is an instance of


a javax.servlet.http.HttpServletResponse interface.

 The container creates it for every request.

Here is an example of a JSP request and response implicit objects where a user submits login
information, and another JSP page receives it for processing:
Example (HTML file):
<!DOCTYPE html>

<html>

<head>

<title>User login form</title>

</head>
Advanced Java
<body>

<form action="login.jsp">

Please enter Username: <input type="text" name="u_name" /> <br />

<input type="submit" value="Submit Details" />

</form>

</body>

</html>

Example (login.jsp):
<%@ page import = " java.util.* " %>

<%

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

if(username.equals("admin")){

response.sendRedirect("home.jsp");

}else{

out.print("Invalid Username");

%>

Methods of response Implicit Object

JSP has different methods for dealing with implicit response objects, which is of type
HttpServeltResponse. Each of these methods has its own functionality.
Advanced Java
 String encodeURL(String url): is used for encoding a particular URL by comprising the session ID
along with it. Otherwise, when the encoding is not required, it will return the URL unchanged.

 String encodeRedirectURL(String url): is used for encoding a particular URL for using it in the
sendRedirect method. Otherwise, when the encoding is not required, it will return the URL
unchanged.

 boolean containsHeader(String name): is used for returning a Boolean signifying whether the
name response header is already set or not.

 void addDateHeader(String name, long date): is used for adding a response header with the
given name along with a date-value.

 void addHeader(String name, String value): is used to add a response header with the given
name and a value.

 boolean isCommitted(): is used for returning a Boolean value signifying whether the response
has been committed or not.

 void addIntHeader(String name, int value): is used for adding a response header with the
specified name along with an integer value.

 void flushBuffer(): is used for forcing any content in the buffer for writing it to the client.

 void addCookie(Cookie cookie): is used for adding a particular cookie with the response.

 void reset(): is used for clearing any data which is present in the buffer, header or status code.

 void sendError(int sc): is used for sending an error response (through particular status code) to
its client.

 void sendError(int sc, String msg): is used for sending an error response (through some
particular status string) to its client.

 void resetBuffer(): is used for clearing the content of the underlying buffer without clearing the
status code or header.

 void sendRedirect(String location): is used for sending a short-term redirect response to the
client.

 void setBufferSize(int size): is used for setting an ideal buffer size for the response body.
Advanced Java
 void setCharacterEncoding(String charset): is used for setting the character encoding (usually
MIME charset - UTF 8) being sent to the client.

 void setContentType(String type): is used for setting the content type being sent to the client
when the response has not yet been committed.

 void setDateHeader(String name, long date): is used to set a response header with the given
name and date-value.

 void setContentLength(int len): is used for setting the length of the body of content in the
response.

 void setHeader(String name, String value): is used for setting a response header with the given
name as well as value.

 void setIntHeader(String name, int value): is used to set a response header with the given
name and an integer value.

 void setLocale(Locale loc): is used for setting the locale of the response in case the response is
not yet committed.

 void setStatus(int sc): is used for setting the status code for your response.

Session:
A session can be defined as an object associated with each user with a unique session ID, and the
user's data is based on the account they have registered. Different forms of data can be set in a
session; These data related to each user of the site help the user and the website owner in different
ways. As you know, HTTP is a "stateless" protocol; Whenever a user visits a web page, the user
opens a separate connection with the webserver, and the server does not keep a record of
preceding client requests.
Different approaches to maintain a session between client and server are:

1. Cookies: Cookies are text files that allow programmers to store some information on a client
computer, and they are kept for usage tracking purposes.

2. Passing Session ID in URL: Adding and passing session ID to URL is also a way to identify a
session. However, this method is obsolete and insecure because the URL can be tracked.

The session Implicit Object


Advanced Java
 A session object is the most commonly used implicit object implemented to store user data to
make it available on other JSP pages until the user's session is active.

 The session implicit object is an instance of a javax.servlet.http.HttpSession interface.

 This session object has different session methods to manage data within the session scope.

Here is an example of a JSP request and session implicit objects where a user submits login
information, and another JSP page receives it for processing:
Example (HTML file):
<!DOCTYPE html>

<html>

<head>

<title>User login form</title>

</head>

<body>

<form action="login.jsp">

Please enter Username: <input type="text" name="u_name" /> <br />

<input type="submit" value="Submit Details" />

</form>

</body>

</html>

Example (login.jsp):
<%@ page import = " java.util.* " %>

<%
Advanced Java
String username = request.getParameter("u_name");

if(username.equals("admin")){

session.setAttribute("u_name",username);

response.sendRedirect("home.jsp");

}else{

out.print("Invalid Username");

%>

Example (home.jsp):
<%

String session_u_name = (String)session.getAttribute("u_name");

out.print("Hi "+session_u_name);

%>

JSP Sessions Methods

1. public Object getAttribute(String name): is used for returning the object bound with the

specified name for a session and null if there is no object.

2. public Enumeration getAttributeNames(): is used for returning an Enumeration of String objects

that will hold the names of all the objects to this session.

3. public long getCreationTime(): is used for returning the time when the session was created right

from midnight January 1, 1970, GMT.


Advanced Java
4. public String getId(): is used for returning a string that will hold a unique identifier assigned to

your session.

5. public long getLastAccessedTime(): is used for returning the latest time your client sent a

request linked with the session.

6. public int getMaxInactiveInterval(): is used for returning the highest time interval (in seconds),

which has to be maintained by the servlet container as a session gets opened between client

accesses.

7. public void invalidate(): is used for invalidating a session and unbinds its objects bound to it.

8. public boolean isNew(): is used for returning a true when the client does not know anything

about the session or when the client chooses not to join the session.

9. public void removeAttribute(String name): is used for removing the object bound specifically to

a session.

10. public void setAttribute(String name, Object value): is used for binding an object to your

session with the help of a specified name.

11. public void setMaxInactiveInterval(int interval): is used for specifying the time (in seconds)

between client requests where the servlet container will nullify this session.

How to Create a database in MySql using JSP code

A database consists of one or more tables.

The CREATE DATABASE statement is used to create a database in MySQL.


Advanced Java
The following examples create a database named "test":

create-table.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<%@ page import="java.sql.*" %>

<html>

<head>

<title>Create a Database using JSP</title>

</head>

<body>

<h1>Create a Database using JSP</h1>

<%

Connection connection = null;

try {

Class.forName("com.mysql.jdbc.Driver").newInstance();

connection = DriverManager.getConnection("jdbc:mysql://localhost:3306", "root", "");

Statement statement = connection.createStatement();

String query = "CREATE DATABASE test";

statement.executeUpdate(query);

out.println("Database test created sucessfully.");

catch (Exception e)
Advanced Java
{

out.println("An error occurred.");

%>

</body>

</html>

Insert Data Into MySQL Using JSP Source Code

For insert data in MySQL using JSP first we have to create a table in data base.

The INSERT INTO statement is used to insert new data to a MySQL table:

INSERT INTO table_name (column1, column2, column3,...)

VALUES (value1, value2, value3,...)

For creating table the SQL query is:

SQL Query

CREATE TABLE users

id int NOT NULL AUTO_INCREMENT,

first_name varchar(50),

last_name varchar(50),

city_name varchar(50),

email varchar(50),

PRIMARY KEY (id)


Advanced Java
);

Here we using 2 files for insert data in MySQL:

index.html:for getting the values from the user

process.jsp:A JSP file that process the request

index.html

<!DOCTYPE html>

<html>

<body>

<form method="post" action="process.jsp">

First name:<br>

<input type="text" name="first_name">

<br>

Last name:<br>

<input type="text" name="last_name">

<br>

City name:<br>

<input type="text" name="city_name">

<br>

Email Id:<br>

<input type="email" name="email">

<br><br>

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

</form>
Advanced Java
</body>

</html>

process.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<%@page import="java.sql.*,java.util.*"%>

<%

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

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

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

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

try

Class.forName("com.mysql.jdbc.Driver");

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");

Statement st=conn.createStatement();

int i=st.executeUpdate("insert into


users(first_name,last_name,city_name,email)values('"+first_name+"','"+last_name+"','"+city_name+
"','"+email+"')");

out.println("Data is successfully inserted!");

catch(Exception e)
Advanced Java
{

System.out.print(e);

e.printStackTrace();

%>

Output

First name:

Last name:

City name:

Email Id:

Retrieve data from MySQL database using JSP

For retrieve data from MySQL database using JSP first we have to create a table in data base.

After create a table in the MySQL database you need to insert record or data on it.If you want to
know how to insert data in jsp please visit the link : Insert data in JSP.
Advanced Java

The SELECT statement is used to retrieve data from one or more tables:

The SQL query for retrieve specific column.

SELECT column_name(s) FROM table_name

or we can use the * character to retrieve ALL columns from a table:

SELECT * FROM table_name

To learn more about SQL, please visit our SQL tutorial.

In this example we retrieve the employee data of a company.

The JSP file for retrieving data from database is:

retrieve.jsp

<%@page import="java.sql.DriverManager"%>

<%@page import="java.sql.ResultSet"%>

<%@page import="java.sql.Statement"%>

<%@page import="java.sql.Connection"%>

<%

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

String driver = "com.mysql.jdbc.Driver";

String connectionUrl = "jdbc:mysql://localhost:3306/";


Advanced Java
String database = "test";

String userid = "root";

String password = "";

try {

Class.forName(driver);

} catch (ClassNotFoundException e) {

e.printStackTrace();

Connection connection = null;

Statement statement = null;

ResultSet resultSet = null;

%>

<!DOCTYPE html>

<html>

<body>

<h1>Retrieve data from database in jsp</h1>

<table border="1">

<tr>

<td>first name</td>

<td>last name</td>

<td>City name</td>

<td>Email</td>
Advanced Java
</tr>

<%

try{

connection = DriverManager.getConnection(connectionUrl+database, userid, password);

statement=connection.createStatement();

String sql ="select * from users";

resultSet = statement.executeQuery(sql);

while(resultSet.next()){

%>

<tr>

<td><%=resultSet.getString("first_name") %></td>

<td><%=resultSet.getString("last_name") %></td>

<td><%=resultSet.getString("city_name") %></td>

<td><%=resultSet.getString("email") %></td>

</tr>

<%

connection.close();

} catch (Exception e) {

e.printStackTrace();

%>

</table>

</body>
Advanced Java
</html>

After retrieve the data from the data base the table look like this.

id first name last name City name Email Id

1 Divyasundar Sahu Mumbai [email protected]

2 Hritika Sahu Pune [email protected]

3 Milan Jena Chennai [email protected]

In this example we will discuss about how to delete a record or data from MySQL database using
JSP.

The DELETE statement is used to delete records from a table:

DELETE FROM table_name

WHERE some_column = some_value

Notice : The WHERE clause specifies which record or records that should be deleted. If you omit the
WHERE clause, all records will be deleted!

To learn more about SQL, please visit our SQL tutorial.

The following examples delete the record with id=3 in the "users" table:

To delete a record from table you must have insert data.If you want to know how to insert data in
jsp please visit : Insert data in JSP.

The users table look like this:


Advanced Java

id first name last name City name Email Id

1 Divyasundar Sahu Mumbai [email protected]

2 Hritika Sahu Pune [email protected]

3 Milan Jena Chennai [email protected]

Now i am going to delete the id=3 record.

index.jsp

<%@page import="java.sql.DriverManager"%>

<%@page import="java.sql.ResultSet"%>

<%@page import="java.sql.Statement"%>

<%@page import="java.sql.Connection"%>

<%

String driver = "com.mysql.jdbc.Driver";

String connectionUrl = "jdbc:mysql://localhost:3306/";

String database = "student";

String userid = "root";

String password = "";

try {

Class.forName(driver);

} catch (ClassNotFoundException e) {

e.printStackTrace();

Connection connection = null;


Advanced Java
Statement statement = null;

ResultSet resultSet = null;

%>

<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<body>

<h1>Retrieve data from database in jsp</h1>

<table border="1">

<tr>

<td>first name</td>

<td>last name</td>

<td>City name</td>

<td>Email</td>

<td>Action</td>

</tr>

<%

try{

connection = DriverManager.getConnection(connectionUrl+database, userid, password);

statement=connection.createStatement();

String sql ="select * from users";

resultSet = statement.executeQuery(sql);

int i=0;

while(resultSet.next()){
Advanced Java
%>

<tr>

<td><%=resultSet.getString("fname") %></td>

<td><%=resultSet.getString("lname") %></td>

<td><%=resultSet.getString("city_name") %></td>

<td><%=resultSet.getString("email") %></td>

<td><a href="delete.jsp?id=<%=resultSet.getString("id") %>"><button type="button"


class="delete">Delete</button></a></td>

</tr>

<%

i++;

connection.close();

} catch (Exception e) {

e.printStackTrace();

%>

</table>

</body>

</html>

delete.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-


8859-1"%>

<%@page import="java.sql.*,java.util.*"%>

<%
Advanced Java
String id=request.getParameter("id");

try

Class.forName("com.mysql.jdbc.Driver");

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/student", "root",


"");

Statement st=conn.createStatement();

int i=st.executeUpdate("DELETE FROM users WHERE id="+id);

out.println("Data Deleted Successfully!");

catch(Exception e)

System.out.print(e);

e.printStackTrace();

%>

After delete the id=3 record from the table the table is now

id first name last name City name Email Id

1 Divyasundar Sahu Mumbai [email protected]

2 Hritika Sahu Pune [email protected]

You might also like