JSP
JSP
JavaServer Pages is a technology for developing web pages that include dynamic content.
Unlike a plain HTML page, which contains static content that always remains the same, a
JSP page can change its content based on any number of variable items, including the
identity of the user, the user's browser type, information provided by the user, and
selections made by the user.
A JSP page contains standard markup language elements, such as HTML tags, just like a
regular web page. However, a JSP page also contains special JSP elements that allow the
server to insert dynamic content in the page. JSP elements can be used for a variety of
purposes, such as retrieving information from a database or registering user preferences.
When a user asks for a JSP page, the server executes the JSP elements, merges the results
with the static parts of the page, and sends the dynamically composed page back to the
browser.
JSP defines a number of standard elements that are useful for any web application, such
as accessing JavaBeans components, passing control between pages and sharing
information between requests, pages, and users. Developers can also extend the JSP
syntax by implementing application-specific elements that perform tasks such as
accessing databases and Enterprise JavaBeans, sending email, and generating HTML to
present application-specific data. One such set of commonly needed custom elements is
defined by a specification related to the JSP specification: the JSP Standard Tag Library
(JSTL) specification. The combination of standard elements and custom elements allows for
the creation of powerful web applications.
Why JSP
JavaServer Pages often serve the same purpose as programs implemented using
the Common Gateway Interface (CGI). But JSP offers several advantages in comparison
with the CGI.
<h1>Good evening!</h1>
</c:otherwise>
</c:choose>
Welcome to our site, open 24 hours a day.
</body>
</html>
Output
This page inserts a different message to the user based on the time of day: "Good
morning!" if the local time is before 12 P.M., "Good day!" if between 12 P.M. and 6
P.M., and "Good evening!" otherwise. When a user asks for this page, the JSP
enabled web server executes the logic represented by the highlighted JSP elements
and creates an HTML page that is sent back to the user's browser. For example, if the
current time is 8:53 P.M., the resulting page sent from the server to the browser.
Compilation
Another benefit that is important to mention is that a JSP page is always compiled
before it's processed by the server. Remember that older technologies such as
CGI/Perl require the server to load an interpreter and the target script each time
the page is requested. JSP gets around this problem by compiling each JSP page into
executable code the first time it's requested (or on demand), and invoking the
resulting code directly on all subsequent requests. When coupled with a persistent
Java virtual machine on a JSP-enabled web server, this allows the server to handle JSP
pages much faster.
This separation means that with JSP, a typical business can divide its efforts among
two groups that excel in their own areas of expertise: a Java web development team
with programmers who implement the application logic as servlets, EJBs and custom
JSP elements, and page authors who craft the specifics of the interface and use the
powerful custom elements without having to do any programming. While the second
half is for programmers who wish to combine JSP with other technologies and create
their own JSP elements.
Java servlet-based applications, processing the request and generating the response are
both handled by a single servlet class. Example shows how a servlet class often looks.
The point is that the servlet contains request processing and business logic (implemented
by methods such as isOrderInfoValid() and saveOrderInfo( )), and also generates the
response HTML code, embedded directly in the servlet code using println( ) calls. A more
structured servlet application isolates different pieces of the processing in various reusable
utility classes and may also use a separate class library for generating the actual HTML
elements in the response. Even so, the pure servlet based approach still has a few
problems:
Changing the look and feel of the application, or adding support for a new type of
client (such as a WML client), requires the servlet code to be updated and
recompiled.
It's hard to take advantage of web page development tools when designing the
application interface. If such tools are used to develop the web page layout, the
generated HTML must then be manually embedded into the servlet code, a process
which is time consuming, error prone, and extremely boring.
Adding JSP to the puzzle lets you solve these problems by separating the request processing
and business logic code from the presentation. Instead of embedding HTML in the code,
place all static HTML in a JSP page, just as in a regular web page, and add a few JSP
elements to generate the dynamic parts of the page. The request processing can remain the
domain of the servlet, and the business logic can be handled by JavaBeans and EJB
components.
Servlet vs JSP
SERVLET JSP
Servlets run faster than JSP JSP runs slower because it has the transition phase
for converting from JSP page to a Servlet file. Once
it is converted to a Servlet then it will start the
compilation
Executes inside a Web server, such as A JSP program is compiled into a Java servlet
Tomcat before execution. Once it is compiled into a
servlet, it's life cycle will be same as of servlet. But,
JSP has it's own API for the lifecycle.
sReceives HTTP requests from users and Easier to write than servlets as it is similar to
provides HTTP responses HTML.
We can not build any custom tags One of the key advantage is we can build custom
tags using JSP API (there is a separate package
available for writing the custom tags) which can be
available as the re-usable components with lot of
flexibility
Servlet has the life cycle methods init(), JSP has the life cycle methods of jspInit(),
service() and destroy() _jspService() and jspDestroy()
Written in Java, with a few additional JSPs can make use of the Javabeans inside the web
APIs specific to this kind of processing. pages
Since it is written in Java, it follows all the
Object Oriented programming
techniques.
SERVLET JSP
When client makes a request to Server, it first goes to container. Then container checks
whether the servlet class is older than jsp page( To ensure that the JSP file got modified). If
this is the case then container does the translation again (converts JSP to Servlet) otherwise
it skips the translation phase (i.e. if JSP webpage is not modified then it doesn’t do the
translation to improve the performance as this phase takes time and to repeat this step
every time is not time feasible).
1. Translation
2. Compilation
3. Loading
4. Instantiation
5. Initialization
6. RequestProcessing
7. Destruction
A Java servlet file is generated from a JSP source file. This is the first step of JSP life cycle. In
translation phase, container validates the syntactic correctness of JSP page and tag files.
The JSP container interprets the standard directives and actions, and the custom
actions referencing tag libraries used in this JSP page.
In the above pictorial description, demo.jsp is translated to demo_jsp.java in the first
step
Let's take an example of "demo.jsp" as shown below:
demo.jsp
1. <html>
2. <head>
3. <title>Demo JSP</title>
4. </head>
5. <%
6. int demvar=0;%>
7. <body>
8. Count is:
9. <% Out.println(demovar++); %>
10. <body>
11. </html>
Demo JSP Page is converted into demo_jsp servlet in the below code.
Here you can see that in the screenshot theOutput is 1 because demvar is initialized to 0
and then incremented to 0+1=1
demo.jsp, is a JSP where one variable is initialized and incremented. This JSP is
converted to the servlet (demo_jsp.class ) wherein the JSP engine loads the JSP Page
and converts to servlet content.
When the conversion happens all template text is converted to println() statements
and all JSP elements are converted to Java code.
The generated java servlet file is compiled into java servlet class
The translation of java source page to its implementation class can happen at any
time between the deployment of JSP page into the container and processing of the
JSP page.
In the above pictorial description demo_jsp.java is compiled to a class file
demo_jsp.class
3. Classloading
Servlet class that has been loaded from JSP source is now loaded into the container
4. Instantiation
In this step the object i.e. the instance of the class is generated.
The container manages one or more instances of this class in the response to
requests and other events. Typically, a JSP container is built using a servlet container.
A JSP container is an extension of servlet container as both the container support JSP
and servlet.
A JSP Page interface which is provided by container provides init() and destroy ()
methods.
There is an interface HttpJSPPage which serves HTTP requests, and it also contains
the service method.
5. Initialization
_jspinit() method will initiate the servlet instance which was generated from JSP and
will be invoked by the container in this phase.
Once the instance gets created, init method will be invoked immediately after that
It is only called once during a JSP life cycle, the method for initialization is declared as
shown above
6. Request processing
_jspservice() method is invoked by the container for all the requests raised by the JSP
page during its life cycle
For this phase, it has to go through all the above phases and then only service
method can be invoked.
It passes request and response objects
This method cannot be overridden
The method is shown above: It is responsible for generating of all HTTP methods
i.eGET, POST, etc.
7. Destroy
Everything in the page that isn't a JSP element is called template text. Template text can be
any text: HTML, WML, XML, or even plain text. It can be used with any markup language.
Template text is always passed straight through to the browser.
When a JSP page request is processed, the template text and dynamic content generated
by the JSP elements are merged, and the result is sent as the response to the browser.
JSP Elements
JSP Declaration
A declaration tag is a piece of Java code for declaring variables, methods and classes.
If we declare a variable or method inside declaration tag it means that the
declaration is made inside the servlet class but outside the service method.
We can declare a static member, an instance variable (can declare a number or
string) and methods inside the declaration tag.
Here Dec var is the method or a variable inside the declaration tag.
Example:
In this example, we are going to use the declaration tags
1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
2. pageEncoding="ISO-8859-1"%>
3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
4. <html>
5. <head>
6. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
7. <title>Declaration Tag</title>
8. </head>
9. <body>
10. <%! int count =10; %>
11. <% out.println("The Number is " +count); %>
12. </body>
13. </html>
JSP Scriptlet
Here <%%> tags are scriplets tag and within it, we can place java code.
Example:
In this example, we are taking Scriptlet tags which enclose java code.
Code Line 10-14: In the Scriptlet tags where we are taking two variables num1 and num2 .
Third variable num3 is taken which adds up as num1 and num2.The output is num3.
When you execute the code, you get the following output:
JSP Expression
Syntax:
Example:
Code Line 12: Here we are using expression tags where we are using an expression by
multiplying two numbers i.e. num1 and num 2 and then adding the third number i.e. num3.
When you execute the above code, you get the following output:
JSP Comments
Comments are the one when JSP container wants to ignore certain texts and statements.
When we want to hide certain content, then we can add that to the comments section.
Syntax:
This tags are used to comment in JSP and ignored by the JSP container.
<!—comment -->
Example:
In this example, we are using JSP comments
Example:
Code Line 10: Here we are adding JSP comments to the code to explain what code has. It is
been ignored by the JSP container
When you execute the above code you get the following output:
JSP directives are the messages to JSP container. They provide global information about an
entire JSP page.
JSP directives are used to give special instruction to a container for translation of JSP to
servlet code. In JSP life cycle phase, JSP has to be converted to a servlet which is the
translation phase. They give instructions to the container on how to handle certain aspects
of JSP processing. Directives can have many attributes by comma separated as key-value
pairs.
Syntax of Directive:
1. Page directive
2. Include directive
3. Taglib directive
<%@ page…%>
1. Language
2. Extends
3. Import
4. contentType
5. info
6. session
7. isThreadSafe
8. autoflush
9. buffer
10.IsErrorPage
11.pageEncoding
12.errorPage
13.isELIgonored
1. language: It defines the programming language (underlying language) being used in the
page.
Syntax of language:
Example:
Explanation of code: In the above example, attribute language value is Java which is the
underlying language in this case. Hence, the code in expression tags would be compiled
using java compiler.
2. Extends: This attribute is used to extend (inherit) the class like JAVA does
Syntax of extends:
Example:
Explanation of the code: In the above code JSP is extending DemoClass which is within
demotest package, and it will extend all class features.
3. Import: This attribute is most used attribute in page directive attributes.It is used to tell
the container to import other java classes, interfaces, enums, etc. while generating
servlet code.It is similar to import statements in java classes, interfaces.
Syntax of import:
Example:
In the above code, we are importing Date class from java.util package (all utility classes),
and it can use all methods of the following class.
4. contentType:
It defines the character encoding scheme i.e. it is used to set the content type and
the character set of the response
The default type of contentType is "text/html; charset=ISO-8859-1".
Example:
In the above code, the content type is set as text/html, it sets character encoding for JSP
and for generated response page.
5. info
Syntax of info:
Example:
In the above code, string "Guru Directive JSP" can be retrieved by the servlet interface using
getServletInfo()
6. Session
When it is set to false, then we can indicate the compiler to not create the session by
default.
Syntax of session:
Example:
Explanation of code:
In the above example, session attribute is set to "false" hence we are indicating that we
don't want to create any session in this JSP
7. isThreadSafe:
Syntax of isThreadSafe:
Here true or false represents if synchronization is there then set as true and set it as false.
Example:
In the above code, isThreadSafe is set to "true" hence synchronization will be done, and
multiple threads can be used.
8. AutoFlush:
This attribute specifies that the buffered output should be flushed automatically or not and
default value of that attribute is true.
If the value is set to false the buffer will not be flushed automatically and if its full, we will
get an exception.
When the buffer is none then the false is illegitimate, and there is no buffering, so it will be
flushed automatically.
Syntax of autoFlush:
Example:
In the above code, the autoflush is set to false and hence buffering won't be done and it has
manually flush the output.
9. Buffer:
It directs the servlet to write the buffer before writing to the response object.
Syntax of buffer:
Here the value represents the size of the buffer which has to be defined. If there is no
buffer, then we can write as none, and if we don't mention any value then the default is
8KB
Example:
In the above code, buffer size is mentioned as 16KB wherein the buffer would be of that
size
10. isErrorPage:
It indicates that JSP Page that has an errorPage will be checked in another JSP page
Any JSP file declared with "isErrorPage" attribute is then capable to receive
exceptions from other JSP pages which have error pages.
Exceptions are available to these pages only.
The default value is false.
Syntax of isErrorPage:
Example:
In the above code, isErrorPage is set as true. Hence, it will check any other JSPs has
errorPage (described in the next attribute) attribute set and it can handle exceptions.
11.PageEncoding:
The "pageEncoding" attribute defines the character encoding for JSP page.
Syntax of pageEncoding:
Example:
In the above code "pageEncoding" has been set to default charset ISO-8859-1
12.errorPage:
This attribute is used to set the error page for the JSP page if JSP throws an exception and
then it redirects to the exception page.
Syntax of errorPage:
Example:
13.isELIgnored:
Its datatype is java enum, and the default value is false hence EL is enabled by
default.
Syntax of isELIgnored:
Example:
In the above code, isELIgnored is true and hence Expression Language (EL) is ignored here.
Example:
Code Line 3: Here we have used import attribute, and it is importing "Date class" which is
from Java util package, and we are trying to display current date in the code.
When you execute the above code, you will get the following output
JSP "include directive" is used to include one file to the another file
This included file can be HTML, JSP, text files, etc.
It is also useful in creating templates with the user views and break the pages into
header & footer and sidebar actions.
It includes file during translation phase
<%@ include….%>
Example:
Directive_jsp2.jsp:
Code Line 3: In this code, we use include tags where we are including the file
directive_header_jsp3.jsp into the main file(_jsp2.jsp)and gets the output of both main file
and included file.
Directive_header_jsp3.jsp:
Code Line 11-12: We have taken a variable count initialized to 1 and then incremented it.
This will give the output in the main file as shown below.
When you execute the above code you get the following output:
JSP taglib directive is used to define the tag library with "taglib" as the prefix, which
we can use in JSP.
JSP taglib directive is used in the JSP pages using the JSP standard tag libraries
It uses a set of custom tags, identifies the location of the library and provides means
of identifying custom tags in JSP page.
Here "uri" attribute is a unique identifier in tag library descriptor and "prefix" attribute is a
tag name.
Example:
Code Line 3: Here "taglib" is defined with attributes uri and prefix.
Code Line 9: "gurutag" is the custom tag defined and it can be used anywhere
JSP actions use the construct in XML syntax to control the behavior of the servlet engine.
We can dynamically insert a file, reuse the beans components, forward user to another
page, etc. through JSP Actions like include and forward.
Unlike directives, actions are re-evaluated each time the page is accessed.
Syntax:
jsp:useBean
jsp:include
jsp:setProperty
jsp:getProperty
jsp:forward
jsp:plugin
jsp:attribute
jsp:body
jsp:text
jsp:param
jsp:attribute
jsp:output
1. jsp:useBean:
This action name is used when we want to use beans in the JSP page.
With this tag, we can easily invoke a bean.
Here it specifies the identifier for this bean and class is full path of the bean class
Example:
Code Line 10: In the above code we use "bean id" and "class path" of the bean.
2. jsp:include
It also used to insert a jsp file into another file, just like include directive.
It is added during request processing phase
Syntax of jsp:include
Example:
Date.jsp
Action_jsp2.jsp
Code Line 10: In the first file we are including the date.jsp file in action_jsp2.jsp
Date.jsp:
Code Line 11: We are printing today's date in code line 11 in date.jsp
3. jsp:setProperty
Syntax:
Here, the name defines the bean whose property is set and property which we want to set.
Also, we can set value and param attribute.
Here value is not mandatory, and it defines the value which is assigned to the property.
Here param is the name of the request parameter using which value can be fetched.
The example of setproperty will be demonstrated below with getproperty
4. jsp:getProperty
Syntax:
Here, the name of the bean from which the property has to be retrieved and bean should
be defined. The property attribute is the name of the bean property to be retrieved.
TestBean.java:
TestBean.java:
Code Line 5: TheTestBean is implementing the serializable class. It is a bean class with
getters setters in the code.
Code Line 7: Here we are taking private string variable msg as "null"
Code Line 9-14: Here we are using getters and setters of variable "msg".
Action_jsp3.jsp
Code Line 10: Here we are using "useBean" tag, where it specifies the bean i.e TestBean
which has to be used in this jsp class
Code Line 11: Here we are setting the value for the property msg for bean TestBean as
"GuruTutorial."
CodeLine12: Here using getProperty, we are getting the value of property msg for bean
TestBean i.e GuruTutorial which is there in the output
When you execute the above code you get the following output:
5. jsp:forward:
It is used to forward the request to another jsp or any static page.
Here the request can be forwarded with no parameters or with parameters.
Syntax:
<jsp:forward page="value">
Example:
Action_jsp41.jsp
Code Line 10: Here we are using forward JSP Action to forward the request to the page
mentioned in the attribute, i.e., jsp_action_42.jsp
Jsp_action_42.jsp
Code Line 10: Once we call action_jsp41.jsp, the request gets forwarded to this page, and
we get the output as "This is after forward page."
6. jsp:plugin
It is used to introduce Java components into jsp, i.e., the java components can be
either an applet or bean.
It detects the browser and adds <object> or <embed> tags into the file
Syntax:
7. jsp:param
Syntax:
<jsp:params>
<jsp:param name="val" value="val"/ >
</jsp:params>
8. jsp:body
This tag is used to define the XML dynamically i.e., the elements can generate during
request time than compilation time.
It actually defines the XML, which is generated dynamically element body.
Syntax:
<jsp:body></jsp:body>
9. jsp:attribute
This tag is used to define the XML dynamically i.e. the elements can be generated
during request time than compilation time
It actually defines the attribute of XML which will be generated dynamically.
Syntax:
Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 40
22-11-2019 Java Server Pages
<jsp:attribute></jsp:attribute>
10.jsp:text
Syntax:
<jsp:text>template text</jsp:text>
Here template text refers to only template text (which can be any generic text which needs
to be printed on jsp ) or any EL expression.
Example:
JSP implicit objects are created during the translation phase of JSP to the servlet.
These objects can be directly used in scriplets that goes in the service method.
They are created by the container automatically, and they can be accessed using
objects.
1. out
2. request
3. response
4. config
5. application
6. session
7. pageContext
8. page
9. exception
1. out
Out is one of the implicit objects to write the data to the buffer and send output to
the client in response
Out object allows us to access the servlet's output stream
Out is object of javax.servlet.jsp.jspWriter class
While working with servlet, we need printwriter object
Example:
2. Request
Example:
3. Response
Example:
4. Application
Example:
5. Session
6. pageContext:
Page
Request
Session
Application
Example:
7. Exception
Example:
An expiration date, after which the client is no long expected to retain the cookie. If
no date is specified, the cookie expires as soon as the browser session ends.
A domain name, such as servername.com, which restricts the subset of URLs for
which the cookie is valid. If unspecified, the cookie is returned with all requests to
the originating Web server.
A path name that further restricts the URL subset.
A secure attribute, which, if present, indicates the cookie should only be returned if
the connection uses a secure channel, such as SSL.
First, the Web browser requests a page from the Web server. No cookies are involved at
this point. When the server responds with the requested document, it sends a Set-Cookie
header assigning the value fr to a cookie named language. The cookie is set to expire in one
year. The browser reads this header, extracts the cookie information, and stores the
name/value pair in its cookie cache, along with the Web server’s domain and default path.
Later, when the user visits the page again, the browser recognizes it previously received a
cookie from this server and the cookie hasn’t yet expired, and, therefore, sends the cookie
back to the server.
One advantage of cookies over other persistence schemes is they can retain their values
after the browser session is over, even after the client computer is rebooted. This makes
cookies well suited for maintaining users’ preferences, such as language. The application
shown in the following enables the user to select the desired language by clicking a
hyperlink. The selection causes two cookies to be sent to the client: one for language and
one for country. The next time the user visits the site, the browser automatically sends the
cookies back to the server and the user’s preferred language is used in the page.
Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 51
22-11-2019 Java Server Pages
Cookies Methods
Following table lists out the useful methods associated with the Cookie object which you
can use while manipulating cookies in JSP −
S.No. Method & Description
Keep in mind, neither the name nor the value should contain white space or any of the
following characters −
[]()=,"/?@:;
cookie.setMaxAge(60*60*24);
response.addCookie(cookie);
Example
main.jsp
<%
// Create cookies for first and last names.
Cookie firstName = new Cookie("first_name", request.getParameter("first_name"));
Cookie lastName = new Cookie("last_name", request.getParameter("last_name"));
<html>
<head>
<title>Setting Cookies</title>
</head>
<body>
<center>
Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 54
22-11-2019 Java Server Pages
<h1>Setting Cookies</h1>
</center>
<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>
cookie_main.jsp
<html>
<body>
</body>
</html>
Example
<html>
<head>
<title>Reading Cookies</title>
</head>
Deependra Rastogi, Assistant Professor, SCSE, Galgotia University Page 55
22-11-2019 Java Server Pages
<body>
<center>
<h1>Reading Cookies</h1>
</center>
<%
Cookie cookie = null;
Cookie[] cookies = null;
</html>
Example
<html>
<head>
<title>Reading Cookies</title>
</head>
<body>
<center>
<h1>Reading Cookies</h1>
</center>
<%
Cookie cookie = null;
Cookie[] cookies = null;
if((cookie.getName( )).compareTo("first_name") == 0 ) {
cookie.setMaxAge(0);
response.addCookie(cookie);
out.print("Deleted cookie: " + cookie.getName( ) + "<br/>");
}
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
}
} else {
out.println(
"<h2>No cookies founds</h2>");
}
%>
</body>
</html>
JSP makes use of the servlet provided HttpSession Interface. This interface provides a way
to identify a user across.
Example
Session Tracking
<html>
<head>
<title>Session Tracking</title>
</head>
<body>
<center>
<h1>Session Tracking</h1>
</center>
<th>Value</th>
</tr>
<tr>
<td>id</td>
<td><% out.print( session.getId()); %></td>
</tr>
<tr>
<td>Creation Time</td>
<td><% out.print(createTime); %></td>
</tr>
<tr>
<td>Time of Last Access</td>
<td><% out.print(lastAccessTime); %></td>
</tr>
<tr>
<td>User ID</td>
<td><% out.print(userID); %></td>
</tr>
<tr>
<td>Number of visits</td>
<td><% out.print(visitCount); %></td>
</tr>
</table>
</body>
</html>
Login.jsp
login_logic.jsp
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/employee","root", "");
Statement st = con.createStatement();
ResultSet rs;
rs = st.executeQuery("select * from user_detail where uname='" + userid + "' and
passwd='" + pwd + "'");
if (rs.next()) {
session.setAttribute("userid", userid);
response.sendRedirect("success.jsp");
} else {
out.println("Invalid password <a href='Login.jsp'>try again</a>");
}
%>
success.jsp
<%
if ((session.getAttribute("userid") == null) || (session.getAttribute("userid") ==
"")) {
%>
<%} else {
%>
Welcome <%=session.getAttribute("userid")%>
<a href='logout.jsp'>Log out</a>
<%
}
%>
logout.jsp
<%
session.setAttribute("userid", null);
session.invalidate();
response.sendRedirect("Login.jsp");
%>
Database
User.java
package com.bari.model;
import java.util.Date;
Database.java
package com.bari.util;
import java.sql.Connection;
import java.sql.DriverManager;
public class Database {
public static Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/employee",
"root","");
return con;
}
catch(Exception ex) {
System.out.println("Database.getConnection() Error -->" + ex.getMessage());
return null;
}
}
UserDao.java
package com.bari.dao;
import java.sql.*;
import java.util.*;
import com.bari.model.User;
import com.bari.util.Database;
public UserDao() {
connection = Database.getConnection();
}
ps.setString(1, user.getUname());
ResultSet rs = ps.executeQuery();
if (rs.next()) // found
{
updateUser(user);
} else {
addUser(user);
}
} catch (Exception ex) {
System.out.println("Error in check() -->" + ex.getMessage());
}
}
public void addUser(User user) {
try {
PreparedStatement preparedStatement = connection.prepareStatement("insert into
users(uname, password, email, registeredon) values (?, ?, ?, ? )");
// Parameters start with 1
preparedStatement.setString(1, user.getUname());
preparedStatement.setString(2, user.getPassword());
preparedStatement.setString(3, user.getEmail());
preparedStatement.setDate(4, new java.sql.Date(user.getRegisteredon().getTime()));
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
preparedStatement.setString(2, user.getEmail());
preparedStatement.setDate(3, new java.sql.Date(user.getRegisteredon().getTime()));
preparedStatement.setString(4, user.getUname());
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
return users;
}
if (rs.next()) {
user.setUname(rs.getString("uname"));
user.setPassword(rs.getString("password"));
user.setEmail(rs.getString("email"));
user.setRegisteredon(rs.getDate("registeredon"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return user;
}
}
UserController.java
package com.bari.controller;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.bari.dao.UserDao;
import com.bari.model.User;
public UserController() {
super();
dao = new UserDao();
}
if (action.equalsIgnoreCase("delete")){
String userId = request.getParameter("userId");
dao.deleteUser(userId);
forward = LIST_USER;
request.setAttribute("users", dao.getAllUsers());
} else if (action.equalsIgnoreCase("edit")){
forward = INSERT_OR_EDIT;
String userId = request.getParameter("userId");
User user = dao.getUserById(userId);
request.setAttribute("user", user);
} else if (action.equalsIgnoreCase("listUser")){
forward = LIST_USER;
request.setAttribute("users", dao.getAllUsers());
} else {
forward = INSERT_OR_EDIT;
}
index.jsp
user.jsp
listuser.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Show All Users</title>
</head>
<body>
<table border=1>
<thead>
<tr>
<th>User Name</th>
<th>Email</th>
<th>Registration Date</th>
<th colspan=2>Action</th>
</tr>
</thead>
<tbody>
<c:forEach items="${users}" var="user">
<tr>
<td><c:out value="${user.uname}" /></td>
<td><c:out value="${user.email}" /></td>
<td><fmt:formatDate pattern="dd MMM,yyyy" value="${user.registeredon}" /></td>
<td><a href="UserController?action=edit&userId=<c:out
value="${user.uname}"/>">Update</a></td>
<td><a href="UserController?action=delete&userId=<c:out
value="${user.uname}"/>">Delete</a></td>
</tr>
</c:forEach>
</tbody>
</table>
<p><a href="UserController?action=insert">Add User</a></p>
</body>
</html>
web.xml
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>