480 likes | 641 Views
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…
E N D
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
History 2004 Spring 1.0 … SpringSource created (originally called Interface21) French division created 2008 Spring 1.0?? 我 VMware acquires SpringSource 2009 2012 Many « new Emerging Products » at VMware: CloudFoundry, GemFire, RabbitMQ … 3
Inspired from a blog entry http://blog.springsource.org/2012/08/29/
Agenda HTML Javascript CSS Taglibs JSP file General Spring MVC best practices Adding jQuery (Javascript) Adding Bootstrap (CSS) Avoiding JSP soup
Why Spring MVC? Many people like it because it is simple
Why Spring MVC? http://www.infoq.com/research/jvm-web-frameworks • InfoQ top 20 Web frameworks for the JVM • Spring MVC number 1
Why Spring MVC? http://zeroturnaround.com/labs/developer-productivity-report-2012-java-tools-tech-devs-and-data/ • Survey from zeroturnaround • Spring MVC number 1
How to use Spring MVC? @Controller publicclass UserController { @RequestMapping(value="/users/", method=RequestMethod.POST) public ModelAndView createUser(User user) { //... } } publicclass UserController extends SimpleFormController { public ModelAndView onSubmit(Object command) { //... } } Deprecated!! Which way is more appropriate?
Validation with Spring MVC class DiningValidator extends Validator { publicvoid validate(Object target, Errors errors) { if((DiningForm)target) .merchantNumber.matches("[1-9][0-9]*") ) errors.rejectValue(“merchantNumber”, “numberExpected”); } } Not the preferred way anymore! Programmatic validation?
Validation with Spring MVC import javax.validation.constraints.*; public class Dining { @Pattern(regexp="\\d{16}") private String creditCardNumber; @Min(0) privateBigDecimal monetaryAmount; @NotNull private Date date; } POJO Bean validation (JSR 303) annotations
Validation with Spring MVC import javax.validation.Valid; … @Controller publicclass UserController { @RequestMapping("/user") public String update(@Valid User user, BindingResult result) { if (result.hasErrors()) { return “rewards/edit”; } // continue on success... } } Controller Bean validation (JSR 303)
View Layer <c:urlvalue="/user.htm"var="formUrl"/> <form:formmodelAttribute="user"action="${formUrl}"> <labelclass="control-label">Enter your first name:</label> <form:inputpath="firstName"/> <form:errorspath="firstName"/> ... <buttontype="submit”>Save changes</button> </form:form> JSP Form tag library
JSP: Which way is better? <tr> <td><%=user.getFirstName() %></td> <td><%=user.getLastName() %></td> </tr> 1 Not perfect: it is better to use taglibs jsp file <tr> <td> ${user.firstName} </td> <td> ${user.lastName} </td> </tr> 2 No html escape: risk for cross site scripting <tr> <td><c:outvalue="${user.firstName}"/></td> <td><c:outvalue="${user.lastName}"/></td> </tr> 3 Good!
Jar files best practices One word about Webjars
Is it good? Version numbers!!!
Best practices <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 Manage version numbers using Maven or Gradle
Version numbers? <linkhref="/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!
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 <dependency> <groupId>org.webjars</groupId> <artifactId>jquery-ui</artifactId> <version>1.9.1</version> </dependency> <mvc:resourcesmapping="/webjars/**"location="classpath:/META-INF/resources/webjars/"/> <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! Inside pom.xml Spring configuration Inside JSP
What is jQuery? • Javascript framework • Very simple core with thousands of plugins available • Datatable • jQuery UI (datepicker, form interaction…)
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? Only for very simple use GOOD! Integrates well with Spring MVC Not available yet May be in 2013 java.util.Date Joda Time JSR 310: Date and time API
jqueryui date picker <script> $( "#startDate" ).datepicker({ dateFormat: "yy-m-dd" }); $( "#endDate" ).datepicker({ dateFormat: "yy-m-dd" }); </script> … <form:inputpath="startDate"/> <form:inputpath="endDate"/> JSP file
Adding jQuery Datatable
jQuery datatables • jQuery plugin for datatables • Click, sort, scroll, next/previous… • http://datatables.net/
Datatables in Spring MVC <dependency> <groupId>com.github.datatables4j</groupId> <artifactId>datatables4j-core-impl</artifactId> <version>0.7.0</version> </dependency> pom.xml • You don’t even need to write Javascript yourself! • Just use DataTables4J • http://datatables4j.github.com/docs/
Datatables in Spring MVC <datatables:tabledata="${userList}"id="dataTable"row="user"> <datatables:columntitle="First Name" property="firstName"sortable="true"/> <datatables:columntitle="Last Name" property="lastName"sortable="true"/> </datatables:table> JSP file Inside JSP file
Bootstrap Let’s talk about CSS…
Why Bootstrap? Let’s talk about Bootstrap! So your Web Designer does not have to cry anymore
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? 1 2 3 https://github.com/popular/starred • Most popular project on github!
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/
JSP file Avoiding JSP soup HTML Javascript CSS Taglibs
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!
Form fields: Without custom tags <divclass=“control-group”id=“${lastName}"> <labelclass="control-label">${lastNameLabel}</label> <divclass="controls"> <form:inputpath="${name}"/> <spanclass="help-inline"> <form:errorspath="${name}"/> </span> </div> </div> CSS div Label Form input Error message (if any) JSP
Using custom tags <%@taglibprefix="form"uri="http://www.spring…org/tags/form"%> <%@attributename="name"required="true"rtexprvalue="true"%> <%@attributename="label"required="true"rtexprvalue="true"%> <divclass="control-group"id="${name}"> <labelclass="control-label">${label}</label> <divclass="controls"> <form:inputpath="${name}"/> <spanclass="help-inline"> <form:errorspath="${name}"/> </span> </div> </div> inputField.tag • First create a tag (or tagx) file
Using custom tags Folder which contains custom tags <htmlxmlns:custom="urn:jsptagdir:/WEB-INF/tags/html" …> … <custom:inputFieldname="firstName"label="Enter your first name:"/> <custom:inputFieldname=”lastName"label="Enter your last name:"/> </html> JSP file 1 line of code instead of 9!! JSP No more JSP soup! • Custom tag call
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