Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Spring One China 2012 (Beijing)

Michael Isvy
December 08, 2012

Spring One China 2012 (Beijing)

Integrating Spring MVC with jQuery, Bootstrap, DataTables4J and webjars

Michael Isvy

December 08, 2012
Tweet

More Decks by Michael Isvy

Other Decks in Technology

Transcript

  1. •  The github project used for my demos is available

    here: •  https://github.com/michaelisvy/demo-springone-beijing demos
  2. •  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 3
  3. History 4 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??
  4. JSP  file •  General  Spring  MVC  best  prac8ces   • 

    Adding  jQuery  (Javascript)   •  Adding  Bootstrap  (CSS)   •  Avoiding  JSP  soup   Agenda 6 HTML Javascript CSS Taglibs
  5. •  InfoQ top 20 Web frameworks for the JVM – 

    Spring MVC number 1 Why Spring MVC? http://www.infoq.com/research/jvm-web-frameworks
  6. •  Survey from zeroturnaround –  Spring MVC number 1 Why

    Spring MVC? http://zeroturnaround.com/labs/developer-productivity-report-2012-java-tools- tech-devs-and-data/
  7. •  Which way is more appropriate? How to use Spring

    MVC? 11 public class UserController extends SimpleFormController { public ModelAndView onSubmit(Object command) { //... } } @Controller public class UserController { @RequestMapping(value="/users/", method=RequestMethod.POST) public ModelAndView createUser(User user) 
 { //... } } Deprecated!!
  8. •  Programmatic validation? Validation with Spring MVC 12 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!
  9. •  Bean validation (JSR 303) annotations Validation with Spring MVC

    13 import javax.validation.constraints.*; public class Dining { 
 @Pattern(regexp="\\d{16}") private String creditCardNumber; @Min(0) private BigDecimal monetaryAmount; @NotNull private Date date; } POJO
  10. •  Bean validation (JSR 303) Validation with Spring MVC 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
  11. •  Form tag library View Layer 15 <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
  12. JSP: Which way is better? 17 <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 No html escape: risk for cross site scripting Good! jsp file
  13. Best practices 20 •  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
  14. Version numbers? 21 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
  15. •  Allow CSS and JS libraries to be imported as

    Maven libraries –  jQuery, jQuery-ui, bootstrap, backbonejs… –  http://www.webjars.org/ Webjars
  16. Using Webjars 24 •  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!
  17. •  Javascript framework •  Very simple core with thousands of

    plugins available –  Datatable –  jQuery UI (datepicker, form interaction…) What is jQuery?
  18. •  One of the most popular jQuery plugins –  Autocomplete

    –  Date picker –  Drag and drop –  Slider –  … •  Let us get started with dates! jqueri-ui
  19. •  java.util.Date •  Joda Time •  JSR 310: Date and

    time API How do you use dates in Java? 30 Only for very simple use GOOD! Not available yet May be in 2013 Integrates well with Spring MVC
  20. jqueryui date picker 31 <script> $( "#startDate" ).datepicker({ dateFormat: "yy-m-dd"

    }); $( "#endDate" ).datepicker({ dateFormat: "yy-m-dd" }); </script> … <form:input path="startDate" /> <form:input path="endDate" /> JSP file
  21. •  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
  22. •  Inside JSP file Datatables in Spring MVC 35 <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
  23. •  So your Web Designer does not have to cry

    anymore Why Bootstrap? Let’s talk about Bootstrap!
  24. •  Originally called “Twitter Bootstrap” •  Available from 2011 • 

    Typography, forms, buttons, charts, navigation and other interface components •  Integrates well with jQuery What is Bootstrap?
  25. •  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
  26. •  Our application now looks good in a web browser

    •  What about the internals? –  We can do better! Avoiding JSP soup
  27. •  Should be your best friend when working with JSPs!

    •  Can easily turn 100 lines of code into 10 lines of code! JSP custom tags
  28. •  Custom tags are part of Java EE –  .tag

    or .tagx files •  Created in 2004 –  Not a new feature! Custom tags 44
  29. 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 div Label Form input Error message (if any) JSP
  30. •  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
  31. •  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!
  32. •  Consider  using  WebJars  for  sta8c  files   –  http://www.webjars.org/

      •  It’s  easy  to  integrate  Spring  MVC  with  jQuery   –  Consider  using  DataTables4J     –  hOp://datatables4j.github.com/docs/   –  Bootstrap  is  cool!   –  JSP  custom  tags  can  make  your  life  easier   Conclusion 48