Lekcija10 - 02_Java-Servlets_2013_11_07 - files-ante-lv

Download Report

Transcript Lekcija10 - 02_Java-Servlets_2013_11_07 - files-ante-lv

Java Servlet Technology
Introduction
• Servlets are Java programs that run on a
Web server, handle HTTP requests and build
Web pages
• Servlet specification versions
•
•
•
•
•
[version 1.0]
[version 2.4 – Java2EE 1.4]
[version 2.5 – Java EE 5]
[version 3.0 – Java EE 6]
[version 3.1 – Java EE 7]
June 1997
November 2003
September 2005
December 2009
May 2013
Java Enterprise Edition
• Java EE is a comprehensive platform for
multi-user, enterprise-wide applications
• It is based on Java SE
and adds APIs
for Internet-based
server-side
computing
http://docs.oracle.com/javaee/7/tutorial/doc/
Java EE architecture
Distributed component-based multi-tier
enterprise application model
Servlets in Java EE
Java Servlet - a Java program that extends the
functionality of a Web server, generating
dynamic content and interacting with Web clients
using a request-response paradigm
Web Application Internals
Java Web Application Technologies
Java Servlet technology is the foundation of all
the web application technologies
Servlets and JSPs
• Servlets - Java classes that dynamically process
requests and construct responses
• JSP pages - text-based documents that execute as
servlets, but allow a more natural approach to
creating static content
• Appropriate usage
•
•
Servlets - service-oriented applications, control
functions
JSP - generating text-based markup
(HTML, SVG, WML, XML)
Static vs Dynamic contents
• Static contents
•
•
Typically static HTML page
Same display for everyone
• Dynamic contents
•
•
Contents is dynamically generated based on
conditions
Conditions could be
• User identity
• Time of the day
• User entered values through forms and selections
What is Servlet?
• Java™ object which is based on a servlet
framework and APIs and extends the
functionality of a HTTP server
• Mapped to URLs and managed by container with
a simple architecture
• Available and running on all major web servers
and application servers
• Platform and server independent
Servlets library
• To start programming with servlets need to include
appropriate library in application classpath
• Maven configuration:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
• Library: javax-servlet-api-3.1.0.jar
• Classes are located in a package: javax.servlet
Adding Java to a Maven Project
• Manually create a folder for Java classes
\your_webapp\src\main\java
• Servlet classes and other Java classes may be
placed into this folder
Servlet that generates plain text
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println("Hello World!");
out.close();
}
}
Servlet that generates HTML
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body><h1>" +
"Hello World!</h1></body></html>");
out.close();
}
}
Mapping URLs to Servlets
• When a request is received by the web container
it must determine which web component should
handle the request
• Need to add a servlet definition and a servlet
mapping for each servlet to web.xml file
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
URL patterns
• Four types of URL patterns
• Exact match:
<url-pattern>/dir1/dir2/name</url-pattern>
• Path match:
<url-pattern>/dir1/dir2/*</url-pattern>
• Extension match:
<url-pattern>*.ext</url-pattern>
• Default resource:
<url-pattern>/</url-pattern>
Servlet 3.0 mapping style
import
import
import
import
java.io.*;
javax.servlet.ServletException;
javax.servlet.annotation.WebServlet;
javax.servlet.http.*;
@WebServlet("/servlet3")
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println("Hello World!");
out.close();
}
}
Deployment descriptor (web.xml)
is optional since version 3.0
Servlets and JSP - Comparison
JSP is a text-based document capable of returning
dynamic content to a client browser
Servlets typically
are used for
returning
non-HTML data
Servlet Request & Response Model
What does Servlet do?
• Receives a client request (mostly in the form of
HTTP request)
• Extracts some information from the request
• Does content generation or business logic processing
(possibly by accessing database, invoking EJBs, etc)
• Creates and sends a response to a client (mostly in
the form of HTTP response) or forwards the request
to another servlet or JSP page
Requests and Responses
• What is a request?
•
Information that is sent from client to a server
• Who made the request
• What user-entered data is sent
• Which HTTP headers are sent
• What is a response?
•
Information that is sent to client from a server
• Text (html, plain) or binary (image) data
• HTTP headers, cookies, etc
Things to do in doGet() & doPost()
• Extract client-sent information (HTTP parameter)
from HTTP request
• Set (save) and get (read) attributes to/from Scope
objects
• Perform some business logic or access database
• Optionally forward the request to other Web
components (Servlet or JSP)
• Populate HTTP response message and send it to a
client
Steps of Populating HTTP Response
• Fill response headers
• Set some properties of the response
•
Buffer size
• Get an output stream object from the response
PrintWriter out = response.getWriter();
• Write body content to the output stream
out.println("Hello World!");
Example: Simple Response
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Fill response headers
response.setContentType("text/html");
// Set buffer size
response.setBufferSize(8192);
// Get an output stream object from the response
PrintWriter out = response.getWriter();
// Write body content to output stream
out.println("<title>First Servlet</title>");
out.println("<big>Hello Java EE Programmers!</big>")
}
}
Getting Request Parameters
• A request can come with any number of parameters
• Parameters are sent from HTML forms:
•
•
GET: as a query string, appended to a URL after ?
POST: as encoded POST data, not appearing in the URL
• getParameter("paramName")
•
•
•
Returns the value of ‘paramName’
Returns null if no such parameter is present
Works identically for GET and POST requests
Example 1: Welcome message
@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
if (name == null || "".equals(name.trim())){
name = "guest";
}
PrintWriter out = response.getWriter();
out.println("<html><body><h1>"
+ "Welcome " + name + "!"
+ "</h1></body></html>");
out.close();
}
}
Example 2: User login
1. login.html
<html>
<head><title>Login</title></head>
<body>
<form action="/my-super-app/login" method="POST">
<p><label for="login">Login:</label><br>
<input id="login" name="login" size="30" type="text"/></p>
<p><label for="password">Password:</label><br>
<input id="password" name="password" type="password"/></p>
<p><input type="submit" value="Login"/></p>
</form>
</body>
</html>
Example 2: User login
2. LoginServlet.java
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String login = request.getParameter("login");
String password = request.getParameter("password");
boolean isValid = checkPassword(login, password);
String path = request.getContextPath();
if (isValid){
response.sendRedirect(path + "/login_ok.html");
}
else{
response.sendRedirect(path + "/login_failed.html");
}
}}
Getting additional information
• Client information
•
•
String request.getRemoteAddr()
String request.getRemoteHost()
• Server information
•
•
String request.getServerName()
int request.getServerPort()
• Misc
•
•
•
•
•
ServletInputStream getInputStream()
BufferedReader getReader()
String getProtocol()
String getContentType()
boolean isSecure()
Getting additional information
• Client information
•
•
String request.getRemoteAddr()
String request.getRemoteHost()
• Server information
•
•
String request.getServerName()
int request.getServerPort()
• Misc
•
•
•
•
•
ServletInputStream getInputStream()
BufferedReader getReader()
String getProtocol()
String getContentType()
boolean isSecure()
Demo Project
[Option 1] Git repository:
git clone
https://github.com/avasiljeva/servlet_jsp_demo.git
[Option 2] SVN repository:
http://www.ante.lv/svn/files-antelv/trunk/servlet_jsp_demo
SVN username/password:
student/student
Servlet Interfaces & Classes
interfaces
classes
Servlet Life Cycle
•
The life cycle of a servlet is controlled by the
container
•
When a HTTP request is mapped to a servlet, the
container performs the following steps
1. If an instance of the servlet does not exist, the web
container
a. Loads the servlet class
b. Creates an instance of the servlet class
c. Initializes the servlet instance by calling the init
method
2. Invokes the service method, passing request and
response objects
Servlet Life Cycle Methods
Servlet Life Cycle Methods
• Invoked by container
•
container controls life cycle of a servlet
• Defined in
•
javax.servlet.GenericServlet class
• init()
• destroy()
• service() - this is an abstract method
•
javax.servlet.http.HttpServlet class
• doGet(), doPost(), doXxx()
• service() - implementation
init() & destroy()
• init()
•
•
•
Invoked once when the servlet is first instantiated
Not called for each request
Perform any set-up in this method
• setting up a database connection
• destroy()
•
•
•
Invoked before servlet instance is removed
Not called after each request
Perform any clean-up
• closing a previously created database connection
Example: init()
public class CatalogServlet extends HttpServlet {
private BookDB bookDB;
// Perform any one-time operation for the servlet,
// like getting database connection object.
// Note: In this example, database connection object is assumed
// to be created via other means (via life cycle event
// mechanism)
// and saved in ServletContext object. This is to share a same
// database connection object among multiple servlets
public void init() throws ServletException {
bookDB = (BookDB)getServletContext().getAttribute("bookDB");
if (bookDB == null)
throw new UnavailableException("Couldn't get database");
}
...
}
Example: destroy()
public class CatalogServlet extends HttpServlet {
private BookDB bookDB;
public void init() throws ServletException {
bookDB = (BookDB)getServletContext().
getAttribute("bookDB");
if (bookDB == null)
throw new UnavailableException(
"Couldn't get database");
}
public void destroy() {
// close connection and other clean-up
bookDB = null;
}
...
}
service()
•
•
•
Is called in a new thread by a server for each request
Dispatches to doGet, doPost, etc
service() methods take generic requests and responses:
service(ServletRequest request, ServletResponse response)
• Do not override
this method!
doGet, doPost, doXxx
• Handles GET, POST and other requests
• Override these to provide desired behaviour
Servlet thread-safety
• Servlet code is called in a separate thread each
time
• Carefully synchronize access to shared data
(instance variables) using synchronization
(e.g. synchronized keyword, atomic counters etc)
public class ThreadSafeServlet implements Servlet {
private int counter;
public void service(ServletRequest request,
ServletResponse response)
synchronized(this) {
++counter;
}
}
}
RequestDispatcher
• Applications are often composed of many
Servlets working together
• Forwarding a request to another Servlet is
possible using RequestDispatcher
• RequestDispatcher primary functions
• forward - complete transfer of control to another
Servlet
• include - insert result from running another
Servlet into response
Dispatching to another component
public class ServletForward extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException{
// pathname is relative to invoking servlet
RequestDispatcher dispatcher =
request.getRequestDispatcher("another_servlet");
dispatcher.forward(request, response);
}
}
Including another component 1
public class ServletIncludeParent extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println("<html><head></head>");
out.println("<body>ServletIncludeParent start<br/>");
RequestDispatcher dispatcher =
request.getRequestDispatcher("servlet_include_child");
dispatcher.include(request, response);
out.println("ServletIncludeParent finish");
out.println("</body></html>");
out.close();
}
}
Including another component 2
public class ServletIncludeChild extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println("ServletIncludeChild<br/>");
}
}
Output:
ServletIncludeParent start
ServletIncludeChild
ServletIncludeParent finish
Sending redirect
Redirect means sending a response from servlet to
the browser that tells the browser to go to (make a
brand new request for) another URL or page
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
String contextPath = request.getContextPath();
response.sendRedirect(contextPath + "/redirect.jsp");
}
}
RequestDispatcher vs Redirect
• forward() is server-side,
sendRedirect() is client-side
• When using forward(), the target servlet receives
the same request/response objects as the original
servlet 
•
you can pass data between them using
request.setAttribute()
•
With a sendRedirect() the only way to pass data is
through the session or with web parameters
• A sendRedirect() also updates the browser history
Servlet initialization parameters
<servlet>
<servlet-name>DemoServlet3</servlet-name>
<servlet-class>com.web.demo.DemoServlet3</servlet-class>
<init-param>
<param-name>my_param</param-name>
<param-value>my_value</param-value>
</init-param>
</servlet>
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
String value = getServletConfig()
.getInitParameter("my_param");
String theSameValue = getInitParameter("my_param");
}
Scope Objects
• Enables sharing information among
collaborating web components via attributes
maintained in Scope objects
•
Attributes are name/object pairs
• Attributes maintained in the Scope objects are
accessed with
•
getAttribute() & setAttribute()
• Four Scope objects are defined
•
Web context, session, request, page
Four Scope Objects: Accessibility
• Web context
•
Accessible from Web components within a Web
context
• Session
•
Accessible from Web components handling a request
that belongs to the session
• Request
•
Accessible from Web components handling the
request
• Page
•
Accessible from JSP page that creates the object
Four Scope Objects: Classes
• Web context
javax.servlet.ServletContext
• Session
javax.servlet.http.HttpSession
• Request
javax.servlet.http.HttpServletRequest
• Page
javax.servlet.jsp.PageContext
WebContext (ServletContext)
Used by servlets to
•
•
Set and get context-wide (application-wide)
object-valued attributes
Get request dispatcher
• To forward to or include web component
•
•
•
•
Access Web context-wide initialization parameters
set in the web.xml file
Access Web resources associated with the Web
context
Log
Access other misc information
Scope of ServletContext
• There is one ServletContext object per
"web application" per Java Virtual Machine
How to Access ServletContext?
Within your servlet code, call
getServletContext()
public class CatalogServlet extends HttpServlet {
private BookDB bookDB;
public void init() throws ServletException {
// Get context-wide attribute value from
// ServletContext object
bookDB = (BookDB)getServletContext().
getAttribute("bookDB");
if (bookDB == null)
throw new UnavailableException(
"Couldn't get database");
}
Logging
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
...
getServletContext().log(“Life is good!”);
...
getServletContext().log(“Life is bad!”, someException);
Writes the specified message to a servlet log file,
usually an event log. The name and type of the
servlet log file is specific to the servlet container.
Session Tracking
• Why session tracking?
•
•
•
User registration
Web page settings
On-line shopping cart
• HTTP is stateless!
• Have to use specific methods:
•
•
•
Cookies
Hidden Form Fields
URL Rewriting
Cookies
• Idea: associate cookie with data on server
String sessionID = makeUniqueString();
HashMap sessionInfo = new HashMap();
HashMap globalTable = findTableStoringSessions();
globalTable.put(sessionID, sessionInfo);
Cookie sessionCookie =
new Cookie("JSESSIONID", sessionID);
sessionCookie.setPath("/");
response.addCookie(sessionCookie);
• Still to be done:
•
•
•
•
Extracting cookie that stores session identifier
Setting appropriate expiration time for cookie
Associating the hash tables with each request
Generating the unique session identifiers
Hidden Form Fields
• Idea:
<INPUT TYPE="HIDDEN" NAME="session" VALUE="...">
• Advantage
•
Works even if cookies are disabled or unsupported
• Disadvantages
•
•
Lots of tedious processing
All pages must be the result of form submissions
URL Rewriting
• Idea
•
•
•
Client appends some extra data on the end of each URL
that identifies the session
Server associates that identifier with data it has stored
about that session
E.g., http://host/path/file.html;jsessionid=1234
• Advantage
•
Works even if cookies are disabled or unsupported
• Disadvantages
•
•
•
Must encode all URLs that refer to your own site
All pages must be dynamically generated
Fails for bookmarks and links from other sites
The Session Tracking API
Session tracking API built on top of URL
rewriting or cookies
•
Look up HttpSession object associated with current
request (or create new one)
• All cookie/URL rewriting mechanics hidden
•
Look up information associated with a session
•
Associate information with a session
Example: Looking Up Session
HttpSession session = request.getSession(true);
ShoppingCart sc = (ShoppingCart)
session.getAttribute("shoppingCart");
if (cart == null) {
cart = new ShoppingCart();
session.setAttribute("shoppingCart", cart);
}
...
// do something with your shopping cart object
HttpSession Methods
• getAttribute(String name)
•
Extracts a previously stored value from a session object. Returns null
if no value is associated with given name.
• setAttribute(name, value)
•
Associates a value with a name. Monitor changes: values implement
HttpSessionBindingListener.
• removeAttribute(name)
•
Removes values associated with name
• getAttributeNames()
•
Returns names of all attributes in the session
• getId()
•
Returns the unique identifier
HttpSession Methods
• isNew()
•
Determines if session is new to client (not to page)
• getCreationTime()
•
Returns time at which session was first created
• getLastAccessedTime()
•
• Returns time at which session was last sent from client
getMaxInactiveInterval, setMaxInactiveInterval
•
Gets or sets the amount of time session should go without
access before being invalidated
• invalidate()
•
Invalidates current session
Servlets Filters
Servlet filters
• A filter is an object that can transform the header
and content (or both) of a request or response
• Filters typically do not themselves create responses
• Filter provides functionality that can be “attached”
to any kind of web resource
• Filters provide the ability to encapsulate recurring
tasks in reusable units
Servlet filter main tasks
• Query the request and act accordingly
• Block the request-and-response pair from passing
any further
• Modify the request/response headers and data
• Interact with external resources
Servlet filter applications
•
Authentication
•
•
Logging and auditing
•
•
Making downloads smaller
Localization
•
•
Scaling maps, and so on
Data compression
•
•
Tracking users of a web application
Image conversion
•
•
Blocking requests based on user identity
Targeting the request and response to a particular locale
XSLT transformations of XML content
•
Targeting web application responses to more that one type of client
Using filters
• In summary, the tasks involved in using filters are
•
Programming the filter
• javax.servlet.Filter
• javax.servlet.FilterChain
• javax.servlet.FilterConfig
• javax.servlet.annotation.WebFilter
•
Programming customized requests and responses
•
Specifying the filter chain for each web resource
Sample filter
public final class HitCounterFilter implements Filter {
private FilterConfig filterConfig = null;
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
public void destroy() {
this.filterConfig = null;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
. . .
// do some job
chain.doFilter(request, wrapper);
. . .
}
}
Customized Requests/Responses
•
A filter that modifies a response must usually capture the
response before it is returned to the client
•
To do this, you pass a stand-in stream to the servlet that
generates the response
•
To pass stand-in stream to the servlet, the filter creates a
response wrapper that overrides the getWriter or
getOutputStream method
•
To override request/response methods, you wrap the request
in an object that extends (Http)ServletRequestWrapper
or (Http)ServletResponseWrapper
Example: CharResponseWrapper
public class CharResponseWrapper extends
HttpServletResponseWrapper {
private CharArrayWriter output;
public String toString() {
return output.toString();
}
public CharResponseWrapper(HttpServletResponse response){
super(response);
output = new CharArrayWriter();
}
public PrintWriter getWriter(){
return new PrintWriter(output);
}
}
Specifying Filter Mappings
• The last step is to specify how to apply a filter to
a web component or a set of web components
•
Declare the filter using the <filter> element in
the web application deployment descriptor
•
Map the filter to a servlet by defining a
<filter-mapping> element in the deployment
descriptor
Sample filter configuration
<filter>
<filter-name>Compression Filter</filter-name>
<filter-class>CompressionFilter</filter-class>
<init-param>
<param-name>compressionThreshold</param-name>
<param-value>10</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Compression Filter</filter-name>
<servlet-name>CompressionTest</servlet-name>
</filter-mapping>
<servlet>
<servlet-name>CompressionTest</servlet-name>
<servlet-class>CompressionTest</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CompressionTest</servlet-name>
<url-pattern>/CompressionTest</url-pattern>
</servlet-mapping>
Filter Annotations
It is possible to replace XML configuration:
<filter>
<filter-name>Compression Filter</filter-name>
<filter-class>CompressionFilter</filter-class>
<init-param>
<param-name>compressionThreshold</param-name>
<param-value>10</param-value>
</init-param>
</filter>
by annotations in Java code:
@WebFilter(filterName = "CompressionFilter",
initParams = {
@WebInitParam(
name = "compressionThreshold", value = "10")})
public class CompressionFilter implements Filter {
....
Filter to Servlet Mapping
• You can map a filter to one or more servlets and
you can map more than one filter to a servlet
Servlet event listeners
•
You can monitor and react to events in a servlet’s life
cycle by defining listener objects whose methods get
invoked when life-cycle events occur
•
Implement listener interface
•
•
•
•
•
•
•
•
javax.servlet.ServletContextListener
javax.servlet.ServletContextAttributeListener
javax.servlet.ServletRequestListener
javax.servlet.ServletRequestAttributeListener
javax.servlet.http.HttpSessionListener
javax.servlet.http.HttpSessionAttributeListener
javax.servlet.http.HttpSessionBindingListener
Specify an event listener class in the deployment
descriptor
Example: ServletContextListener
public class MyListener implements ServletContextListener {
private ServletContext context = null;
public void contextInitialized(ServletContextEvent event) {
this.context = event.getServletContext();
// do some job, e.g. initialize database connection
}
public void contextDestroyed(ServletContextEvent event) {
// do some job, e.g. close database connection
this.context = null;
}
}
Register listener in web.xml:
<listener>
<listener-class>com.listeners.MyListener</listener-class>
</listener>
Or simply add annotation:
@WebListener()
public class MyListener implements ServletContextListener {
Using JPA in Servlets
Java Persistence API in Servlets
A simple scenario how to use Java Persistence API
from Servlet web application
1. Add JPA libraries to the project
2. Create the Persistence Class (@Entity)
3. Create the Data Access Object (DAO)
4. Obtain EntityManagerFactory in the
ServletContextListener and initialize DAO with it
git clone https://github.com/avasiljeva/servlet-jpa-app.git
JPA dependencies (Hibernate provider)
Add to pom.xml (Maven configuration file):
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.2.5.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.2.5.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
JPA dependencies (MySQL driver)
Add to pom.xml (Maven configuration file):
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
You may also use some other vendor driver if you
prefer different database
Creating an Entity
@Entity
public class Person {
@Id @GeneratedValue
private Long id;
private String fullName;
public Long getId() {
return id;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
}
Creating a DAO class
public class PersonDAO {
private EntityManagerFactory emf;
public PersonDAO(EntityManagerFactory emf){
this.emf = emf;
}
public void save(Person person){
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(person);
em.getTransaction().commit();
em.close();
}
}
Obtaining EntityManagerFactory
• In order to perform database operations, we need to
obtain an EntityManagerFactory instance
• We will use an application-managed approach
•
when using any kind of a container (e.g. Spring) more
convenient container-managed approach may be used
• A convenient approach is to create
EntityManagerFactory once, encapsulating it in
some sort of a singleton wrapper class
(PersistenceManager), and then use it for
different purposes
PersistenceManager
public class PersistenceManager {
private EntityManagerFactory emf;
private static final PersistenceManager INSTANCE = new PersistenceManager();
public static PersistenceManager getInstance() {
return INSTANCE;
}
private PersistenceManager() {}
public EntityManagerFactory getEntityManagerFactory() {
if (emf == null) createEntityManagerFactory();
return emf;
}
protected void createEntityManagerFactory() {
this.emf = Persistence.createEntityManagerFactory("p_unit");
}
public void closeEntityManagerFactory() {
if (emf != null) {
emf.close();
emf = null;
}}}
Creating EntityManagerFactory
@WebListener
public class PersistenceContextListener
implements ServletContextListener {
public void contextInitialized(ServletContextEvent event) {
ServletContext context = event.getServletContext();
EntityManagerFactory emf =
PersistenceManager.getInstance().getEntityManagerFactory();
PersonDAO personDAO = new PersonDAO(emf);
context.setAttribute("personDAO", personDAO);
}
public void contextDestroyed(ServletContextEvent event) {
PersistenceManager.getInstance().closeEntityManagerFactory();
}
}
Using DAO in a Servlet
@WebServlet("/person")
public class PersonServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String fullName = request.getParameter("full_name");
Person person = new Person();
person.setFullName(fullName);
PersonDAO dao = (PersonDAO)request
.getServletContext().getAttribute("personDAO");
dao.save(p);
}
}
persistence.xml location
• JPA configuration file persistence.xml should
be placed inside WAR file in:
\<WAR>\WEB-INF\classes\META-INF
• When using Maven directory structure, then valid
place for persistence.xml is:
\<project_root>\src\main\resources\META-INF
References
• Java EE 7 Tutorial “Java Servlet Technology”
http://docs.oracle.com/javaee/7/tutorial/doc/serv
lets.htm
• Java Servlet 3.1 Specification
http://jcp.org/aboutJava/communityprocess/final/j
sr340/index.html
• JPA EntityManagerFactory in web applications
http://javanotepad.blogspot.com/2007/05/jpaentitymanagerfactory-in-web.html