Lecture1 - Java Server Pages-Đã G P PDF
Lecture1 - Java Server Pages-Đã G P PDF
Instructor: CUONGPNB1
Know about
Java Server
Pages (JSP)
Can use JSP
to build Web
application
JSP INTRODUCTION
JSP vs Servlet:
Code snippet
<%
String username = "alliant";
out.println(username);
%>
Code snippet
<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Directive tag</title>
</head>
<body>
<%@include file="Header.jsp"%>
<hr />
<h2>This is main content</h2>
<h4 style="color: red"><%=new Date()%></h4>
<hr />
<%@include file="Footer.jsp"%>
</body>
</html>
Code snippet
<h3 align="left">TRAINEE FULL INFORMATION</h3>
<table>
<tr>
<th>Id</th>
<th>Trainee Name</th>
<th>Salary</th>
</tr>
<!-- traineeData: a list of trainee -->
<c:forEach items="${traineeData}" var="trainee">
<tr>
<td>${trainee.getId()}</td>
<td>${trainee.getName()}</td>
<td>${trainee.getSalary()}</td>
</tr>
</c:forEach>
</table>
©FPT SOFTWARE - Corporate Training Center - Internal Use 18
Action tags (1/2)
Action (<%action... %>
JSP Actions lets you perform some action.
Provide access to common tasks performed in a JSP:
• Including content from other resources.
• Forwarding the user to another page.
• Interacting with JavaBeans.
Delimited by <jsp:action> and </jsp:action>.
side-bar
content
2. If the included file is changed but not the JSP which is including it then the changes
will reflect only when we use include action tag. The changes will not reflect if you
are using include.
3. Syntax difference.
4. When using include action tag we can also pass the parameters to the included page
by using param action tag but in case of include directive it’s not possible.
Code snippet
<jsp:useBean id="account" class="ctc.fr.atjb.bean.Account">
<jsp:setProperty property="emailAddress" name="account" />
<jsp:setProperty property="password" name="account" />
<h3>
Welcome,
<jsp:getProperty property="emailAddress" name="account" /><br>
</h3>
You have been successfully Logged in...
</jsp:useBean>
<!--ViewStock.jsp -->
<%
String stockCode = request.getParameter("stockCode");
String stockName = request.getParameter("stockName");
String description = request.getParameter("des");
%>
©FPT SOFTWARE - Corporate Training Center - Internal Use 34
Implicit Objects
Response
Can use
Servlet to
develop web
application
Understand
Servlet
INTRODUCTION TO SERVLET
1 2
Then the Servlet uses response object to write the response back to the
client. 5 6
Servlet container provides the execution The Web container manages a servlet by
environment for Servlet. invoking various life cycle methods.
©FPT SOFTWARE - Corporate Training Center - Internal Use 10
Section 2
SERVLET API
Example:
Closes the output stream, flushes the output buffer and sends the
©FPT SOFTWARE - Corporate Training Center - Internal Use information to the client. 26
Create Deployement Descriptor
1 <!DOCTYPE web-app PUBLIC
Deployment
2 "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
3 "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"> descriptor
4 Element web-app defines the configuration of (web.xml) for
5 <web-app>
each servlet in the Web application and the servlet the Web
6
7 <!-- General description
mapping for each servlet.
of your Web application --> application.
8 <display-name>
Element display-name specifies a name
9 Sample
10 Servlet Examples
that can be displayed to the administrator
11 </display-name> of the server on which the Web
12 application is installed.
13 <description>
Element description specifies a
14 This is the Web application in which we
15 demonstrate our JSP and Servlet examples.
description of the Web application that
16 </description> might be displayed to the administrator of
17 the server.
18 <!-- Servlet definitions -->
19 <servlet> Element servlet describes a servlet. Element servlet-name is the
20 <servlet-name>welcome</servlet-name>
name for the servlet.
21
22 <description> Element description
23 A simple servlet that handles an HTTP get request. specifies a description for this
24 </description>
particular servlet.
25
26 <servlet-class> Element servlet-class specifies
27 atjb.day3.WelcomeServlet compiled servlet’s fully
28 </servlet-class> qualified class name.
29 </servlet>
30
User Login
Instructor:
JSP Model 1, 2
1 Controller Model:
(Servlet) – Information is provided in
2 objects or beans
View:
Model
(Beans) – The JSP provide the view
3 Controller:
View 4 – Servlet provides control
View logic and becomes the
View
5 (JSPs)View
(JSPs) controller
View
(JSPs)
(JSPs)
(JSP)
Controller
1: Post 2: Retrieve Data
Browser Servlet Data
Resource
3: Establish
bean state,
then place in
4: redirect to session or
appropriate view request
object
5: Access beans
JSP Beans
Option 1 Option 2
DAO
JSP1 JSP3
JSP2
JSP Model 1, 2
Can use
Servlet to
develop web
application
Understand
Servlet
EXCEPTION HANDLING
Code snippet
<%@ page isErrorPage="true"%> Makes JSP page an error handler
<html>
<head>
<title>Error Page</title>
</head>
<body>
<h3>Due to following reasons an error has occurred</h3>
<ul>
<li><%=exception.getClass()%></li> Returns error message
<li><%=exception.getMessage()%></li>
</ul>
</body>
</html>
ErrorPage.jsp
©FPT SOFTWARE - Corporate Training Center - Internal Use 8
Exception Handling
Code snippet
<%@ page errorPage="ErrorPage.jsp"%> Forwards the unhandled exception to errorpage.jsp
<html>
<head>
<title>Form</title>
</head>
<body>
<form>
<table>
<tr>
<td>Enter a number :</td>
<td><input type="text" name="number" /></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
<%
String num = request.getParameter("number");
if (num != null) {
String number = num.trim();
int no = Integer.parseInt(number);
int value = 100 / no; Code occurs error
}
%>
</body>
</html>
SESSION TRACKING
Advantages
Remember user IDs and password.
To track visitors on a Web site for better service and new features.
Cookies enable efficient ad processing.
Disadvantages
The size and number of cookies stored are limited.
Personal information is exposed to the other users.
Cookies fails to work if the security level is set too high in the Internet
browser.
Servlet CookieServlet
Handles both get and post requests
The session ID is encoded in the URLs that are created by the JSP pages
<b>Search results for books</b>
<form method="post" action="serverprogram.jsp"> URL of server side program
// Provides check box for different products
<input type="checkbox" name="productID" value="100">
CD MP3 Converter Kit For Your CAR<br>
<input type="checkbox“ name="productID" value="101">
Front Loading Car MP3/CD Player With Anti Shock Memory and FM<br>
<input type="checkbox“ name="productID" value="102">
CAR/Home DVD/VCD/MP3 Playerwith anti shock for Indian Roads<br>
// Submits the user input to URL
<input type="submit“ name="Submit" value="Add to Cart"><br>
</form>
// URL for server side program after the user selects a product
// and goes to another page
<form method="post" action="serverprogram.jsp?productID=102">
// Provides check box for different products
<input type="checkbox" name="productID" value="150">
DVD Player with built in Amplifier <br>
<input type="checkbox" name="productID" value="160">
Ultra Slim DVD Player Multi Region 5.1 Digital<br>
// Submits input to the URL
<input type="submit" name="Submit" value="Add to Cart"> <br>
</form>
SERVLET FILTER
LoginServlet
user_login.jsp AppFilter
2 • Spring IoC
3 • Spring Bean
4 • Dependency Injection
5 • SpEL
SPRING IOC
public Employee() {
}
//getter-setter methods
}
Employee
-----
- empId Client
- empName -----
- address Container + main()
------
+ getter
+ setter
Bean Class
XML file
Demo Class
Run
Bean Class
XML file
Demo Class
Run
//getter-setter
}
Bean Class
XML file
Demo Class
Run
Result
Initial!
Employee details: Employee [empId=1, empName=Jack, address=Eastern Shores]
Employee details: Employee [empId=2, empName=Jennie, address=Shouthern Shores]
Destroy!
SPRING BEAN
public Address() {
// getter-setter methods
}
global session Scopes a single bean definition to the lifecycle of a global HTTP
Session. Typically only valid when used in a portlet context. Only
valid in the context of a web-aware Spring ApplicationContext.
SPRING DI
public Employee() {
this.empId = 0;
this.empName = "N/A";
this.address = new Address();
}
}
IOC
DI
Interface Service
Constructor Setter/Getter
Implementation Locator
SpEL
package com.fsoft.bean;
import org.springframework.beans.factory.annotation.Value;
@Component("addr")
public class Address {
@Value("Hanoi")
private String city;
@Value("Duytan")
private String street;
public Address() {
}
// ...
}
2 • Spring IoC
3 • Spring Bean
4 • Dependency Injection
5 • SpEL
Instructor:
2 • Spring Controller
3 • Resolving Views
4 • Spring @Autowired
5 • JdbcTemplate
INTRODUCTION
•Handler Mapping Maps incoming HTTP Requests to handlers, In spring MVC framework we use @Request
Step2 Mapping annotation to map the incoming Http Request with Model and View Object inside the controller class.
•Controller class in spring is implemented with the help of @Controller Annotation, which does model Map with data and
extracting a view name, it can also send directly as HTTP response without mapping the incoming request with model data
Step3 object.
•The Controller class has ModelAndView objectthat has the model or Data and the view name, the Controller class
executes the incoming request by calling the respective service method and returns ModelAndView Object to
Step4 DispatcherServlet.
•The DispatcherServlet will send the view name to a ViewResolver to find the original View (.jsp) page to display.
Step5
• The DispatcherServlet will then send the model object to View in order to render the
Step6 result.
• The view (.jsp) page will show the HTTP Response back to Client on the web browser.
Step7
is Servlet
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet-context.xml</param-value>
</context-param>
<servlet>
<servlet-name>dispatcher-servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher-servlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</beans>
SPRING CONTROLLER
RESOLVING VIEWS
XmlViewResolver This view resolver uses configuration file written in XML for
view resolution.
UrlBaseViewResolver This view resolver uses “logical view name” returned to find
actual view.
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.tiles3.TilesViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles3.TilesView
</value>
</property>
</bean>
@Override
protected ModelAndView handleRequestInternal(
HttpServletRequest request,HttpServletResponse response)
throws Exception {
return model;
}
}
<bean class="org.springframework.web.servlet.view.
ResourceBundleViewResolver">
<property name="basename" value= "spring-views" />
<property name="order" value="0" />
</bean>
@Override
protected ModelAndView handleRequestInternal(
HttpServletRequest request,HttpServletResponse response)
throws Exception {
return model;
}
}
course_list.(class) = org.springframework.web.servlet.view.JstlView
course_list.url = /views/pages/course_list.jsp
WelcomePage.(class) = org.springframework.web.servlet.view.JstlView
WelcomePage.url = /views/pages/WelcomePage.jsp
SPRING @AUTOWIRED
AddressServiceImpl AddressService
------ ------
+ getAllAddress() + getAllAddress()
AddressServiceImpl AddressService
------ ------
+ getAllAddress() + getAllAddress()
@Controller
public class AddressController {
@Autowired
private AddressService addressService;
return "address_list";
}
}
43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 37
Section 4
SPRING JDBCTEMPLATE
It takes care of creation and release of resources such as creating and closing of
connection object etc. So it will not lead to any problem if you forget to close the
connection.
It handles the exception and provides the informative exception messages by the
help of excepion classes defined in the org.springframework.dao package.
We can perform all the database operations by the help of JdbcTemplate class
such as insertion, updation, deletion and retrieval of the data from the database.
public int update(String query, is used to insert, update and delete records using
Object... args) PreparedStatement using given arguments.
public void execute(String query) is used to execute DDL query.
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName“
value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="url"
value="jdbc:sqlserver://1WDDIEUNT1-LT:1433;databaseName=FAMS" />
<property name="username" value="sa" />
<property name="password" value="12345678" />
</bean>
And index.jsp:
<body>
<h2>Welcome <span>${userName}</span>! </h2>
</body>
</html>
• Spring Autowrite
2
• JdbcTemplate
3
return "employeeView";
}
@ModelAttribute
public void addAttributes(Model model) {
model.addAttribute("msg",
"Welcome to the Netherlands!");
}
@GetMapping("/showViewPage")
public String passParametersWithModel(Model model) {
Map<String, String> map = new HashMap<>();
map.put("spring", "mvc");
model.addAttribute("message", “Welcome to Spring framework");
model.mergeAttributes(map);
return "viewPage";
}
return "hello";
}
@COMPONENT VS @REPOSITORY
AND @SERVICE IN SPRING
@Repository
public interface UserDao {
User login(User user) throws Exception;
}
@Repository("userDao")
@Transactional
public class UserDaoImpl implements UserDao {
@Autowired
private SessionFactory sessionFactory;
}
SPRING JDBCTEMPLATE
It takes care of creation and release of resources such as creating and closing of
connection object etc. So it will not lead to any problem if you forget to close the
connection.
It handles the exception and provides the informative exception messages by the
help of excepion classes defined in the org.springframework.dao package.
We can perform all the database operations by the help of JdbcTemplate class
such as insertion, updation, deletion and retrieval of the data from the database.
public int update(String query, is used to insert, update and delete records using
Object... args) PreparedStatement using given arguments.
public void execute(String query) is used to execute DDL query.
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName“
value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="url"
value="jdbc:sqlserver://1WDDIEUNT1-LT:1433;databaseName=FAMS" />
<property name="username" value="sa" />
<property name="password" value="12345678" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource"
ref="dataSource" /> <!-- Dependency Injection -->
<property name="packagesToScan" value="fa.training.entities" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.SQLServerDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
@Transactional
public void businessLogic() {
... use entity manager inside a transaction ...
}
@Pattern(regexp="^[A-Za-z0-9_]+$", message="{user.name.rex}")
@Size(max = 30, min = 8, message = "{user.name.invalid}")
@NotEmpty(message = "Please enter username")
@Column(name = "USERNAME", nullable = false, unique = true)
private String username;
@Column(name = "PASSWORD")
private String password;
List<User> list();
}
@Service
public class UserServiceImp implements UserService {
@Autowired
private UserDao userDao;
@Repository
@Transactional
public class UserDaoImp implements UserDao {
@Autowired
private SessionFactory sessionFactory;
@Override
public void save(User user) {
sessionFactory.getCurrentSession().save(user);
}
@Override
public List<User> list() {
TypedQuery<User> query = sessionFactory.getCurrentSession()
.createQuery("from User");
return query.getResultList();
}
}
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 27
Build a simple Web App
Demo!
@GetMapping("/api/employees/{id}")
@ResponseBody
public String getEmployeesById(@PathVariable String id) {
return "ID: " + id;
}
http://localhost:8080/api/employees/111
---- ID: 111
@GetMapping("/api/employeeswithvariable/{id}")
@ResponseBody
public String getEmployeesByIdWithVariableName(@PathVariable("id")
String employeeId) {
return "ID: " + employeeId;
}
@GetMapping("/api/employees/{id}/{name}")
@ResponseBody
public String getEmployeesByIdAndName(@PathVariable String id,
@PathVariable String name) {
return "ID: " + id + ", name: " + name;
}
Example:
http://localhost:8080/api/employees/1/bar
---- ID: 1, name: bar
http://localhost:8080/api/employeeswithrequiredfalse
---- ID missing
2
•Spring JdbcTemplate
3
•Spring Web MVC and Hibernate ORM
4
• Spring @Pathvariable Annotation
5
•Build a simple Web App (CRUD)
• @SessionAttributes or @SessionAttribute
3
@PostMapping("/api/foos")
public String addFoo( @RequestParam(name = "id") String fooId,
@RequestParam String name) {
return "ID: " + fooId + " Name: " + name;
}
http://localhost:8080/api/foos
---- ID: not provided
<tr>
<td>Interests:</td>
<%-- Approach 2: Property is of an array or of type java.util.Collection --%>
<td>Quidditch:
<form:checkbox path="interests" value="Quidditch" />
Herbology:
<form:checkbox path="interests" value="Herbology" />
Defence Against the Dark Arts:
<form:checkbox path="interests" value="Defence Against the Dark Arts" />
</td>
</tr>
<tr>
<td>Favourite Word:</td>
<%-- Approach 3: Property is of type java.lang.Object --%>
<td>Magic:
<form:checkbox path="favouriteWord" value="Magic" />
</td>
</tr>
</table>
</form:form>
@PostMapping("/subscription")
public String subcription(
@ModelAttribute("preferences") Preferences preferences,
Model model) {
LogUtils.getLogger().info(preferences);
return "newsletter_subscription";
}
Results:
@SESSIONATTRIBUTES OR
@SESSIONATTRIBUTE
/**
* Add user in model attribute.
*/
@ModelAttribute("user")
public User setUpUserForm() {
return new User();
}
@PostMapping("/dologin")
public String doLogin(@ModelAttribute("user") User user, Model model) {
return "index";
} else {
model.addAttribute("message", "Login failed. Try again.");
return "login";
}
}
return "index";
}
}
public MyOtherGlass() {
}
// getter and setter moethod
}
LogUtils.getLogger().info(largeGlass.isLargeGlass());
Results:
[INFO ] 2020-11-14 15:12:47.678 [http-nio-8080-exec-2]
LogUtils - false
[INFO ] 2020-11-14 15:12:47.680 [http-nio-8080-exec-2]
LogUtils - true
spring-servlet.xml file:
<!– Properties Spring -->
<bean class="org.springframework.beans.factory.config
.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:DBConfig.properties</value>
</list>
</property>
</bean>
<context:property-placeholder
location="classpath:data.properties, classpath:DBConfig.properties"
ignore-unresolvable="true" />
@Value("#{20 - 1}") // 19
private double subtract; @Value("#{36 div 2}") // 18, the same as for / operator
private double divideAlphabetic;
@Value("#{10 * 2}") // 20
private double multiply; @Value("#{37 % 10}") // 7
private double modulo;
@Value("#{36 / 2}") // 19
private double divide; @Value("#{37 mod 10}") // 7, the same as for % operator
private double moduloAlphabetic;
@Value("#{(2 + 2) * 2 + 9}") // 17
private double brackets;
We will add some fields to read the configuration from employee.properties using @Value
annotation. @Controller
Example: @SessionAttributes("user")
@PropertySource(value = "classpath:data.properties")
public class UserController {
@Value("#{'${MSG1}'}")
private String msg1;
@Value("#{'${MSG2}'}")
private String msg2;
@Value("#{'${MSG3}'}")
private String msg3;
@Value("#{'${MSG4}'}")
private String msg4;
@Value("#{'${MSG5}'}")
private String msg5;
@Value("#{'${technic_name}'.split(',')}")
private List<String> technics;
}
This interface also provides a way to add flash attributes and they will
be automatically propagated to the "output" FlashMap of the current
request.
After the redirect, flash attributes are automatically added to the model
of the controller that serves the target URL.
addAttribute(“attributeName”, “attributeValue”)
Add the supplied attribute under the supplied name.
model.asMap().get("key");
return "redirect:/success.jsp";
}
• @SessionAttributes or @SessionAttribute
3
• Interceptor
2
• Practice time
4
Spring form-validation
Controller
Phone validator
That will map any exceptions of type java.lang.ArithmeticException (or its sub
types) to the view named MathError.
During execution of a Spring controller, if such an exception is thrown, the client
will be redirected to the mapped view: /views/MathError.jsp:
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
model.addObject("sum", (a + b));
model.addObject("subtract", (a - b));
model.addObject("multiply", (a * b));
model.addObject("divide", (a / b));
return model;
}
}
return "done";
}
@ExceptionHandler({IOException.class, java.sql.SQLException.class})
public ModelAndView handleIOException(Exception ex) {
ModelAndView model = new ModelAndView("IOError");
model.addObject("exception", ex.getMessage());
return model;
}
}
model.addObject("exception", ex.getMessage());
return model;
}
public MyException() {
}
// getter and setter methods
}
@ExceptionHandler(MyException.class)
public ModelAndView handleMyException(MyException mex) {
@ExceptionHandler(Exception.class)
public ModelAndView handleException(Exception ex) {
}
}
if (exception.equalsIgnoreCase("error")) {
throw new MyException("A1001",
"This is a custom exception message.");
} else if (exception.equalsIgnoreCase("io-error")) {
throw new IOException();
} else {
return "success";
}
}
}
If the user provides a /error request, the controller method will throw the MyException, and the
ExceptionControllerAdvice.handleMyException() method will be invoked to handle the exception.
If the user provides a /io-error request, the controller method throw the IOException, and the
ExceptionControllerAdvice.handleException() method will be invoked to handle the exception.
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handleResourceNotFoundException() {
return "notFoundJSPPage";
}
}
if (exception.equalsIgnoreCase("error")) {
throw new MyException("A1001", "This is a custom exception message.");
} else if (exception.equalsIgnoreCase("io-error")) {
throw new IOException();
} else if (exception.equalsIgnoreCase("404")) {
throw new ResourceNotFoundException();
} else {
return "success";
}
}
}
SPRING INTERCEPTOR
postHandle()
View
response afterCompletion()
preHandle()=>index()=>postHandle()=>index.jsp=>afterCompletion()
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/user/**" />
<mvc:mapping path="/order/**" />
<mvc-exclude:mapping path="/user/login.htm" />
<mvc-exclude:mapping path="/user/register.htm" />
<mvc-exclude:mapping path="/user/forgot-passowrd.htm" />
<mvc-exclude:mapping path="/user/active.htm" />
<bean class="com.springmvc.LoggerInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
Login Logout
Instructor:
1 •Introduction
• Starter template
2
INTRODUCTION
SETUP
Notes:
This dependency, internally imports all given dependencies and add to your project.
Notice how some dependencies are direct, and some dependencies further refer to other starter
templates which transitively downloads more dependencies.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
STARTER DEPENDENCIES
spring-boot-starter-web-services spring-ws-core
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.
SpringBootApplication;
@SpringBootApplication
public class Application {
It enables the scanning of config classes, files and load them into spring
context.
In below example, execution start with main() method. It start loading all the
config files, configure them and bootstrap the application based on application
properties in application.properties file in /resources folder.
Step 2: provide the name, group, and package of the project. We have
provided:
Name: bfams
Group: fa.training
Package: fa.training
spring.datasource.url=jdbc:sqlserver://localhost;databaseName=FAMS1
spring.datasource.username=sa
spring.datasource.password=12345678
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.
SQLServerDriver
spring.jpa.show-sql=true
spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect
spring.jpa.hibernate.ddl-auto =none
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.4.0)
2020-11-20 16:46:40.403 INFO 920 --- [ main] fa.training.ServletInitializer : Starting ServletInitializer v0.0.1-SNAPSHOT using Java 1.8.0_211 on LPP00065422A with PID 920 (C:\Users\dieunt1\ecli
2020-11-20 16:46:40.422 INFO 920 --- [ main] fa.training.ServletInitializer : No active profile set, falling back to default profiles: default
2020-11-20 16:46:44.897 INFO 920 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFERRED mode.
2020-11-20 16:46:45.001 INFO 920 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 45 ms. Found 0 JPA repository interfaces.
2020-11-20 16:46:47.752 INFO 920 --- [ main] o.a.c.c.C.[.[.[/hrm_springbootwebmvc] : Initializing Spring embedded WebApplicationContext
2020-11-20 16:46:47.753 INFO 920 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 7055 ms
2020-11-20 16:46:49.504 INFO 920 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-11-20 16:46:50.121 INFO 920 --- [ task-1] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-11-20 16:46:50.956 WARN 920 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. E
2020-11-20 16:46:51.281 INFO 920 --- [ task-1] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.23.Final
2020-11-20 16:46:55.186 INFO 920 --- [ task-1] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2020-11-20 16:46:55.747 INFO 920 --- [ main] .s.s.UserDetailsServiceAutoConfiguration :
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
@Configuration
@EnableWebMvc
@ComponentScan
public class MvcConfiguration implements WebMvcConfigurer {
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
viewResolver.setViewClass(JstlView.class);
return viewResolver;
}
@GetMapping("/")
public String init(Model model) {
return "login";
}
@GetMapping("/index")
public String initIndex(Model model) {
return "index";
}
}
registry.addViewController("/savepassword")
.setViewName("savepassword.html");
registry.addViewController("/login")
.setViewName("login.html");
registry.addViewController("/")
.setViewName("loggedin/index.html");
h1 {
background-color: green;
color: red;
text-align: center;
}
<html>
<head>
<link href="/css/style.css"
rel="stylesheet">
</head>
<h1>Spring boot example</h1>
</html>
Automatic UI refresh
The spring-boot-devtools module includes an embedded LiveReload server
that can be used to trigger a browser refresh when a resource is changed.
Precondition is that your browser should have supported extention for it.
By default, live reload is enabled
application.properties
spring.devtools.livereload.enabled = false # Set false to disable live reload
1 •Introduction
2 • Starter template
1 • Introduction
4 • Query methods
INTRODUCTION
Spring Data JPA provides support for creating JPA repositories by extending
the Spring Data repository interfaces.
Spring Data Commons provides the infrastructure that is shared by the
datastore-specific Spring Data projects.
The JPA Provider (like hibernate) implements the Java Persistence API.
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
@NoRepositoryBean
public interface PagingAndSortingRepository < T, ID > extends CrudRepository < T, ID > {
/**
* Returns all entities sorted by the given options.
*
* @param sort
* @return all entities sorted by the given options
*/
Iterable < T > findAll(Sort sort);
/**
* Returns a {@link Page} of entities meeting the paging restriction provided in the
{@code Pageable} object.
*
* @param pageable
* @return a page of entities
*/
Page < T > findAll(Pageable pageable);
}
package org.springframework.data.jpa.repository;
import java.util.List;
import javax.persistence.EntityManager;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.QueryByExampleExecutor;
@NoRepositoryBean
public interface JpaRepository < T, ID > extends PagingAndSortingRepository < T, ID > ,
QueryByExampleExecutor < T > {
<S extends T > List < S > saveAll(Iterable < S > entities);
void flush();
void deleteAllInBatch();
T getOne(ID id);
@Override <
S extends T > List < S > findAll(Example < S > example);
@Override <
S extends T > List < S > findAll(Example < S > example, Sort sort);
}
Pageable sortedByPriceDesc =
PageRequest.of(0, 3,
Sort.by("price").descending());
Pageable sortedByPriceDescNameAsc =
PageRequest.of(0, 5,
Sort.by("price").descending()
.and(Sort.by("name")));
QUERY METHODS
We will create a query using the JPA criteria API from this but essentially this
translates into the following query:
findByFirstname,findByFirstnameIs,
Is,Equals … where x.firstname = 1?
findByFirstnameEquals
… … …
@Entity
@Table(name = "USERS")
@NamedQuery(name = "User.findByEmailAddress",
query = "select u from User u where u.emailAddress = ?1")
public class User {
1 • Introduction
4 • Query methods
•Introduction
1
INTRODUCTION
## Hibernate Properties
# The SQL dialect makes Hibernate generate better
# SQL for the chosen database
spring.jpa.properties.hibernate.dialect =
org.hibernate.dialect.MySQL5InnoDBDialect
spring.datasource.url=jdbc:sqlserver://localhost;
databaseName=HumanResourceDB
spring.datasource.username=sa
spring.datasource.password=12345678
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc
.SQLServerDriver
spring.jpa.show-sql=true
spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect
spring.jpa.hibernate.ddl-auto =update
@Column(name = "PASSWORD")
private String password;
@Path: used to specify the relative path of class and methods. We can get the
URI of a webservice by scanning the Path annotation value.
@GET, @PUT, @POST, @DELETE and @HEAD: used to specify the HTTP
request type for a method.
@Produces, @Consumes: used to specify the request and response types.
@PathParam: used to bind the method parameter to path value by parsing it.
/**
* Create user user.
*
* @param user the user
* @return the user
*/
@PostMapping("/add")
public User create(@Valid @RequestBody User user) {
return userService.save(user);
}
/**
* Create user user.
* @param user the user
* @return the user
*/
@PostMapping("/add")
public User create (@Valid @RequestBody User user) {
return userService.save(user);
}
userService.findById(userId).orElseThrow(
() -> new ResourceNotFoundException("User not found: "
+ userId, "404"));
return ResponseEntity.ok(updatedUser);
userService.delete(user);
return response;
@Autowired
private UserService userService;
/**
* The method to insert a new user into User table in DB.
*/
@PostMapping("/add")
public User create(@Valid @RequestBody User user) {
return userService.save(user);
}
}
// standard getters/setters
}
@Autowired
ExampleService exampleService;
@PostMapping("/response")
@ResponseBody
public ResponseTransfer postResponseController(
@RequestBody User user) {
return new ResponseTransfer("Thanks For Posting!!!");
}
}
In the developer console of our browser or using a tool like Postman, we
can see the following response:
{"text":"Thanks For Posting!!!"}
@GetMapping("/hello")
public ResponseEntity<String> hello() {
return new ResponseEntity<>("Hello World!",
HttpStatus.OK);
}
if (isInFuture(yearOfBirth)) {
return new ResponseEntity<>(
"Year of birth cannot be in the future",
HttpStatus.BAD_REQUEST);
}
@GetMapping("/customHeader")
public ResponseEntity<String> customHeader() {
@GetMapping("/hello")
public ResponseEntity<String> hello() {
return ResponseEntity.ok("Hello World!");
}
For the most popular HTTP status codes we get static methods:
BodyBuilder accepted();
BodyBuilder badRequest();
BodyBuilder created(java.net.URI location);
HeadersBuilder<?> noContent();
HeadersBuilder<?> notFound();
BodyBuilder ok();
@GetMapping("/age")
ResponseEntity<String> age(@RequestParam("yearOfBirth") int yearOfBirth) {
if (isInFuture(yearOfBirth)) {
return ResponseEntity.badRequest()
.body("Year of birth cannot be in the future");
}
return ResponseEntity.status(HttpStatus.OK)
.body("Your age is " + calculateAge(yearOfBirth));
}