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… • Active blogger on blog.springsource.com 2 History 2004 Spring 1.0 … SpringSource created (originally called Interface21) 2008 French division created 我 3 Spring 1.0?? 2009 VMware acquires SpringSource 2012 Many « new Emerging Products » at VMware: CloudFoundry, GemFire, RabbitMQ … Inspired from a blog entry http://blog.springsource.org/2012/08/29/ 4 Agenda • • • • 5 General Spring MVC best practices Adding jQuery (Javascript) Adding Bootstrap (CSS) Avoiding JSP soup HTML Javascript CSS Taglibs JSP file General Spring MVC best practices Why Spring MVC? • Many people like it because it is simple Why Spring MVC? • InfoQ top 20 Web frameworks for the JVM – Spring MVC number 1 http://www.infoq.com/research/jvm-web-frameworks Why Spring MVC? • Survey from zeroturnaround – Spring MVC number 1 http://zeroturnaround.com/labs/developer-productivity-report-2012-java-toolstech-devs-and-data/ How to use Spring MVC? • Which way is more appropriate? public class UserController extends SimpleFormController { @Controller public class UserController { @RequestMapping(value="/users/", method=RequestMethod.POST) public ModelAndView createUser(User user) { //... } public ModelAndView onSubmit(Object command) { //... } } } Deprecated!! 10 Validation with Spring MVC • Programmatic validation? 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! 11 Validation with Spring MVC • Bean validation (JSR 303) annotations import javax.validation.constraints.*; public class Dining { @Pattern(regexp="\\d{16}") private String creditCardNumber; @Min(0) private BigDecimal monetaryAmount; @NotNull private Date date; } 12 POJO Validation with Spring MVC • Bean validation (JSR 303) import javax.validation.Valid; … @Controller public class UserController { @RequestMapping("/user") public String update(@Valid User user, BindingResult result) { if (result.hasErrors()) { return “rewards/edit”; } // continue on success... } } Controller View Layer • Form tag library <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> 14 JSP JSP best practices!! 15 JSP: Which way is better? <tr> <td> <%=user.getFirstName() %></td> <td> <%=user.getLastName() %> </td> </tr> Not perfect: it is better to use taglibs jsp file <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> 16 No html escape: risk for cross site scripting Good! Jar files best practices One word about Webjars Is it good? Version numbers!!! 18 Best practices • 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> 19 Maven POM file pom.xml Version numbers? <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 Let’s talk about Webjars! 20 Webjars • Allow CSS and JS libraries to be imported as Maven libraries – jQuery, jQuery-ui, bootstrap, backbonejs… – http://www.webjars.org/ Webjars <dependency> <groupId>org.webjars</groupId> <artifactId>jquery-ui</artifactId> <version>1.9.1</version> </dependency> pom.xml Using Webjars • Inside pom.xml Spring configuration <dependency> <groupId>org.webjars</groupId> <artifactId>jquery-ui</artifactId> <version>1.9.1</version> </dependency> <mvc:resources mapping="/webjars/**" location="classpath:/METAINF/resources/webjars/"/> • Inside JSP <link rel=“stylesheet" href=“/webjars/jquery-ui/1.9.1/js/jquery-ui-1.9.1.custom.js"> 。js file is inside a jar file! 23 Adding jQuery What is jQuery? • Javascript framework • Very simple core with thousands of plugins available – Datatable – jQuery UI (datepicker, form interaction…) Why jQuery? jquery-ui jqueri-ui • One of the most popular jQuery plugins – – – – – Autocomplete Date picker Drag and drop Slider … • Let us get started with dates! How do you use dates in Java? • java.util.Date Only for very simple use • Joda Time GOOD! Integrates well with Spring MVC • JSR 310: Date and time API 29 Not available yet May be in 2013 jqueryui date picker <script> $( "#startDate" ).datepicker({ dateFormat: "yy-m-dd" }); $( "#endDate" ).datepicker({ dateFormat: "yy-m-dd" }); </script> … <form:input path="startDate" /> <form:input path="endDate" /> JSP file 30 Adding jQuery Datatable jQuery datatables • jQuery plugin for datatables • Click, sort, scroll, next/previous… • http://datatables.net/ Datatables in Spring MVC • You don’t even need to write Javascript yourself! • Just use DataTables4J – http://datatables4j.github.com/docs/ <dependency> <groupId>com.github.datatables4j</groupId> <artifactId>datatables4j-core-impl</artifactId> <version>0.7.0</version> </dependency> pom.xml Datatables in Spring MVC • Inside JSP file <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 34 Bootstrap Let’s talk about CSS… Why Bootstrap? • So your Web Designer does not have to cry anymore Let’s talk about Bootstrap! What is 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! https://github.com/popular/starred Bootstrap themes • 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/ Avoiding JSP soup HTML Javascript CSS Taglibs JSP file Avoiding JSP soup • Our application now looks good in a web browser • What about the internals? – We can do better! JSP custom tags • Should be your best friend when working with JSPs! • Can easily turn 100 lines of code into 10 lines of code! Custom tags • Custom tags are part of Java EE – .tag or .tagx files • Created in 2004 – Not a new feature! 43 Form fields: Without custom tags JSP <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 div Label Form input Error message (if any) Using custom tags • First create a tag (or tagx) file <%@ 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 Using custom tags • Custom tag call 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! Conclusion • 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 47 Thank You!