java web development with stripes

34
Java Web Development with Stripes Samuel Santos

Upload: samuel-santos

Post on 05-Dec-2014

16.439 views

Category:

Technology


5 download

DESCRIPTION

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.

TRANSCRIPT

Page 1: Java Web Development with Stripes

Java Web Development with Stripes

Samuel Santos

Page 2: Java Web Development with Stripes

About me

• Senior Java Engineer and Web Advocate at Present Technologies

• Open source enthusiast

• Web standards contributor

• Casual blogger

Present Technologies 2

Page 3: Java Web Development with Stripes

Agenda

• Why

• What is it

• Goals

• Setting up

• Features

• Extensions

• Find more

• Q&A Present Technologies 3

Page 4: Java Web Development with Stripes

Why

“Java web development doesn’t have to suck.” Tim Fennell, Stripes author

Present Technologies 4

Page 5: Java Web Development with Stripes

Why

“Have you ever used a framework and felt you had to do too much work for the framework compared to what the framework gave you in return?”

Freddy Daoud, Stripes Book

Present Technologies 5

Page 6: Java Web Development with Stripes

What is it

• Stripes is a Model-View-Controller (MVC) framework

• Stripes is not a “full-stack” framework

• Stripes is an action-based framework

Present Technologies 6

Page 7: Java Web Development with Stripes

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 Homepage

Present Technologies 7

Page 8: Java Web Development with Stripes

Setting up

Present Technologies 8

<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>

Page 9: Java Web Development with Stripes

Features - Smart binding

URLs binding

Present Technologies 9

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>

Page 10: Java Web Development with Stripes

Parameters

And Events

<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>

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); } }

Features - Smart binding

Present Technologies 10

Page 11: Java Web Development with Stripes

Features - Smart binding

Localized buttons and labels

Present Technologies 11

<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 name com.example.javapt09.stripes.action.SmartBindingActionBean.user.lastName=Last name com.example.javapt09.stripes.action.SmartBindingActionBean.print=Print

Page 12: Java Web Development with Stripes

Features - Validation

Frequently used @Validate attributes

Present Technologies 12

Attribute Type Description

field 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.

Page 13: Java Web Development with Stripes

Features - Validation

Automatic maxlength on text inputs

Present Technologies 13

public 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>

Page 14: Java Web Development with Stripes

Features - Validation

Custom Validation

Present Technologies 14

@ValidationMethod public void validate(ValidationErrors errors) { if (user.getLastName().equals(user.getFirstName())) { errors.add("lastName", new SimpleError("First and last name must be different!")); } }

Page 15: Java Web Development with Stripes

Features - Validation

Displaying errors and messages

• Messages

• All errors

• Specific field error

Present Technologies 15

<s:messages />

<s:errors />

<s:errors field="user.firstName" />

Page 16: Java Web Development with Stripes

Features - Customizable URLs

Clean URLs

Present Technologies 16

<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() { ... } }

Page 17: Java Web Development with Stripes

Features - Layouts

Reusable layout

Present Technologies 17

<%@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>

Page 18: Java Web Development with Stripes

Features - Layouts

Using a reusable layout to render a page

Present Technologies 18

<%@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>

Page 19: Java Web Development with Stripes

Features - Layouts

Final result

Present Technologies 19

<!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>

Page 20: Java Web Development with Stripes

Features - Exception handling

Present Technologies 20

<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); } }

Page 21: Java Web Development with Stripes

Features - Exception handling

Don’t catch your exceptions

Present Technologies 21

public Resolution handledException() throws IOException { throw new IOException("Handled exception"); } public Resolution unhandledException() throws Exception { throw new Exception("Unhandled exception"); }

Page 22: Java Web Development with Stripes

Features - Interceptors

Built-in interceptors

Stripes request processing lifecycle stages:

Present Technologies 22

@Before(stages = LifecycleStage.BindingAndValidation) public void prepareSomeStuff() { // load data from the DB }

RequestInit ActionBeanResolution HandlerResolution

BindingAndValidation CustomValidation EventHandling

ResolutionExecution RequestComplete

Page 23: Java Web Development with Stripes

Features - Interceptors

Custom interceptors

Present Technologies 23

public interface Interceptor { Resolution intercept(ExecutionContext context) throws Exception; }

@Intercepts(LifecycleStage.ActionBeanResolution) public class EJBInterceptor implements Interceptor { public Resolution intercept(ExecutionContext context) throws Exception { ... } }

Page 24: Java Web Development with Stripes

Features - Easy Ajax integration

Present Technologies 24

public 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>

Page 25: Java Web Development with Stripes

Features - File download

Present Technologies 25

public 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); } }

Page 26: Java Web Development with Stripes

Features - File upload

File upload form

Present Technologies 26

<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>

Page 27: Java Web Development with Stripes

Features - File upload

Saving the file

Present Technologies 27

public 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"); } }

Page 28: Java Web Development with Stripes

Features - Extension/customization

• Stripes uses auto-discovery to find extensions

• The specified packages will be scanned for extensions like interceptors, formatters, type converters, exception handlers, etc

Present Technologies 28

<init-param> <param-name>Extension.Packages</param-name> <param-value>com.example.javapt09.stripes.extensions</param-value> </init-param>

@Validate(maxlength = 100, converter = EmailTypeConverter.class) private String email;

Page 29: Java Web Development with Stripes

Extensions

• Spring integration (built-in) http://www.stripesframework.org/display/stripes/Spring

+with+Stripes

• EJB3 integration http://code.google.com/p/stripes-ejb3

Present Technologies 29

Page 30: Java Web Development with Stripes

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+authorization

Present Technologies 30

Page 31: Java Web Development with Stripes

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.html

Present Technologies 31

Page 32: Java Web Development with Stripes

Find more

• Stripes Framwork http://www.stripesframework.org

• Stripes Book: Stripes ...and Java Web Development Is Fun Again

http://www.pragprog.com/titles/fdstr

Present Technologies 32

Page 33: Java Web Development with Stripes

Q&A

Present Technologies 33

Page 34: Java Web Development with Stripes

Contacts

• Present Technologies http://www.present-technologies.com

• Blog http://www.samaxes.com

• Twitter http://twitter.com/samaxes

Present Technologies 34