integrating spring @mvc with jquery and bootstrap
DESCRIPTION
Integrating Spring @MVC with jQuery and Bootstrap. Michael Isvy. Michael Isvy. Trainer and Senior Consultant Joined SpringSource in 2008 Already taught Spring in more than 20 countries Core-Spring, Spring MVC, Spring with JPA/Hibernate, Apache Tomcat… - PowerPoint PPT PresentationTRANSCRIPT
Integrating Spring @MVC with jQuery and Bootstrap
Michael Isvy
• Trainer and Senior Consultant– Joined SpringSource in 2008
– Already taught Spring in more than 20 countries• Core-Spring, Spring MVC, Spring with JPA/Hibernate, Apache
Tomcat…
• Active blogger on blog.springsource.com
Michael Isvy
2
History
3
2004
2008 French division created
2009 VMware acquires SpringSource
2012 Many « new Emerging Products » at VMware:CloudFoundry, GemFire, RabbitMQ …
我
Spring 1.0
SpringSource created (originally called Interface21)
…
Spring 1.0??
Inspired from a blog entry
4
http://blog.springsource.org/2012/08/29/
JSP file
• General Spring MVC best practices• Adding jQuery (Javascript)• Adding Bootstrap (CSS)• Avoiding JSP soup
Agenda
5
HTMLJavascriptCSSTaglibs
General Spring MVC best practices
• Many people like it because it is simple
Why Spring MVC?
• InfoQ top 20 Web frameworks for the JVM– Spring MVC number 1
Why Spring MVC?
http://www.infoq.com/research/jvm-web-frameworks
• Survey from zeroturnaround– Spring MVC number 1
Why Spring MVC?
http://zeroturnaround.com/labs/developer-productivity-report-2012-java-tools-tech-devs-and-data/
• Which way is more appropriate?
How to use Spring MVC?
10
public class UserController extends SimpleFormController {
public ModelAndView onSubmit(Object command) { //... }
}
@Controllerpublic class UserController {
@RequestMapping(value="/users/", method=RequestMethod.POST) public ModelAndView createUser(User user) { //... }
}
Deprecated!!
• Programmatic validation?
Validation with Spring MVC
11
class DiningValidator extends Validator { public void validate(Object target, Errors errors) { if ((DiningForm)target) .merchantNumber.matches("[1-9][0-9]*") ) errors.rejectValue(“merchantNumber”, “numberExpected”); }}
Not the preferred way anymore!
• Bean validation (JSR 303) annotations
Validation with Spring MVC
12
import javax.validation.constraints.*;public class Dining { @Pattern(regexp="\\d{16}") private String creditCardNumber;
@Min(0) private BigDecimal monetaryAmount;
@NotNull private Date date;}
POJO
• Bean validation (JSR 303)
Validation with Spring MVC
import javax.validation.Valid;…@Controllerpublic class UserController {
@RequestMapping("/user") public String update(@Valid User user, BindingResult result) { if (result.hasErrors()) { return “rewards/edit”; } // continue on success... }}
Controller
• Form tag library
View Layer
14
<c:url value="/user.htm" var="formUrl" /><form:form modelAttribute="user" action="${formUrl}"> <label class="control-label">Enter your first name:</label> <form:input path="firstName"/> <form:errors path="firstName"/> ... <button type="submit”>Save changes</button></form:form>
JSP
JSP best practices!!
15
JSP: Which way is better?
16
<tr> <td> <%=user.getFirstName() %></td> <td> <%=user.getLastName() %> </td></tr>
<tr> <td> ${user.firstName} </td> <td> ${user.lastName} </td></tr>
<tr> <td> <c:out value="${user.firstName}"/> </td> <td> <c:out value="${user.lastName}"/> </td></tr>
Not perfect: it is better to use taglibs
Not perfect: it is better to use taglibs
No html escape: risk for cross site scripting
No html escape: risk for cross site scripting
Good!Good!
jsp file
Jar files best practices
One word about Webjars
Is it good?
18
Version numbers!!!Version numbers!!!
Best practices
19
• Manage version numbers using Maven or Gradle
<dependency> <groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId><version>3.1.3.RELEASE</version>
</dependency><dependency> <groupId>junit</groupId>
<artifactId>junit</artifactId><version>4.10</version><scope>test</scope>
</dependency>
Maven POM file pom.xml
Maven POM file pom.xml
Version numbers?
20
Let’s talk about Webjars!Let’s talk about Webjars!
<link href="/bootstrap/css/bootstrap.css" rel="stylesheet"/>
<script src="/js/addThis.js"></script><script src="/js/jquery-ui.js"></script><script src="/js/jquery.dataTables.js"></script><script src="/js/jquery.js"></script>
JSP file
• Allow CSS and JS libraries to be imported as Maven libraries– jQuery, jQuery-ui, bootstrap, backbonejs…
– http://www.webjars.org/
Webjars
Webjars
<dependency> <groupId>org.webjars</groupId> <artifactId>jquery-ui</artifactId> <version>1.9.1</version></dependency>
pom.xml
Using Webjars
23
• Inside pom.xml Spring configuration
• Inside JSP
<dependency> <groupId>org.webjars</groupId> <artifactId>jquery-ui</artifactId> <version>1.9.1</version></dependency>
<link rel=“stylesheet" href= “ /webjars/jquery-ui/1.9.1/js/jquery-ui-1.9.1.custom.js">
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>
。 js file is inside a jar file!。 js file is inside a jar file!
Adding jQuery
• Javascript framework• Very simple core with thousands of plugins available
– Datatable
– jQuery UI (datepicker, form interaction…)
What is jQuery?
Why jQuery?
jquery-ui
• One of the most popular jQuery plugins– Autocomplete
– Date picker
– Drag and drop
– Slider
– …
• Let us get started with dates!
jqueri-ui
• java.util.Date
• Joda Time
• JSR 310: Date and time API
How do you use dates in Java?
29
Only for very simple useOnly for very simple use
GOOD!GOOD!
Not available yetMay be in 2013
Not available yetMay be in 2013
Integrates well with Spring MVCIntegrates well with Spring MVC
jqueryui date picker
30
<script> $( "#startDate" ).datepicker({ dateFormat: "yy-m-dd" }); $( "#endDate" ).datepicker({ dateFormat: "yy-m-dd" });</script>…<form:input path="startDate" /><form:input path="endDate" />
JSP file
Adding jQuery
Datatable
• jQuery plugin for datatables• Click, sort, scroll, next/previous…• http://datatables.net/
jQuery datatables
• You don’t even need to write Javascript yourself!• Just use DataTables4J
– http://datatables4j.github.com/docs/
Datatables in Spring MVC
<dependency><groupId>com.github.datatables4j</groupId><artifactId>datatables4j-core-impl</artifactId><version>0.7.0</version>
</dependency>
pom.xml
• Inside JSP file
Datatables in Spring MVC
34
<datatables:table data="${userList}" id="dataTable" row="user"><datatables:column title="First Name"
property="firstName" sortable="true" />
<datatables:column title="Last Name" property="lastName" sortable="true" />
</datatables:table>
JSP file
Bootstrap
Let’s talk about CSS…
• So your Web Designer does not have to cry anymore
Why Bootstrap?
Let’s talk about Bootstrap!Let’s talk about Bootstrap!
• Originally called “Twitter Bootstrap”• Available from 2011• Typography, forms, buttons, charts, navigation and other
interface components• Integrates well with jQuery
What is Bootstrap?
• Most popular project on github!
What is Bootstrap?
https://github.com/popular/starred
• Hundreds of themes available– So your website does not look like all other websites!
– Some are free and some are commercial
• Example: www.bootswatch.com/
Bootstrap themes
Avoiding JSP soup
JSP file
HTMLJavascriptCSSTaglibs
• Our application now looks good in a web browser
• What about the internals?– We can do better!
Avoiding JSP soup
• Should be your best friend when working with JSPs!
• Can easily turn 100 lines of code into 10 lines of code!
JSP custom tags
• Custom tags are part of Java EE– .tag or .tagx files
• Created in 2004– Not a new feature!
Custom tags
43
Form fields: Without custom tags
<div class=“control-group” id=“${lastName}"><label class="control-label">${lastNameLabel}</label><div class="controls">
<form:input path="${name}"/><span class="help-inline">
<form:errors path="${name}"/></span>
</div></div>
CSS divLabelForm input
Error message (if any)
JSP
• First create a tag (or tagx) file
Using custom tags
<%@ taglib prefix="form" uri="http://www.spring…org/tags/form" %><%@ attribute name="name" required="true" rtexprvalue="true" %><%@ attribute name="label" required="true" rtexprvalue="true" %><div class="control-group" id="${name}">
<label class="control-label">${label}</label><div class="controls">
<form:input path="${name}"/><span class="help-inline">
<form:errors path="${name}"/></span>
</div></div>
inputField.tag
• Custom tag call
Using custom tags
Folder which contains custom tags
<html xmlns:custom="urn:jsptagdir:/WEB-INF/tags/html" …> … <custom:inputField name="firstName" label="Enter your first name:" /> <custom:inputField name=”lastName" label="Enter your last name:" /></html>
JSP file
1 line of code instead of 9!!
No more JSP soup!
• Consider using WebJars for static files– http://www.webjars.org/
• It’s easy to integrate Spring MVC with jQuery– Consider using DataTables4J – http://datatables4j.github.com/docs/
– Bootstrap is cool!– JSP custom tags can make your life easier
Conclusion
47
Thank You!