0
Java Web Development with Stripes                                Samuel Santos
About me• Senior Java Engineer and Web Advocate at  Present Technologies• Open source enthusiast• Web standards contributo...
Agenda•   Why•   What is it•   Goals•   Setting up•   Features•   Extensions•   Find more•   Q&APresent Technologies   3
Why“Java web development doesn’t have to suck.”                           Tim Fennell, Stripes authorPresent Technologies ...
Why“Have you ever used a framework and felt youhad to do too much work for the frameworkcompared to what the framework gav...
What is it• Stripes is a Model-View-Controller (MVC)  framework• Stripes is not a “full-stack” framework• Stripes is an ac...
Goals• Make developing web applications in Java  easy• Provide simple yet powerful solutions to  common problems• Make the...
Setting up<filter>    <filter-name>StripesFilter</filter-name>    <filter-class>net.sourceforge.stripes.controller.Stripes...
Features - Smart binding URLs binding         public class SmartBindingActionBean extends BaseActionBean {             ......
Features - Smart binding                                         <s:form beanclass="com.example.javapt09.stripes.action.Sm...
Features - Smart bindingLocalized buttons and labels<s:form beanclass="com.example.javapt09.stripes.action.SmartBindingAct...
Features - ValidationFrequently used @Validate attributesAttribute              Type       Descriptionfield               ...
Features - ValidationAutomatic maxlength on text inputspublic class SmartBindingActionBean extends BaseActionBean {   @Val...
Features - ValidationCustom Validation@ValidationMethodpublic void validate(ValidationErrors errors) {    if (user.getLast...
Features - ValidationDisplaying errors and messages• Messages   <s:messages />• All errors   <s:errors />• Specific field ...
Features - Customizable URLsClean URLs<servlet-mapping>    <servlet-name>DispatcherServlet</servlet-name>    <url-pattern>...
Features - LayoutsReusable layout<%@include file="/WEB-INF/jsp/common/taglibs.jsp" %><s:layout-definition><!DOCTYPE html><...
Features - LayoutsUsing a reusable layout to render a page<%@include file="/WEB-INF/jsp/common/taglibs.jsp" %><s:layout-re...
Features - LayoutsFinal result<!DOCTYPE html><html>    <head>        <meta charset="UTF-8" />        <title>JavaPT09 - Str...
Features - Exception handling<init-param>    <param-name>DelegatingExceptionHandler.Packages</param-name>    <param-value>...
Features - Exception handlingDon’t catch your exceptionspublic Resolution handledException() throws IOException {    throw...
Features - InterceptorsBuilt-in interceptors@Before(stages = LifecycleStage.BindingAndValidation)public void prepareSomeSt...
Features - InterceptorsCustom interceptorspublic interface Interceptor {    Resolution intercept(ExecutionContext context)...
Features - Easy Ajax integrationpublic class AjaxActionBean extends BaseActionBean {    private List<String> cities = new ...
Features - File downloadpublic class DownloadActionBean extends BaseActionBean {    @DefaultHandler    public Resolution m...
Features - File uploadFile upload form<s:form beanclass="com.example.javapt09.stripes.action.UploadActionBean"    enctype=...
Features - File uploadSaving the filepublic class UploadActionBean extends BaseActionBean {    private FileBean fileBean; ...
Features - Extension/customization• Stripes uses auto-discovery to find extensions   <init-param>       <param-name>Extens...
Extensions• Spring integration (built-in)         http://www.stripesframework.org/display/stripes/Spring           +with+S...
Extensions• Stripes Security (roles based)         http://www.stripesframework.org/display/stripes/Securi           ng+Str...
Extensions• Stripes-Reload    Plugin for Stripes 1.5 that reloads modifications    made to your Action Beans, Type Convert...
Find more• Stripes Framwork         http://www.stripesframework.org• Stripes Book: Stripes ...and Java Web  Development Is...
Q&APresent Technologies   33
Contacts• Present Technologies         http://www.present-technologies.com• Blog         http://www.samaxes.com• Twitter  ...
Upcoming SlideShare
Loading in...5
×

Java Web Development with Stripes

13,103

Published on

Stripes presentation for the Portuguese JUG session at JavaPT09 event.
Last version available at Speaker Deck: http://speakerdeck.com/samaxes/java-web-development-with-stripes.

Published in: Technology, News & Politics
0 Comments
5 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
13,103
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
209
Comments
0
Likes
5
Embeds 0
No embeds

No notes for slide

Transcript of "Java Web Development with Stripes"

  1. 1. Java Web Development with Stripes Samuel Santos
  2. 2. About me• Senior Java Engineer and Web Advocate at Present Technologies• Open source enthusiast• Web standards contributor• Casual bloggerPresent Technologies 2
  3. 3. Agenda• Why• What is it• Goals• Setting up• Features• Extensions• Find more• Q&APresent Technologies 3
  4. 4. Why“Java web development doesn’t have to suck.” Tim Fennell, Stripes authorPresent Technologies 4
  5. 5. Why“Have you ever used a framework and felt youhad to do too much work for the frameworkcompared to what the framework gave you inreturn?” Freddy Daoud, Stripes BookPresent Technologies 5
  6. 6. What is it• Stripes is a Model-View-Controller (MVC) framework• Stripes is not a “full-stack” framework• Stripes is an action-based frameworkPresent Technologies 6
  7. 7. Goals• Make developing web applications in Java easy• Provide simple yet powerful solutions to common problems• Make the Stripes ramp up time for a new developer less than 30 minutes• Make it really easy to extend Stripes, without making you configure every last thing From Stripes HomepagePresent Technologies 7
  8. 8. Setting up<filter> <filter-name>StripesFilter</filter-name> <filter-class>net.sourceforge.stripes.controller.StripesFilter</filter-class> <init-param> <param-name>ActionResolver.Packages</param-name> <param-value>com.example.javapt09.stripes.action</param-value> </init-param></filter><servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>net.sourceforge.stripes.controller.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup></servlet><filter-mapping> <filter-name>StripesFilter</filter-name> <servlet-name>DispatcherServlet</servlet-name> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> <dispatcher>ERROR</dispatcher></filter-mapping><servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>*.action</url-pattern></servlet-mapping> Present Technologies 8
  9. 9. Features - Smart binding URLs binding public class SmartBindingActionBean extends BaseActionBean { ... }<s:link beanclass="com.example.javapt09.stripes.action.SmartBindingActionBean">Smart binding</s:link><s:link href="${contextPath}/SmartBinding.action">Smart binding</s:link> Present Technologies 9
  10. 10. Features - Smart binding <s:form beanclass="com.example.javapt09.stripes.action.SmartBindingActionBean"> <p> <s:label for="user.firstName" /> <s:text id="user.firstName" name="user.firstName" /> Parameters </p> <p> <s:label for="user.lastName" /> And Events </p> <p> <s:text id="user.lastName" name="user.lastName" /> <s:submit name="print" /> </p> </s:form>public class SmartBindingActionBean extends BaseActionBean { @ValidateNestedProperties({ @Validate(field = "firstName", required = true, maxlength = 100), @Validate(field = "lastName", required = true, maxlength = 100) }) private User user; public User getUser() { return user; } public void setUser(User user) { this.user = user; } @DefaultHandler @DontValidate public Resolution main() { return new ForwardResolution("/WEB-INF/jsp/binding-validation.jsp"); } public Resolution print() { getContext().getMessages().add(new LocalizableMessage( "com.example.javapt09.stripes.action.SmartBindingActionBean.print.success", user)); return new RedirectResolution(SmartBindingActionBean.class); }} Present Technologies 10
  11. 11. Features - Smart bindingLocalized buttons and labels<s:form beanclass="com.example.javapt09.stripes.action.SmartBindingActionBean"> <p> <s:label for="user.firstName" /> <s:text id="user.firstName" name="user.firstName" /> </p> <p> <s:label for="user.lastName" /> <s:text id="user.lastName" name="user.lastName" /> </p> <p> <s:submit name="print" /> </p></s:form>com.example.javapt09.stripes.action.SmartBindingActionBean.user.firstName=First namecom.example.javapt09.stripes.action.SmartBindingActionBean.user.lastName=Last namecom.example.javapt09.stripes.action.SmartBindingActionBean.print=Print Present Technologies 11
  12. 12. Features - ValidationFrequently used @Validate attributesAttribute Type Descriptionfield String Name of nested field to validate.required boolean true indicates a required field.on String[] Event handlers for which to apply.minlength int Minimum length of input.maxlength int Maximum length of input.expression String EL expression to validate the input.mask String Regular expression that the input must match.minvalue double Minimum numerical value of input.maxvalue double Maximum numerical value of input.converter Class Type converter to use on the input.Present Technologies 12
  13. 13. Features - ValidationAutomatic maxlength on text inputspublic class SmartBindingActionBean extends BaseActionBean { @ValidateNestedProperties({ @Validate(field = "firstName", required = true, maxlength = 100), @Validate(field = "lastName", required = true, maxlength = 100) }) private User user; ...}<form action="/javapt09/SmartBinding.action" method="post"> <p> <label for="user.firstName">First name</label> <input id="user.firstName" maxlength="100" name="user.firstName" type="text" /> </p> <p> <label for="user.lastName">Last name</label> <input id="user.lastName" maxlength="100" name="user.lastName" type="text" /> </p> <p> <input name="print" value="Print" type="submit" /> </p></form> Present Technologies 13
  14. 14. Features - ValidationCustom Validation@ValidationMethodpublic void validate(ValidationErrors errors) { if (user.getLastName().equals(user.getFirstName())) { errors.add("lastName", new SimpleError("First and last name must be different!")); }} Present Technologies 14
  15. 15. Features - ValidationDisplaying errors and messages• Messages <s:messages />• All errors <s:errors />• Specific field error <s:errors field="user.firstName" />Present Technologies 15
  16. 16. Features - Customizable URLsClean URLs<servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>/action/*</url-pattern></servlet-mapping>@UrlBinding("/action/cleanURL/{$event}/{city}")public class CustomizableURLActionBean extends BaseActionBean { private String city; public Resolution delete() { ... }}Present Technologies 16
  17. 17. Features - LayoutsReusable layout<%@include file="/WEB-INF/jsp/common/taglibs.jsp" %><s:layout-definition><!DOCTYPE html><html> <head> <meta charset="UTF-8" /> <title>${title}</title> <link rel="stylesheet" type="text/css" href="${contextPath}/css/style.css" /> </head> <body> <div id="header"> <span class="title">${title}</span> </div> <div id="body"> <s:layout-component name="body" /> </div> </body></html></s:layout-definition>Present Technologies 17
  18. 18. Features - LayoutsUsing a reusable layout to render a page<%@include file="/WEB-INF/jsp/common/taglibs.jsp" %><s:layout-render name="/WEB-INF/jsp/common/layout-main.jsp" title="JavaPT09 - Stripes » Layouts"> <s:layout-component name="body"> <p>Main page content...</p> </s:layout-component></s:layout-render>Present Technologies 18
  19. 19. Features - LayoutsFinal result<!DOCTYPE html><html> <head> <meta charset="UTF-8" /> <title>JavaPT09 - Stripes » Layouts</title> <link rel="stylesheet" type="text/css" href="/javapt09/css/style.css" /> </head> <body> <div id="header"> <span class="title">JavaPT09 - Stripes » Layouts</span> </div> <div id="body"> <p>Main page content...</p> </div> </body></html>Present Technologies 19
  20. 20. Features - Exception handling<init-param> <param-name>DelegatingExceptionHandler.Packages</param-name> <param-value>com.example.javapt09.stripes.exception</param-value></init-param>public class DefaultExceptionHandler implements AutoExceptionHandler { public Resolution handle(Exception exception, HttpServletRequest request, HttpServletResponse response) { // Handle Exception return new ForwardResolution(ErrorActionBean.class); } public Resolution handle(IOException exception, HttpServletRequest request, HttpServletResponse response) { // Handle IOException return new ForwardResolution(ErrorActionBean.class); }}Present Technologies 20
  21. 21. Features - Exception handlingDon’t catch your exceptionspublic Resolution handledException() throws IOException { throw new IOException("Handled exception");}public Resolution unhandledException() throws Exception { throw new Exception("Unhandled exception");}Present Technologies 21
  22. 22. Features - InterceptorsBuilt-in interceptors@Before(stages = LifecycleStage.BindingAndValidation)public void prepareSomeStuff() { // load data from the DB}Stripes request processing lifecycle stages:RequestInit ActionBeanResolution HandlerResolutionBindingAndValidation CustomValidation EventHandlingResolutionExecution RequestComplete Present Technologies 22
  23. 23. Features - InterceptorsCustom interceptorspublic interface Interceptor { Resolution intercept(ExecutionContext context) throws Exception;}@Intercepts(LifecycleStage.ActionBeanResolution)public class EJBInterceptor implements Interceptor { public Resolution intercept(ExecutionContext context) throws Exception { ... }} Present Technologies 23
  24. 24. Features - Easy Ajax integrationpublic class AjaxActionBean extends BaseActionBean { private List<String> cities = new ArrayList<String>(); public Resolution load() { return new JavaScriptResolution(cities); }}<div id="cities"></div><script type="text/javascript"> var client = new XMLHttpRequest(); client.open("GET", "${contextPath}/Ajax.action?load="); client.onreadystatechange = function() { if (this.readyState == 4) { var cities = eval(client.responseText); var citiesList = ""; for (var i = 0; i < cities.length; i++) { citiesList += "<li>" + cities[i] + "</li>"; } document.getElementById("cities").innerHTML = "<ul>" + citiesList + "</ul>"; } } client.send(null);</script> Present Technologies 24
  25. 25. Features - File downloadpublic class DownloadActionBean extends BaseActionBean { @DefaultHandler public Resolution main() throws FileNotFoundException { String fileName = "stripes.png"; String filePath = getContext().getServletContext().getRealPath("/img/" + fileName); return new StreamingResolution("image/png", new FileInputStream(filePath)).setFilename(fileName); }} Present Technologies 25
  26. 26. Features - File uploadFile upload form<s:form beanclass="com.example.javapt09.stripes.action.UploadActionBean" enctype="multipart/form-data"> <p> <s:file name="fileBean" /> </p> <p> <s:submit name="upload" /> </p></s:form>Present Technologies 26
  27. 27. Features - File uploadSaving the filepublic class UploadActionBean extends BaseActionBean { private FileBean fileBean; public FileBean getFileBean() { return fileBean; } public void setFileBean(FileBean fileBean) { this.fileBean = fileBean; } @DefaultHandler public Resolution main() { return new ForwardResolution("/WEB-INF/jsp/file-upload.jsp"); } public Resolution upload() throws IOException { fileBean.getFileName(); fileBean.getSize(); fileBean.getContentType(); // fileBean.save(new File()); return new ForwardResolution("/WEB-INF/jsp/file-upload.jsp"); }}Present Technologies 27
  28. 28. Features - Extension/customization• Stripes uses auto-discovery to find extensions <init-param> <param-name>Extension.Packages</param-name> <param-value>com.example.javapt09.stripes.extensions</param-value> </init-param>• The specified packages will be scanned for extensions like interceptors, formatters, type converters, exception handlers, etc @Validate(maxlength = 100, converter = EmailTypeConverter.class) private String email;Present Technologies 28
  29. 29. Extensions• Spring integration (built-in) http://www.stripesframework.org/display/stripes/Spring +with+Stripes• EJB3 integration http://code.google.com/p/stripes-ejb3Present Technologies 29
  30. 30. Extensions• Stripes Security (roles based) http://www.stripesframework.org/display/stripes/Securi ng+Stripes+With+ACLs• Stripes Security (custom authorization) http://www.stripesframework.org/display/stripes/Securit y+Interceptor+for+custom+authorizationPresent Technologies 30
  31. 31. Extensions• Stripes-Reload Plugin for Stripes 1.5 that reloads modifications made to your Action Beans, Type Converters, Formatters, and Resource Bundles without having to restart your server http://www.stripesbook.org/stripes-reload.htmlPresent Technologies 31
  32. 32. Find more• Stripes Framwork http://www.stripesframework.org• Stripes Book: Stripes ...and Java Web Development Is Fun Again http://www.pragprog.com/titles/fdstrPresent Technologies 32
  33. 33. Q&APresent Technologies 33
  34. 34. Contacts• Present Technologies http://www.present-technologies.com• Blog http://www.samaxes.com• Twitter http://twitter.com/samaxesPresent Technologies 34
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×