0% found this document useful (0 votes)
21 views55 pages

Backend Development and Servlets: Lek Hsiang Hui

The document discusses backend development using JavaEE and servlets. It recaps persistence frameworks and entity relationships, and how to use Java Persistence API for object relational mapping. Servlets are introduced as components for frontend development.

Uploaded by

keeweikuang123
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)
21 views55 pages

Backend Development and Servlets: Lek Hsiang Hui

The document discusses backend development using JavaEE and servlets. It recaps persistence frameworks and entity relationships, and how to use Java Persistence API for object relational mapping. Servlets are introduced as components for frontend development.

Uploaded by

keeweikuang123
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/ 55

LECTURE 2

BACKEND
DEVELOPMENT
AND SERVLETS
LEK HSIANG HUI

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
LEARNING OBJECTIVES
At the end of this lecture, you should:
• Recall how to do backend development using
JavaEE (Recap of IS2103)
• Understand how create web clients using servlets
and JSP

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
2
JAVA EE APPLICATION ARCHITECTURE

Frontend
Development

Backend
Development
(Quick recap
in this lecture)

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
3
JAVA EE COMPONENTS
Backend:
• Recap: Persistence Framework
• Recap: Session Beans
Frontend:
• Servlets

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
4
PERSISTENCE
FRAMEWORK
Persistence Session
Framework Beans Servlets JSP

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
5
PERSISTENCE FRAMEWORK
convert from table form into object
form means object relational
mapping

Java Persistence API (JPA) performs Object


Relational Mapping (ORM)
• Mapping Entity classes to relational database
tables
• Loading data from relational database into Entity
objects

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
6
ENTITY CLASS
Persistence package: javax.persistence.*
Annotated with @Entity
Must at least have a public or protected, no-
argument constructor
Persistent fields:
• Java primitive type
• String
• Serializable types such as java.util.Date
Collection-valued persistence field should use the
java.util.* collection interfaces

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
7
ENTITY CLASS
Persistent fields should use the JavaBean getter/setter
convention
Should have a unique identifier (primary key) annotated
with @Id
• Often want to use generate primary key automatically:
@GeneratedValue(strategy = GenerationType.IDENTITY)
Must implement Serializable if entity can be sent as a
detached object

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
8
ENTITY RELATIONSHIPS
MULTIPLICITY
javax.persistence.*
@OneToOne
• Each entity instance is mapped to a single instance of
another entity
@OneToMany
• Each entity instance is mapped to multiple instances of
another entity
@ManyToOne
• Opposite of One-to-many
@ManyToMany
• Entity instances can be mapped to multiple instances of
each other

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
9
Use mappedBy for
bi-directional case
EXAMPLE

@Entity @Entity
public class SalesOrder public class Shipment
@Id @Id
private Long shipmentId;
private Long salesOrderId;
@OneToOne(mappedBy="shipment")
@OneToOne private SalesOrder salesOrder;
private Shipment shipment; ...
... }
}

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
10
EXAMPLE

@Entity
public class Employee{
@Id
private Long employeeId;
@ManyToOne
private Company company;
@ManyToOne
private BusinessAddress businessAddress;
...
}
©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
11
EXAMPLE
@Entity
public class Company{
@Id
private Long companyId;
@OneToMany(mappedBy="company")
private List<Employee> employees;
...
}
@Entity
public class BusinessAddress{
@Id
private long businessAddressId;
...
}

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
12
Persistence context ------------------------- Database

entity will be persisted in the persistence context first and in a timely


manner, the database will synchrnise with the persistence context

ENTITYMANAGER API
persist() : Make new entity instance managed
and persistent em.merge is when you recieve something from
user and update the database

merge() : Update the state of an unmanaged


entity instance into the persistence context
refresh() : Fetch the latest persistent state from
datasource
remove() : Remove an entity instance
flush() : Force synchronization of persistent
state to the datasource database, to get the latest technology
use refresh and flush when many technologies such as php,javee etc using

detach(): Make the entity instance unmanaged

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
13
JAVA PERSISTENCE QUERY
LANGUAGE
Used to query the underlying database

“Object-oriented SQL” : referencing class


