Upload
sraveendra
View
215
Download
0
Embed Size (px)
Citation preview
7/28/2019 Web Development Using Spring MVC
1/61
Web DevelopmentUsing Spring MVC
Wenjie He
Gateway JUG, Nov. 4, 2008
7/28/2019 Web Development Using Spring MVC
2/61
Project Description
Mobile Member Portal
for Express Scripts, Inc. (ESI)
Main Requirements:
Built in ESI Framework-- Spring MVC/Castrol/XSL
Capable of being viewed from the Blackberry (and
iPhone) mobile web browser
2
7/28/2019 Web Development Using Spring MVC
3/61
ESI Member Portal (1)
Regular Web Version
Login page
3
7/28/2019 Web Development Using Spring MVC
4/61
ESI Member Portal (2)
Regular Web Version
Main page
4
7/28/2019 Web Development Using Spring MVC
5/61
ESI Member Portal (3)
Regular Web Version
My Prescriptions Check Order Status
5
7/28/2019 Web Development Using Spring MVC
6/61
Demonstration of Mobile Version
Still under development
Look and feel on iPhone
6
7/28/2019 Web Development Using Spring MVC
7/61
Background of Development Team
16 students in my Advanced Javaclass
A few students in my Independent Studyclass
At least half of the students only know coreJava, but not Java EE.
None of the students knows about the SpringFramework.
The students are organized in four groups.
7
7/28/2019 Web Development Using Spring MVC
8/61
Development Phases
Develop using Servlets and JSP
Teaching Java EE basics
Get experience in web development
Two months Develop using Spring and Hibernate
Learning + Developing in one months
Only use Spring MVC basic features
8
7/28/2019 Web Development Using Spring MVC
9/61
Development Tools
Database: HSQLDB
IDE: Eclipse
Build tool: Ant
Server: Tomcat
Framework: Spring
Persistence: Hibernate
9
7/28/2019 Web Development Using Spring MVC
10/61
User Interface Design
Login page and main page HTLM + CSS
10
7/28/2019 Web Development Using Spring MVC
11/61
Introduction to Spring Framework
Target on Enterprise JavaBeans (EJB)
Heavy weight vs. light weight
Example: transaction support
Testing: Test-Driven Design (TDD) Tight coupling vs. loose coupling
11
7/28/2019 Web Development Using Spring MVC
12/61
Why Spring in This Project?
ESI requirements
Make web development more efficient
Streamline the procedure
Regular Servlets & JSP vs. Spring approach Testability
Easy maintenance
12
7/28/2019 Web Development Using Spring MVC
13/61
Spring Web MVC
One of the several modules in Spring
Model-View-Controller (MVC) pattern
Separate user interface from application logic
View user interface
Model data and business services
Controller interactions between model and view
Easier to reuse code
Easier to maintain web applications
Other popular MVC frameworks: Struts, JSF
13
7/28/2019 Web Development Using Spring MVC
14/61
Front Controller Design Pattern
A front controller is a common web-application
pattern Entry point of the framework
The first place a request meets the application
A central servlet that dispatches requests tocontrollers
The Spring web MVC is designed aroundorg.springframework.web.servlet.DispatcherServlet
It is integrated with the Spring IoC container.
IoC Inverse of Control
14
7/28/2019 Web Development Using Spring MVC
15/61
Diagram ofRequest Processing Workflow
15
7/28/2019 Web Development Using Spring MVC
16/61
Library JAR Files
Database: server + driver
hsqldb.jar (691k)
Spring MVC: spring.jar, spring-webmvc.jar
JSTL:jstl.jar, standard.jar
Hibernate3: hibernate3.jar, and some more
Hibernate tools:
hibernate-tools.jar, freemaker.jar Servlets: servlet-api.jar
16
7/28/2019 Web Development Using Spring MVC
17/61
Setting Properties for Database
In build.properties
hsqldb.lib=/JavaEE/DBMS/hsqldb/lib db.name=esimobiledb
hsqldb.dbfile=file:db/${db.name}
hsqldb.dbalias=${db.name}
db.driver=org.hsqldb.jdbcDriver
db.url=jdbc:hsqldb:hsql://localhost/${db.name} db.user=sa
db.pw=17
7/28/2019 Web Development Using Spring MVC
18/61
Ant Target to Start DB Server
7/28/2019 Web Development Using Spring MVC
19/61
Setting Properties for Tomcat
In build.properties appserver.home=/JavaEE/Servers/Tomcat/apache-tomcat-
6.0.18
appserver.bin=${appserver.home}/bin
appserver.lib=${appserver.home}/lib
deploy.path=${appserver.home}/webapps
tomcat.manager.url=http://localhost:8080/manager tomcat.manager.username=tomcat
tomcat.manager.password=javaee
19
7/28/2019 Web Development Using Spring MVC
20/61
Ant Target to Start Tomcat
20
7/28/2019 Web Development Using Spring MVC
21/61
Configuration of Front Controller
In web.xml
esiMobile
org.springframework.web.servlet.DispatcherServlet
2
esiMobile *.htm
21
7/28/2019 Web Development Using Spring MVC
22/61
Loading Spring Application Context
:
Developer chooses the servlet name forDispatcherServlet
In this example, we use esiMobile
Default Spring application context file: esiMobile-servlet.xml
When DispatcherServlet is loaded, the Spring
application context in esiMobile-servlet.xml isloaded.
22
7/28/2019 Web Development Using Spring MVC
23/61
Choosing URL Pattern for Spring MVC
We can choose any URL pattern for
DispatcherServlet
esiMobile
*.htm
Convention for most Spring MVC applications:
*.htm
They are virtual URLs. No such HTML filesexist.
23
7/28/2019 Web Development Using Spring MVC
24/61
Object/Relational Mapping by Hibernate
Mapping Java objects to database tables
Most useful in the Java-based middle-tier
Encapsulate vendor-specific SQL code
Reduces the effort needed to convert betweenrelational database result-sets and graphs ofJava objects
24
7/28/2019 Web Development Using Spring MVC
25/61
Start with a Table in Database
create table USER (
userid varchar(30) not null, username varchar(30), password varchar(30), firstname varchar(40), lastname varchar(40), email varchar(50), accountType varchar(20), lastlogintime date, primary key (userid) );
25
7/28/2019 Web Development Using Spring MVC
26/61
Persistent Class for the Table
public class User {
private String userid; private String username; private String password; private String firstname; private String lastname; private String email; private String accountType; private Date lastlogintime; public void setUserid(String userid) { this.userid = userid; }
26
7/28/2019 Web Development Using Spring MVC
27/61
Hibernate Mapping Files
User.hbm.xml
7/28/2019 Web Development Using Spring MVC
28/61
Hibernate Configuration File
Hibernate.cfg.xml
org.hsqldb.jdbcDriver jdbc:hsqldb:hsql://localhost/esimobiledb sa
org.hibernate.dialect.HSQLDialect
28
7/28/2019 Web Development Using Spring MVC
29/61
Using Hibernate Toolsto Generate Artifacts
Create Hibernate mapping files,
e.g. User.hbm.xml Create Hibernate configuration file,
hibernate.cfg.xml
Run an Ant target to generate databaseschema
Run an Ant target to generate persistentclasses
29
7/28/2019 Web Development Using Spring MVC
30/61
Generate Database Schema
30
7/28/2019 Web Development Using Spring MVC
31/61
Generate Java Persistent Classes
31
7/28/2019 Web Development Using Spring MVC
32/61
Data Access Objects: Base Class
public class DAO {
public static Session getSession() { Session session = (Session) DAO.session.get(); if (session == null) { session = sessionFactory.openSession();
DAO.session.set(session); } return session; }
protected void begin() { getSession().beginTransaction(); }
32
7/28/2019 Web Development Using Spring MVC
33/61
Data Access Object for a Table
public class UserDAO extends DAO {
public User getByUsername(String username) throwsDatabaseException {
try { begin();
Query q = getSession().createQuery( "from User where username = :username"); q.setString("username", username); User user = (User) q.uniqueResult(); commit(); return user; }
33
7/28/2019 Web Development Using Spring MVC
34/61
Bird View of Following Steps
Data binding
Validation
Authentication (services)
Navigation
All built around controllers
34
7/28/2019 Web Development Using Spring MVC
35/61
Spring MVC Controllers
Central piece in Spring MVC pattern
Responsible for dealing with browser requests
Bridge between end user and applicationsservices
A controller is configured as anotherJavaBean in the Spring application context.
webweb DispatcherServlet Controller Service
35
7/28/2019 Web Development Using Spring MVC
36/61
Mapping URLs to Controllers
In esiMobile-servlet.xml
loginESImobileController activateController activateAController usernameController
36
7/28/2019 Web Development Using Spring MVC
37/61
Spring MVC Command Objects
A command object is a bean that holds the request
parameters for easy access. A POJO (Plain Old Java Object) that has fields that
can be accessed via setters and getters
Data binding mapping form fields to the commandclass
Store the data
form fields properties of command
Populate the fields of the form
properties of command form fields
37
7/28/2019 Web Development Using Spring MVC
38/61
An Example of Command Class
public class LoginCommand {
private String userId; private String password;
public String getPassword() { return password; } public void setPassword(String password) { this.password = password; }
38
7/28/2019 Web Development Using Spring MVC
39/61
Presenting Model with a View
After processing, the controller sends the
results back to browser. Mapping view names to actual pages
Displaying data in the model in the view pages
The view and model data is encapsulated in aModelAndView object.
Every controller execution method must return
a ModelAndView object.
39
7/28/2019 Web Development Using Spring MVC
40/61
Declaring a View Resolver
The ModelAndView object contains a logical viewname of the view page.
A view resolver maps the logical view name to a realview page.
In esiMobile-servlet.xml org.springframework.web.servlet.view.JstlView
/WEB-INF/jsp/ .jsp
40
MainPage
/WEB-INF/jsp/MainPage.jsp
7/28/2019 Web Development Using Spring MVC
41/61
Building a Controller:LoginESImobileController (1)
package com.javux.esimobile.controllers;
import com.javux.esimobile.commands.LoginCommand; import com.javux.esimobile.dao.UserDAO; import com.javux.esimobile.services.AuthenticationService; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.validation.BindException; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.SimpleFormController;
public class LoginESImobileController extendsSimpleFormController { private AuthenticationService authenticationService; private UserDAO userDAO;
41
7/28/2019 Web Development Using Spring MVC
42/61
Building a Controller:LoginESImobileController (2)
protected ModelAndView onSubmit(HttpServletRequest request,HttpServletResponse response,
Object command, BindException errors) throws Exception{
HttpSession session = request.getSession( true ); LoginCommand loginCommand = (LoginCommand) command; String username = loginCommand.getUserId();
session.setAttribute("username",username);
if ( authenticationService.authenticate(request, loginCommand,userDAO) ) {
return new ModelAndView(getSuccessView());
} else { request.setAttribute("pass","fail");
return showForm(request, response, errors); }
}42
7/28/2019 Web Development Using Spring MVC
43/61
Building a Controller:LoginESImobileController (3)
public void setAuthenticationService(
AuthenticationServiceauthenticationService) { this.authenticationService =
authenticationService;
}
public void setUserDAO(UserDAO udao) {
userDAO = udao; }
43
7/28/2019 Web Development Using Spring MVC
44/61
Dependency Injection (DI)
Making code simpler, easier to understand,
and easier to test. Traditional way:
Objects responsible for obtaining its own
references Lead to highly coupled and hard-to-test code
DI way:
Objects are given their dependencies at creationtime by the container
Loose coupling44
7/28/2019 Web Development Using Spring MVC
45/61
Benefit of Loose Coupling
The depending object only knows about its
dependencies by their interface Not their implementation
Not how they are instantiated
The dependency can be swapped out with adifferent implementation
ClassAInjected into
InterfaceB
implementation1
implementation2
45
7/28/2019 Web Development Using Spring MVC
46/61
Breaking up Application Context
Splitting the application context file into logical
pieces can make maintenance easier. Putting the beans of services in
esiMobile-services.xml
Configuring the context loader contextConfigLocation /WEB-INF/esiMobile-services.xml
7/28/2019 Web Development Using Spring MVC
47/61
Configuring Beans
in esiMobile-services.xml
47
UserDAO userDAO = new UserDAO();
7/28/2019 Web Development Using Spring MVC
48/61
Configuring Controllers
in Application Context (1)
In esiMobile-servlet.xml
Configuring the command
true loginCommand
com.javux.esimobile.commands.LoginCommand
48
7/28/2019 Web Development Using Spring MVC
49/61
Configuring Controllers
in Application Context (2)
Configuring bean properties
49
C fi i C ll
7/28/2019 Web Development Using Spring MVC
50/61
Configuring Controllers
in Application Context (3)
Configuring views
SignIn
MainPage
50
7/28/2019 Web Development Using Spring MVC
51/61
How DI Works
When creating bean loginESImobileController
Instantiating an instance of UserDAO
UserDAO userDAO = new UserDAO();
Injecting userDAO into loginESImobileController
loginESImobileController.setUserDAO(userDAO);
It is done by the container implicitly.
51
7/28/2019 Web Development Using Spring MVC
52/61
Validating Form Input public class EmailLoginValidator implements Validator {
public boolean supports(Class clazz) {return EmailLoginCommand.class.equals(clazz); }
public void validate(Object obj, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email","error.email.empty");EmailLoginCommand elc = (EmailLoginCommand) obj;
if ( elc.getEmail().length() > 0) {
if (elc.getEmail().indexOf("@") < 0) {errors.rejectValue("email", "error.email.invaid");}
}} 52
7/28/2019 Web Development Using Spring MVC
53/61
Rendering Externalized Mesages
Put all the messages in the file
resources/messages.properties In esiMobile-servlet.xml
In JSP
53
7/28/2019 Web Development Using Spring MVC
54/61
Binding Form Data (1)
54
7/28/2019 Web Development Using Spring MVC
55/61
Binding Form Data (2) Username:
7/28/2019 Web Development Using Spring MVC
56/61
Binding to a Drop Down Box (1)
7/28/2019 Web Development Using Spring MVC
57/61
Binding to a Drop Down Box (2)
7/28/2019 Web Development Using Spring MVC
58/61
Summarize
Dependency Injection
Loose coupling Spring MVC configuration
Bean (service) configuration
Controller configuration
Validation
Data binding
7/28/2019 Web Development Using Spring MVC
59/61
7/28/2019 Web Development Using Spring MVC
60/61
7/28/2019 Web Development Using Spring MVC
61/61