name (and attributes) rather than actual
table names

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
14
JAVA PERSISTENCE QUERY
LANGUAGE
Example:
public List <Member> getAllMembers()
{
Query query = em.createQuery("SELECT m FROM Member m");
return query.getResultList();
}

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
15
JAVA PERSISTENCE QUERY
LANGUAGE
Possible to define parameters:
public List<Member> searchMember(String name)
{
Query query = entityManager.createQuery(
"SELECT m FROM Member m WHERE LOWER(m.name) LIKE :name");
query.setParameter("name", "%" + name.toLowerCase() + "%");

return query.getResultList();
}

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
16
SESSION BEANS

Persistence Session
Framework Beans Servlets JSP

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
17
SESSION BEANS
Server-side components that captures
business logic

These business methods are typically


exposed through interfaces

EJB container manage the


creation/destruction/reusing of the beans

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
18
STATELESS VS STATEFUL SESSION
BEANS
Stateless session beans
• Does not maintain state across multiple method
calls
• E.g. method call takes in the required input
parameters and performs computation based
on the input
Stateful session beans
• Can maintain state, thus a business task can
be completed by a series of method
invocations
Use stateless session beans as far as possible

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
19
LOCAL VS REMOTE INTERFACE
Local interface
• Client must be running in the same JVM as the
enterprise bean
Remote interface
• Client can be running in another JVM
• Greater flexibility but potentially slower
Rule of thumb:
• Use local interface if EJB module and web
application are deployed on the same app server
• Use remote interface if need to distribute
components across multiple app server

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
20
EXAMPLE

@Local
public interface PersonSessionBeanLocal {...}

@Stateless
public class PersonSessionBean implements
PersonSessionLocal
{...}

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
21
Inject Session Bean in
Servlet
(To be elaborated later)

public class Controller extends HttpServlet {


@EJB
private PersonSessionBeanLocal personSessionBeanLocal

protected void processRequest(...) throws ... {


try {
//personSessionBeanLocal.XXX()

}
catch(Exception e) {…}
}
}

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
22
SERVLETS

Persistence Session
Framework Beans Servlets JSP

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
23
WEB CLIENT
Previously in IS2103, you have worked with
application client (desktop)

For enterprise systems, often we work with


web clients (i.e. users access the system
through a web browser)

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
24
CREATING PROJECT WITH WEB CLIENT

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
25
CREATING PROJECT WITH WEB CLIENT

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
26
CREATING PROJECT WITH WEB CLIENT

Make sure this is


checked
MyProject-war
Module will be created

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
27
JAVA SERVLETS
Primary web component for handling HTTP
requests/responses from/to client web
browser

Servlet serves as the Controller for


interacting with the View (i.e. JSP)

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
28
MVC
java class

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
29
CREATING A SERVLET

Subsequently, can create


a servlet by right click on
the war module

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
30
CREATING A SERVLET

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
31
CREATING A SERVLET

If this is not checked, URL


Pattern will be captured in
@WebServlet
annotation
©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
32
JAVA SERVLETS

@WebServlet(urlPatterns = {"/Controller/*"})
public class Controller extends HttpServlet{

//Inject session bean


@EJB
SomeSessionBeanLocal someSessionBeanLocal;

} Servlets extends
URL Pattern is how the HttpServlet
servlet will be triggered

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
33
JAVA SERVLETS
Servlets are triggered based on their url mapping
defined in web.xml (or @WebServlet annotation)
• E.g.
• URL Pattern: /Controller/* → Controller.java
• i.e. when user access
http://localhost:8080/[PROJECT]/Controller/
or
http://localhost:8080/[PROJECT]/Controller/AAA
(where AAA can be anything)
• It will trigger processing at Controller.java

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
34
CREATING A SERVLET

If this is checked, URL


Pattern will be captured in
web.xml
©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
35
WEB.XML

<?xml version="1.0" encoding="UTF-8"?>


<web-app version="3.1" xmlns="…">
<servlet>
<servlet-name>Controller</servlet-name>
<servlet-class>servlet.Controller</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Controller</servlet-name>
<url-pattern>/Controller/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
36
HTTP REQUESTS
Receives request data through:
• HTTP GET: Query string parameters
• HTTP POST: Form parameters
• Uses the name attribute of HTML element
not id
Client web browser sends HTTP GET:
http://localhost:8080/MyApp-war/Servlet?name=john

Servlet processes HTTP GET Request:


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

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
37
JAVA SERVLETS
Servlets handle HTTP requests via the service
methods
• doPost() and doGet()
typically, both call processRequest() to
handle the processing

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
38
JAVA SERVLETS
@WebServlet(urlPatterns = {"/Controller/*"})
public class Controller extends HttpServlet{

@Override
protected void doGet(…) throws ServletException, IOException {
processRequest(request, response);
}

@Override
protected void doPost(…) throws ServletException, IOException {
processRequest(request, response);
}

protected void processRequest(…)throws ServletException,


IOException{

}
}
©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
39
controller is the customer service offer,
for example it will redirect to the correct department Forward to a JSP to
display the HTML
PROCESSREQUEST
protected void processRequest(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String path = request.getPathInfo();

//depending on path do the necessary processing
//which includes calling the session bean

//redirect to JSP
request.getRequestDispatcher("/" + path + ".jsp")
.forward(request, response);
}

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
40
From the Files tab
-EJB MODULE

Move glassfish-resources.xml
Delete ejb-jar.xml
to the setup folder

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
41
-EJB MODULE

After entities and


session beans are
created you might get
a javax.persistence
and javax.ejb does
not exist error

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
42
-EJB MODULE From the Projects tab

Add the Persistence (JPA 2.1) and


Java EE 8 API Library libraries
©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
43
-WAR MODULE

You might encounter a


package javax.servlet does not exist error

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
44
ADD LIBRARIES

Add Java EE Web 8 API


Library to the Libraries of
the
–war module
©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
45
BEANS.XML

Sometimes, there
could be some
problems injecting
the EJB in the
servlet without a
beans.xml. Create
an empty file called
beans.xml in the
Web Pages/WEB-
INF folder

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
46
BEANS.XML Either google a
beans.xml template
or use the following

<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
version="1.2" bean-discovery-mode="annotated">
<!-- some content -->
</beans>

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
47
JSP

Persistence Session
Framework Beans Servlets JSP

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
48
JSP
JSP = Java Server Pages
HTML pages that allow dynamic content to
be rendered
• HTML/CSS/Javascript
• Dynamic content: Scriptlets and JSP Tags
Build on Java Servlet technology
• Compiled into servlet during deployment

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
49
EXAMPLE (SCRIPTLETS)
<%@ page import="java.util.*" %>
<%@ page import="entity.*" %>
<html><body>
<table>
<tr><th>Member Id</th><th>Name</th></tr>
request to get from the controller that
<% is called 'list'

List<Member> members = (List<Members>) request.getAttribute("list");


for(Member member : members) {
%>
<tr>
<td><%=member.getId()%></td>
<td><%=member.getName()%></td>
</tr>
<% } %>
</table>
</body></html>

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
50
JSP TAGS
JavaServer Pages Standard Tag Library
(JSTL) can also be used
• Core tags : Variable support, flow control,
URL management and miscellaneous
• Function tags : Collection length and string
manipulation

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
51
JSTL CORE TAGS
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

Variable support:
• <c:set var="name" scope="session" value="..."/>
• <c:remove var="name" scope="session"/>
Flow control:
• <c:if test="${invalidLogin == 'true'}">...</c:if>
• <c:choose><c:when test="...">...</c:when> ...
<c:otherwise>...</c:otherwise></c:choose>
• <c:forEach var="item" items="${items}">
...${item.val}...</c:forEach>

${…} performs immediate evaluation (used for “get” cases)


#{…} performs deferred evaluation (used for “get”/“set” cases)
©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
52
EXAMPLE (JSTL)
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html><body>
<table>
<tr><th>Member Id</th><th>Name</th></tr>
<c:forEach var="member" items="${list}">
<tr>
<td>${member.id}</td>
<td>${member.name} </td>
</tr>
</c:forEach>
</table> Similar to
</body></html> request.getAttribute("list")

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
53
SUMMARY
Quick recap of Java EE development
Java EE components:
• Persistence framework
• Session Beans
• Servlets

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
54
WHAT’S NEXT?
JSF

©2024 Lek Hsiang Hui. All rights reserved. No part of this document may be reproduced or transmitted in any form or by any
means, electronic or otherwise, without prior written permission of the owner.
55

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy