Moved tests from testsuite to web.servlet

This commit is contained in:
Arjen Poutsma
2008-11-03 12:03:31 +00:00
parent 74733d0d1d
commit 3d06246195
38 changed files with 1155 additions and 23 deletions

View File

@@ -0,0 +1,30 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans;
/**
* @author Juergen Hoeller
*/
public enum CustomEnum {
VALUE_1, VALUE_2;
public String toString() {
return "CustomEnum: " + name();
}
}

View File

@@ -0,0 +1,237 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.core.io.Resource;
/**
* @author Juergen Hoeller
*/
public class GenericBean<T> {
private Set<Integer> integerSet;
private List<Resource> resourceList;
private List<List<Integer>> listOfLists;
private ArrayList<String[]> listOfArrays;
private List<Map<Integer, Long>> listOfMaps;
private Map plainMap;
private Map<Short, Integer> shortMap;
private HashMap<Long, ?> longMap;
private Map<Number, Collection<? extends Object>> collectionMap;
private Map<String, Map<Integer, Long>> mapOfMaps;
private Map<Integer, List<Integer>> mapOfLists;
private CustomEnum customEnum;
private T genericProperty;
private List<T> genericListProperty;
public GenericBean() {
}
public GenericBean(Set<Integer> integerSet) {
this.integerSet = integerSet;
}
public GenericBean(Set<Integer> integerSet, List<Resource> resourceList) {
this.integerSet = integerSet;
this.resourceList = resourceList;
}
public GenericBean(HashSet<Integer> integerSet, Map<Short, Integer> shortMap) {
this.integerSet = integerSet;
this.shortMap = shortMap;
}
public GenericBean(Map<Short, Integer> shortMap, Resource resource) {
this.shortMap = shortMap;
this.resourceList = Collections.singletonList(resource);
}
public GenericBean(Map plainMap, Map<Short, Integer> shortMap) {
this.plainMap = plainMap;
this.shortMap = shortMap;
}
public GenericBean(HashMap<Long, ?> longMap) {
this.longMap = longMap;
}
public GenericBean(boolean someFlag, Map<Number, Collection<? extends Object>> collectionMap) {
this.collectionMap = collectionMap;
}
public Set<Integer> getIntegerSet() {
return integerSet;
}
public void setIntegerSet(Set<Integer> integerSet) {
this.integerSet = integerSet;
}
public List<Resource> getResourceList() {
return resourceList;
}
public void setResourceList(List<Resource> resourceList) {
this.resourceList = resourceList;
}
public List<List<Integer>> getListOfLists() {
return listOfLists;
}
public ArrayList<String[]> getListOfArrays() {
return listOfArrays;
}
public void setListOfArrays(ArrayList<String[]> listOfArrays) {
this.listOfArrays = listOfArrays;
}
public void setListOfLists(List<List<Integer>> listOfLists) {
this.listOfLists = listOfLists;
}
public List<Map<Integer, Long>> getListOfMaps() {
return listOfMaps;
}
public void setListOfMaps(List<Map<Integer, Long>> listOfMaps) {
this.listOfMaps = listOfMaps;
}
public Map getPlainMap() {
return plainMap;
}
public Map<Short, Integer> getShortMap() {
return shortMap;
}
public void setShortMap(Map<Short, Integer> shortMap) {
this.shortMap = shortMap;
}
public HashMap<Long, ?> getLongMap() {
return longMap;
}
public void setLongMap(HashMap<Long, ?> longMap) {
this.longMap = longMap;
}
public Map<Number, Collection<? extends Object>> getCollectionMap() {
return collectionMap;
}
public void setCollectionMap(Map<Number, Collection<? extends Object>> collectionMap) {
this.collectionMap = collectionMap;
}
public Map<String, Map<Integer, Long>> getMapOfMaps() {
return mapOfMaps;
}
public void setMapOfMaps(Map<String, Map<Integer, Long>> mapOfMaps) {
this.mapOfMaps = mapOfMaps;
}
public Map<Integer, List<Integer>> getMapOfLists() {
return mapOfLists;
}
public void setMapOfLists(Map<Integer, List<Integer>> mapOfLists) {
this.mapOfLists = mapOfLists;
}
public T getGenericProperty() {
return genericProperty;
}
public void setGenericProperty(T genericProperty) {
this.genericProperty = genericProperty;
}
public List<T> getGenericListProperty() {
return genericListProperty;
}
public void setGenericListProperty(List<T> genericListProperty) {
this.genericListProperty = genericListProperty;
}
public CustomEnum getCustomEnum() {
return customEnum;
}
public void setCustomEnum(CustomEnum customEnum) {
this.customEnum = customEnum;
}
public static GenericBean createInstance(Set<Integer> integerSet) {
return new GenericBean(integerSet);
}
public static GenericBean createInstance(Set<Integer> integerSet, List<Resource> resourceList) {
return new GenericBean(integerSet, resourceList);
}
public static GenericBean createInstance(HashSet<Integer> integerSet, Map<Short, Integer> shortMap) {
return new GenericBean(integerSet, shortMap);
}
public static GenericBean createInstance(Map<Short, Integer> shortMap, Resource resource) {
return new GenericBean(shortMap, resource);
}
public static GenericBean createInstance(Map map, Map<Short, Integer> shortMap) {
return new GenericBean(map, shortMap);
}
public static GenericBean createInstance(HashMap<Long, ?> longMap) {
return new GenericBean(longMap);
}
public static GenericBean createInstance(boolean someFlag, Map<Number, Collection<? extends Object>> collectionMap) {
return new GenericBean(someFlag, collectionMap);
}
}

View File

@@ -0,0 +1,54 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans;
/**
* @author Rob Harrop
* @since 2.0
*/
public class Pet {
private String name;
public Pet(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String toString() {
return getName();
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final Pet pet = (Pet) o;
if (name != null ? !name.equals(pet.name) : pet.name != null) return false;
return true;
}
public int hashCode() {
return (name != null ? name.hashCode() : 0);
}
}

View File

@@ -0,0 +1,198 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.mock.web;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyContent;
/**
* Mock implementation of the {@link javax.servlet.jsp.tagext.BodyContent} class.
*
* <p>Used for testing the web framework; only necessary for testing
* applications when testing custom JSP tags.
*
* @author Juergen Hoeller
* @since 2.5
*/
public class MockBodyContent extends BodyContent {
private final String content;
/**
* Create a MockBodyContent for the given response.
* @param content the body content to expose
* @param response the servlet response to wrap
*/
public MockBodyContent(String content, HttpServletResponse response) {
this(content, response, null);
}
/**
* Create a MockBodyContent for the given response.
* @param content the body content to expose
* @param targetWriter the target Writer to wrap
*/
public MockBodyContent(String content, Writer targetWriter) {
this(content, null, targetWriter);
}
/**
* Create a MockBodyContent for the given response.
* @param content the body content to expose
* @param response the servlet response to wrap
* @param targetWriter the target Writer to wrap
*/
public MockBodyContent(String content, HttpServletResponse response, Writer targetWriter) {
super(adaptJspWriter(targetWriter, response));
this.content = content;
}
private static JspWriter adaptJspWriter(Writer targetWriter, HttpServletResponse response) {
if (targetWriter instanceof JspWriter) {
return (JspWriter) targetWriter;
}
else {
return new MockJspWriter(response, targetWriter);
}
}
public Reader getReader() {
return new StringReader(this.content);
}
public String getString() {
return this.content;
}
public void writeOut(Writer writer) throws IOException {
writer.write(this.content);
}
//---------------------------------------------------------------------
// Delegating implementations of JspWriter's abstract methods
//---------------------------------------------------------------------
public void clear() throws IOException {
getEnclosingWriter().clear();
}
public void clearBuffer() throws IOException {
getEnclosingWriter().clearBuffer();
}
public void close() throws IOException {
getEnclosingWriter().close();
}
public int getRemaining() {
return getEnclosingWriter().getRemaining();
}
public void newLine() throws IOException {
getEnclosingWriter().println();
}
public void write(char value[], int offset, int length) throws IOException {
getEnclosingWriter().write(value, offset, length);
}
public void print(boolean value) throws IOException {
getEnclosingWriter().print(value);
}
public void print(char value) throws IOException {
getEnclosingWriter().print(value);
}
public void print(char[] value) throws IOException {
getEnclosingWriter().print(value);
}
public void print(double value) throws IOException {
getEnclosingWriter().print(value);
}
public void print(float value) throws IOException {
getEnclosingWriter().print(value);
}
public void print(int value) throws IOException {
getEnclosingWriter().print(value);
}
public void print(long value) throws IOException {
getEnclosingWriter().print(value);
}
public void print(Object value) throws IOException {
getEnclosingWriter().print(value);
}
public void print(String value) throws IOException {
getEnclosingWriter().print(value);
}
public void println() throws IOException {
getEnclosingWriter().println();
}
public void println(boolean value) throws IOException {
getEnclosingWriter().println(value);
}
public void println(char value) throws IOException {
getEnclosingWriter().println(value);
}
public void println(char[] value) throws IOException {
getEnclosingWriter().println(value);
}
public void println(double value) throws IOException {
getEnclosingWriter().println(value);
}
public void println(float value) throws IOException {
getEnclosingWriter().println(value);
}
public void println(int value) throws IOException {
getEnclosingWriter().println(value);
}
public void println(long value) throws IOException {
getEnclosingWriter().println(value);
}
public void println(Object value) throws IOException {
getEnclosingWriter().println(value);
}
public void println(String value) throws IOException {
getEnclosingWriter().println(value);
}
}

View File

@@ -0,0 +1,92 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.mock.web;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.el.ELException;
import javax.servlet.jsp.el.Expression;
import javax.servlet.jsp.el.ExpressionEvaluator;
import javax.servlet.jsp.el.FunctionMapper;
import javax.servlet.jsp.el.VariableResolver;
import org.apache.taglibs.standard.lang.support.ExpressionEvaluatorManager;
/**
* Mock implementation of the JSP 2.0 {@link javax.servlet.jsp.el.ExpressionEvaluator}
* interface, delegating to the Jakarta JSTL ExpressionEvaluatorManager.
*
* <p>Used for testing the web framework; only necessary for testing
* applications when testing custom JSP tags.
*
* <p>Note that the Jakarta JSTL implementation (jstl.jar, standard.jar)
* has to be available on the class path to use this expression evaluator.
*
* @author Juergen Hoeller
* @since 1.1.5
* @see org.apache.taglibs.standard.lang.support.ExpressionEvaluatorManager
*/
public class MockExpressionEvaluator extends ExpressionEvaluator {
private final PageContext pageContext;
/**
* Create a new MockExpressionEvaluator for the given PageContext.
* @param pageContext the JSP PageContext to run in
*/
public MockExpressionEvaluator(PageContext pageContext) {
this.pageContext = pageContext;
}
public Expression parseExpression(
final String expression, final Class expectedType, final FunctionMapper functionMapper)
throws ELException {
return new Expression() {
public Object evaluate(VariableResolver variableResolver) throws ELException {
return doEvaluate(expression, expectedType, functionMapper);
}
};
}
public Object evaluate(
String expression, Class expectedType, VariableResolver variableResolver, FunctionMapper functionMapper)
throws ELException {
if (variableResolver != null) {
throw new IllegalArgumentException("Custom VariableResolver not supported");
}
return doEvaluate(expression, expectedType, functionMapper);
}
protected Object doEvaluate(
String expression, Class expectedType, FunctionMapper functionMapper)
throws ELException {
if (functionMapper != null) {
throw new IllegalArgumentException("Custom FunctionMapper not supported");
}
try {
return ExpressionEvaluatorManager.evaluate("JSP EL expression", expression, expectedType, this.pageContext);
}
catch (JspException ex) {
throw new ELException("Parsing of JSP EL expression \"" + expression + "\" failed", ex);
}
}
}

View File

@@ -0,0 +1,192 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.mock.web;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspWriter;
/**
* Mock implementation of the {@link javax.servlet.jsp.JspWriter} class.
*
* <p>Used for testing the web framework; only necessary for testing
* applications when testing custom JSP tags.
*
* @author Juergen Hoeller
* @since 2.5
*/
public class MockJspWriter extends JspWriter {
private final HttpServletResponse response;
private PrintWriter targetWriter;
/**
* Create a MockJspWriter for the given response,
* using the response's default Writer.
* @param response the servlet response to wrap
*/
public MockJspWriter(HttpServletResponse response) {
this(response, null);
}
/**
* Create a MockJspWriter for the given plain Writer.
* @param targetWriter the target Writer to wrap
*/
public MockJspWriter(Writer targetWriter) {
this(null, targetWriter);
}
/**
* Create a MockJspWriter for the given response.
* @param response the servlet response to wrap
* @param targetWriter the target Writer to wrap
*/
public MockJspWriter(HttpServletResponse response, Writer targetWriter) {
super(DEFAULT_BUFFER, true);
this.response = (response != null ? response : new MockHttpServletResponse());
if (targetWriter instanceof PrintWriter) {
this.targetWriter = (PrintWriter) targetWriter;
}
else if (targetWriter != null) {
this.targetWriter = new PrintWriter(targetWriter);
}
}
/**
* Lazily initialize the target Writer.
*/
protected PrintWriter getTargetWriter() throws IOException {
if (this.targetWriter == null) {
this.targetWriter = this.response.getWriter();
}
return this.targetWriter;
}
public void clear() throws IOException {
if (this.response.isCommitted()) {
throw new IOException("Response already committed");
}
this.response.resetBuffer();
}
public void clearBuffer() throws IOException {
}
public void flush() throws IOException {
this.response.flushBuffer();
}
public void close() throws IOException {
flush();
}
public int getRemaining() {
return Integer.MAX_VALUE;
}
public void newLine() throws IOException {
getTargetWriter().println();
}
public void write(char value[], int offset, int length) throws IOException {
getTargetWriter().write(value, offset, length);
}
public void print(boolean value) throws IOException {
getTargetWriter().print(value);
}
public void print(char value) throws IOException {
getTargetWriter().print(value);
}
public void print(char[] value) throws IOException {
getTargetWriter().print(value);
}
public void print(double value) throws IOException {
getTargetWriter().print(value);
}
public void print(float value) throws IOException {
getTargetWriter().print(value);
}
public void print(int value) throws IOException {
getTargetWriter().print(value);
}
public void print(long value) throws IOException {
getTargetWriter().print(value);
}
public void print(Object value) throws IOException {
getTargetWriter().print(value);
}
public void print(String value) throws IOException {
getTargetWriter().print(value);
}
public void println() throws IOException {
getTargetWriter().println();
}
public void println(boolean value) throws IOException {
getTargetWriter().println(value);
}
public void println(char value) throws IOException {
getTargetWriter().println(value);
}
public void println(char[] value) throws IOException {
getTargetWriter().println(value);
}
public void println(double value) throws IOException {
getTargetWriter().println(value);
}
public void println(float value) throws IOException {
getTargetWriter().println(value);
}
public void println(int value) throws IOException {
getTargetWriter().println(value);
}
public void println(long value) throws IOException {
getTargetWriter().println(value);
}
public void println(Object value) throws IOException {
getTargetWriter().println(value);
}
public void println(String value) throws IOException {
getTargetWriter().println(value);
}
}

View File

@@ -0,0 +1,330 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.mock.web;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.el.ExpressionEvaluator;
import javax.servlet.jsp.el.VariableResolver;
import org.springframework.util.Assert;
/**
* Mock implementation of the {@link javax.servlet.jsp.PageContext} interface.
*
* <p>Used for testing the web framework; only necessary for testing
* applications when testing custom JSP tags.
*
* <p>Note: Expects initialization via the constructor rather than via the
* <code>PageContext.initialize</code> method. Does not support writing to
* a JspWriter, request dispatching, and <code>handlePageException</code> calls.
*
* @author Juergen Hoeller
* @since 1.0.2
*/
public class MockPageContext extends PageContext {
private final ServletContext servletContext;
private final HttpServletRequest request;
private final HttpServletResponse response;
private final ServletConfig servletConfig;
private final Hashtable attributes = new Hashtable();
private JspWriter out;
/**
* Create new MockPageContext with a default {@link org.springframework.mock.web.MockServletContext},
* {@link org.springframework.mock.web.MockHttpServletRequest}, {@link org.springframework.mock.web.MockHttpServletResponse},
* {@link org.springframework.mock.web.MockServletConfig}.
*/
public MockPageContext() {
this(null, null, null, null);
}
/**
* Create new MockPageContext with a default {@link org.springframework.mock.web.MockHttpServletRequest},
* {@link org.springframework.mock.web.MockHttpServletResponse}, {@link org.springframework.mock.web.MockServletConfig}.
* @param servletContext the ServletContext that the JSP page runs in
* (only necessary when actually accessing the ServletContext)
*/
public MockPageContext(ServletContext servletContext) {
this(servletContext, null, null, null);
}
/**
* Create new MockPageContext with a MockHttpServletResponse,
* MockServletConfig.
* @param servletContext the ServletContext that the JSP page runs in
* @param request the current HttpServletRequest
* (only necessary when actually accessing the request)
*/
public MockPageContext(ServletContext servletContext, HttpServletRequest request) {
this(servletContext, request, null, null);
}
/**
* Create new MockPageContext with a MockServletConfig.
* @param servletContext the ServletContext that the JSP page runs in
* @param request the current HttpServletRequest
* @param response the current HttpServletResponse
* (only necessary when actually writing to the response)
*/
public MockPageContext(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response) {
this(servletContext, request, response, null);
}
/**
* Create new MockServletConfig.
* @param servletContext the ServletContext that the JSP page runs in
* @param request the current HttpServletRequest
* @param response the current HttpServletResponse
* @param servletConfig the ServletConfig (hardly ever accessed from within a tag)
*/
public MockPageContext(ServletContext servletContext, HttpServletRequest request,
HttpServletResponse response, ServletConfig servletConfig) {
this.servletContext = (servletContext != null ? servletContext : new MockServletContext());
this.request = (request != null ? request : new MockHttpServletRequest(servletContext));
this.response = (response != null ? response : new MockHttpServletResponse());
this.servletConfig = (servletConfig != null ? servletConfig : new MockServletConfig(servletContext));
}
public void initialize(
Servlet servlet, ServletRequest request, ServletResponse response,
String errorPageURL, boolean needsSession, int bufferSize, boolean autoFlush) {
throw new UnsupportedOperationException("Use appropriate constructor");
}
public void release() {
}
public void setAttribute(String name, Object value) {
Assert.notNull(name, "Attribute name must not be null");
if (value != null) {
this.attributes.put(name, value);
}
else {
this.attributes.remove(name);
}
}
public void setAttribute(String name, Object value, int scope) {
Assert.notNull(name, "Attribute name must not be null");
switch (scope) {
case PAGE_SCOPE:
setAttribute(name, value);
break;
case REQUEST_SCOPE:
this.request.setAttribute(name, value);
break;
case SESSION_SCOPE:
this.request.getSession().setAttribute(name, value);
break;
case APPLICATION_SCOPE:
this.servletContext.setAttribute(name, value);
break;
default:
throw new IllegalArgumentException("Invalid scope: " + scope);
}
}
public Object getAttribute(String name) {
Assert.notNull(name, "Attribute name must not be null");
return this.attributes.get(name);
}
public Object getAttribute(String name, int scope) {
Assert.notNull(name, "Attribute name must not be null");
switch (scope) {
case PAGE_SCOPE:
return getAttribute(name);
case REQUEST_SCOPE:
return this.request.getAttribute(name);
case SESSION_SCOPE:
HttpSession session = this.request.getSession(false);
return (session != null ? session.getAttribute(name) : null);
case APPLICATION_SCOPE:
return this.servletContext.getAttribute(name);
default:
throw new IllegalArgumentException("Invalid scope: " + scope);
}
}
public Object findAttribute(String name) {
Object value = getAttribute(name);
if (value == null) {
value = getAttribute(name, REQUEST_SCOPE);
if (value == null) {
value = getAttribute(name, SESSION_SCOPE);
if (value == null) {
value = getAttribute(name, APPLICATION_SCOPE);
}
}
}
return value;
}
public void removeAttribute(String name) {
Assert.notNull(name, "Attribute name must not be null");
this.removeAttribute(name, PageContext.PAGE_SCOPE);
this.removeAttribute(name, PageContext.REQUEST_SCOPE);
this.removeAttribute(name, PageContext.SESSION_SCOPE);
this.removeAttribute(name, PageContext.APPLICATION_SCOPE);
}
public void removeAttribute(String name, int scope) {
Assert.notNull(name, "Attribute name must not be null");
switch (scope) {
case PAGE_SCOPE:
this.attributes.remove(name);
break;
case REQUEST_SCOPE:
this.request.removeAttribute(name);
break;
case SESSION_SCOPE:
this.request.getSession().removeAttribute(name);
break;
case APPLICATION_SCOPE:
this.servletContext.removeAttribute(name);
break;
default:
throw new IllegalArgumentException("Invalid scope: " + scope);
}
}
public int getAttributesScope(String name) {
if (getAttribute(name) != null) {
return PAGE_SCOPE;
}
else if (getAttribute(name, REQUEST_SCOPE) != null) {
return REQUEST_SCOPE;
}
else if (getAttribute(name, SESSION_SCOPE) != null) {
return SESSION_SCOPE;
}
else if (getAttribute(name, APPLICATION_SCOPE) != null) {
return APPLICATION_SCOPE;
}
else {
return 0;
}
}
public Enumeration getAttributeNames() {
return this.attributes.keys();
}
public Enumeration getAttributeNamesInScope(int scope) {
switch (scope) {
case PAGE_SCOPE:
return getAttributeNames();
case REQUEST_SCOPE:
return this.request.getAttributeNames();
case SESSION_SCOPE:
HttpSession session = this.request.getSession(false);
return (session != null ? session.getAttributeNames() : null);
case APPLICATION_SCOPE:
return this.servletContext.getAttributeNames();
default:
throw new IllegalArgumentException("Invalid scope: " + scope);
}
}
public JspWriter getOut() {
if (this.out == null) {
this.out = new MockJspWriter(this.response);
}
return this.out;
}
public ExpressionEvaluator getExpressionEvaluator() {
return new MockExpressionEvaluator(this);
}
public VariableResolver getVariableResolver() {
return null;
}
public HttpSession getSession() {
return this.request.getSession();
}
public Object getPage() {
throw new UnsupportedOperationException("getPage");
}
public ServletRequest getRequest() {
return this.request;
}
public ServletResponse getResponse() {
return this.response;
}
public Exception getException() {
throw new UnsupportedOperationException("getException");
}
public ServletConfig getServletConfig() {
return this.servletConfig;
}
public ServletContext getServletContext() {
return this.servletContext;
}
public void forward(String url) throws ServletException, IOException {
throw new UnsupportedOperationException("forward");
}
public void include(String url) throws ServletException, IOException {
throw new UnsupportedOperationException("include");
}
public void include(String url, boolean flush) throws ServletException, IOException {
throw new UnsupportedOperationException("include");
}
public void handlePageException(Exception ex) throws ServletException, IOException {
throw new UnsupportedOperationException("handlePageException");
}
public void handlePageException(Throwable ex) throws ServletException, IOException {
throw new UnsupportedOperationException("handlePageException");
}
}

View File

@@ -0,0 +1,74 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.tags;
import java.io.StringWriter;
import javax.servlet.jsp.JspWriter;
import junit.framework.TestCase;
import org.springframework.mock.web.MockBodyContent;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockPageContext;
import org.springframework.mock.web.MockServletContext;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.SimpleWebApplicationContext;
import org.springframework.web.servlet.ThemeResolver;
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;
import org.springframework.web.servlet.theme.FixedThemeResolver;
/**
* Abstract base class for testing tags: provides createPageContext.
*
* @author Alef Arendsen
* @author Juergen Hoeller
*/
public abstract class AbstractTagTests extends TestCase {
protected MockPageContext createPageContext() {
MockServletContext sc = new MockServletContext();
SimpleWebApplicationContext wac = new SimpleWebApplicationContext();
wac.setServletContext(sc);
wac.setNamespace("test");
wac.refresh();
MockHttpServletRequest request = new MockHttpServletRequest(sc);
MockHttpServletResponse response = new MockHttpServletResponse();
if (inDispatcherServlet()) {
request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
LocaleResolver lr = new AcceptHeaderLocaleResolver();
request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, lr);
ThemeResolver tr = new FixedThemeResolver();
request.setAttribute(DispatcherServlet.THEME_RESOLVER_ATTRIBUTE, tr);
request.setAttribute(DispatcherServlet.THEME_SOURCE_ATTRIBUTE, wac);
}
else {
sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
}
return new MockPageContext(sc, request, response);
}
protected boolean inDispatcherServlet() {
return true;
}
}

View File

@@ -0,0 +1,29 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.tags;
/**
* @author Juergen Hoeller
* @since 14.01.2005
*/
public class BindTagOutsideDispatcherServletTests extends BindTagTests {
protected boolean inDispatcherServlet() {
return false;
}
}

View File

@@ -0,0 +1,29 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.tags;
/**
* @author Juergen Hoeller
* @since 14.01.2005
*/
public class HtmlEscapeTagOutsideDispatcherServletTests extends HtmlEscapeTagTests {
protected boolean inDispatcherServlet() {
return false;
}
}

View File

@@ -0,0 +1,182 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.tags;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.BodyTag;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.util.WebUtils;
/**
* @author Juergen Hoeller
* @author Alef Arendsen
*/
public class HtmlEscapeTagTests extends AbstractTagTests {
public void testHtmlEscapeTag() throws JspException {
PageContext pc = createPageContext();
HtmlEscapeTag tag = new HtmlEscapeTag();
tag.setPageContext(pc);
tag.doStartTag();
HtmlEscapingAwareTag testTag = new HtmlEscapingAwareTag() {
public int doStartTagInternal() throws Exception {
return EVAL_BODY_INCLUDE;
}
};
testTag.setPageContext(pc);
testTag.doStartTag();
assertTrue("Correct default", !tag.getRequestContext().isDefaultHtmlEscape());
assertTrue("Correctly applied", !testTag.isHtmlEscape());
tag.setDefaultHtmlEscape("true");
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
assertTrue("Correctly enabled", tag.getRequestContext().isDefaultHtmlEscape());
assertTrue("Correctly applied", testTag.isHtmlEscape());
tag.setDefaultHtmlEscape("false");
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
assertTrue("Correctly disabled", !tag.getRequestContext().isDefaultHtmlEscape());
assertTrue("Correctly applied", !testTag.isHtmlEscape());
tag.setDefaultHtmlEscape("true");
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
testTag.setHtmlEscape("true");
assertTrue("Correctly enabled", tag.getRequestContext().isDefaultHtmlEscape());
assertTrue("Correctly applied", testTag.isHtmlEscape());
testTag.setHtmlEscape("false");
assertTrue("Correctly enabled", tag.getRequestContext().isDefaultHtmlEscape());
assertTrue("Correctly applied", !testTag.isHtmlEscape());
tag.setDefaultHtmlEscape("false");
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
testTag.setHtmlEscape("true");
assertTrue("Correctly disabled", !tag.getRequestContext().isDefaultHtmlEscape());
assertTrue("Correctly applied", testTag.isHtmlEscape());
testTag.setHtmlEscape("false");
assertTrue("Correctly disabled", !tag.getRequestContext().isDefaultHtmlEscape());
assertTrue("Correctly applied", !testTag.isHtmlEscape());
}
public void testHtmlEscapeTagWithContextParamTrue() throws JspException {
PageContext pc = createPageContext();
MockServletContext sc = (MockServletContext) pc.getServletContext();
sc.addInitParameter(WebUtils.HTML_ESCAPE_CONTEXT_PARAM, "true");
HtmlEscapeTag tag = new HtmlEscapeTag();
tag.setDefaultHtmlEscape("false");
tag.setPageContext(pc);
tag.doStartTag();
assertTrue("Correct default", !tag.getRequestContext().isDefaultHtmlEscape());
tag.setDefaultHtmlEscape("true");
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
assertTrue("Correctly enabled", tag.getRequestContext().isDefaultHtmlEscape());
tag.setDefaultHtmlEscape("false");
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
assertTrue("Correctly disabled", !tag.getRequestContext().isDefaultHtmlEscape());
}
public void testHtmlEscapeTagWithContextParamFalse() throws JspException {
PageContext pc = createPageContext();
MockServletContext sc = (MockServletContext) pc.getServletContext();
HtmlEscapeTag tag = new HtmlEscapeTag();
tag.setPageContext(pc);
tag.doStartTag();
sc.addInitParameter(WebUtils.HTML_ESCAPE_CONTEXT_PARAM, "false");
assertTrue("Correct default", !tag.getRequestContext().isDefaultHtmlEscape());
tag.setDefaultHtmlEscape("true");
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
assertTrue("Correctly enabled", tag.getRequestContext().isDefaultHtmlEscape());
tag.setDefaultHtmlEscape("false");
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
assertTrue("Correctly disabled", !tag.getRequestContext().isDefaultHtmlEscape());
}
public void testEscapeBody() throws JspException {
PageContext pc = createPageContext();
final StringBuffer result = new StringBuffer();
EscapeBodyTag tag = new EscapeBodyTag() {
protected String readBodyContent() {
return "test text";
}
protected void writeBodyContent(String content) {
result.append(content);
}
};
tag.setPageContext(pc);
assertEquals(BodyTag.EVAL_BODY_BUFFERED, tag.doStartTag());
assertEquals(Tag.SKIP_BODY, tag.doAfterBody());
assertEquals("test text", result.toString());
}
public void testEscapeBodyWithHtmlEscape() throws JspException {
PageContext pc = createPageContext();
final StringBuffer result = new StringBuffer();
EscapeBodyTag tag = new EscapeBodyTag() {
protected String readBodyContent() {
return "test & text";
}
protected void writeBodyContent(String content) {
result.append(content);
}
};
tag.setPageContext(pc);
tag.setHtmlEscape("true");
assertEquals(BodyTag.EVAL_BODY_BUFFERED, tag.doStartTag());
assertEquals(Tag.SKIP_BODY, tag.doAfterBody());
assertEquals("test &amp; text", result.toString());
}
public void testEscapeBodyWithJavaScriptEscape() throws JspException {
PageContext pc = createPageContext();
final StringBuffer result = new StringBuffer();
EscapeBodyTag tag = new EscapeBodyTag() {
protected String readBodyContent() {
return "' test & text \\";
}
protected void writeBodyContent(String content) {
result.append(content);
}
};
tag.setPageContext(pc);
tag.setJavaScriptEscape("true");
assertEquals(BodyTag.EVAL_BODY_BUFFERED, tag.doStartTag());
assertEquals(Tag.SKIP_BODY, tag.doAfterBody());
assertEquals("Correct content", "\\' test & text \\\\", result.toString());
}
public void testEscapeBodyWithHtmlEscapeAndJavaScriptEscape() throws JspException {
PageContext pc = createPageContext();
final StringBuffer result = new StringBuffer();
EscapeBodyTag tag = new EscapeBodyTag() {
protected String readBodyContent() {
return "' test & text \\";
}
protected void writeBodyContent(String content) {
result.append(content);
}
};
tag.setPageContext(pc);
tag.setHtmlEscape("true");
tag.setJavaScriptEscape("true");
assertEquals(BodyTag.EVAL_BODY_BUFFERED, tag.doStartTag());
assertEquals(Tag.SKIP_BODY, tag.doAfterBody());
assertEquals("Correct content", "\\' test &amp; text \\\\", result.toString());
}
}

View File

@@ -0,0 +1,29 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.tags;
/**
* @author Juergen Hoeller
* @since 14.01.2005
*/
public class MessageTagOutsideDispatcherServletTests extends MessageTagTests {
protected boolean inDispatcherServlet() {
return false;
}
}

View File

@@ -0,0 +1,422 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.tags;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.context.ConfigurableWebApplicationContext;
import org.springframework.web.servlet.support.RequestContext;
import org.springframework.web.servlet.support.RequestContextUtils;
/**
* @author Juergen Hoeller
* @author Alef Arendsen
*/
public class MessageTagTests extends AbstractTagTests {
public void testMessageTagWithMessageSourceResolvable1() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
protected void writeMessage(String msg) {
message.append(msg);
}
};
tag.setPageContext(pc);
tag.setMessage(new DefaultMessageSourceResolvable("test"));
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
assertEquals("Correct message", "test message", message.toString());
}
public void testMessageTagWithMessageSourceResolvable2() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
protected void writeMessage(String msg) {
message.append(msg);
}
};
tag.setPageContext(pc);
pc.setAttribute("myattr", new DefaultMessageSourceResolvable("test"));
tag.setMessage("${myattr}");
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
assertEquals("Correct message", "test message", message.toString());
}
public void testMessageTagWithCode1() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
protected void writeMessage(String msg) {
message.append(msg);
}
};
tag.setPageContext(pc);
tag.setCode("test");
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
assertEquals("Correct message", "test message", message.toString());
}
public void testMessageTagWithCode2() throws JspException {
PageContext pc = createPageContext();
MockHttpServletRequest request = (MockHttpServletRequest) pc.getRequest();
request.addPreferredLocale(Locale.CANADA);
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
protected void writeMessage(String msg) {
message.append(msg);
}
};
tag.setPageContext(pc);
pc.setAttribute("myattr", "test");
tag.setCode("${myattr}");
tag.setHtmlEscape("true");
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
assertEquals("Correct message", "Canadian &amp; test message", message.toString());
}
public void testMessageTagWithNullCode() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
protected void writeMessage(String msg) {
message.append(msg);
}
};
tag.setPageContext(pc);
tag.setCode(null);
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
assertEquals("Correct message", "null", message.toString());
}
public void testMessageTagWithCodeAndArgument() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
protected void writeMessage(String msg) {
message.append(msg);
}
};
tag.setPageContext(pc);
tag.setCode("testArgs");
tag.setArguments("arg1");
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
assertEquals("Correct message", "test arg1 message {1}", message.toString());
}
public void testMessageTagWithCodeAndArguments() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
protected void writeMessage(String msg) {
message.append(msg);
}
};
tag.setPageContext(pc);
tag.setCode("testArgs");
tag.setArguments("arg1,arg2");
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
assertEquals("Correct message", "test arg1 message arg2", message.toString());
}
public void testMessageTagWithCodeAndStringArgumentWithCustomSeparator() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
protected void writeMessage(String msg) {
message.append(msg);
}
};
tag.setPageContext(pc);
tag.setCode("testArgs");
tag.setArguments("arg1,1;arg2,2");
tag.setArgumentSeparator(";");
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
assertEquals("Correct message", "test arg1,1 message arg2,2", message.toString());
}
public void testMessageTagWithCodeAndArrayArgument() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
protected void writeMessage(String msg) {
message.append(msg);
}
};
tag.setPageContext(pc);
tag.setCode("testArgs");
tag.setArguments(new Object[] {"arg1", new Integer(5)});
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
assertEquals("Correct message", "test arg1 message 5", message.toString());
}
public void testMessageTagWithCodeAndObjectArgument() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
protected void writeMessage(String msg) {
message.append(msg);
}
};
tag.setPageContext(pc);
tag.setCode("testArgs");
tag.setArguments(new Integer(5));
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
assertEquals("Correct message", "test 5 message {1}", message.toString());
}
public void testMessageTagWithCodeAndExpressionArgument() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
protected void writeMessage(String msg) {
message.append(msg);
}
};
tag.setPageContext(pc);
tag.setCode("testArgs");
tag.setArguments("${arg1}");
pc.setAttribute("arg1", "my,value");
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
assertEquals("Correct message", "test my,value message {1}", message.toString());
}
public void testMessageTagWithCodeAndExpressionArguments() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
protected void writeMessage(String msg) {
message.append(msg);
}
};
tag.setPageContext(pc);
tag.setCode("testArgs");
tag.setArguments("${arg1},${arg2}");
pc.setAttribute("arg1", "my,value");
pc.setAttribute("arg2", new Integer(5));
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
assertEquals("Correct message", "test my,value message 5", message.toString());
}
public void testMessageTagWithCodeAndExpressionArgumentArray() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
protected void writeMessage(String msg) {
message.append(msg);
}
};
tag.setPageContext(pc);
tag.setCode("testArgs");
tag.setArguments("${argArray}");
pc.setAttribute("argArray", new Object[] {"my,value", new Integer(5)});
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
assertEquals("Correct message", "test my,value message 5", message.toString());
}
public void testMessageTagWithCodeAndExpressionArgumentFormat() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
protected void writeMessage(String msg) {
message.append(msg);
}
};
tag.setPageContext(pc);
tag.setCode("testArgsFormat");
tag.setArguments("${arg1},${arg2}");
pc.setAttribute("arg1", "my,value");
pc.setAttribute("arg2", new Float(5.145));
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
assertEquals("Correct message", "test my,value message 5.14 X", message.toString());
}
public void testMessageTagWithCodeAndText1() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
protected void writeMessage(String msg) {
message.append(msg);
}
};
tag.setPageContext(pc);
tag.setCode("test");
tag.setText("testtext");
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
assertEquals("Correct message", "test message", (message.toString()));
}
public void testMessageTagWithCodeAndText2() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
protected void writeMessage(String msg) {
message.append(msg);
}
};
tag.setPageContext(pc);
pc.setAttribute("myattr", "test & text");
tag.setCode("test2");
tag.setText("${myattr}");
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
assertEquals("Correct message", "test & text", message.toString());
}
public void testMessageTagWithText() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
protected void writeMessage(String msg) {
message.append(msg);
}
};
tag.setPageContext(pc);
tag.setText("test & text");
tag.setHtmlEscape("true");
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
assertEquals("Correct message", "test &amp; text", message.toString());
}
public void testMessageTagWithTextAndExpressionArgumentFormat() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
protected void writeMessage(String msg) {
message.append(msg);
}
};
tag.setPageContext(pc);
tag.setText("test {0} message {1,number,#.##} X");
tag.setArguments("${arg1},${arg2}");
pc.setAttribute("arg1", "my,value");
pc.setAttribute("arg2", new Float(5.145));
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
assertEquals("Correct message", "test my,value message 5.14 X", message.toString());
}
public void testMessageTagWithTextAndJavaScriptEscape() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
protected void writeMessage(String msg) {
message.append(msg);
}
};
tag.setPageContext(pc);
tag.setText("' test & text \\");
tag.setJavaScriptEscape("true");
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
assertEquals("Correct message", "\\' test & text \\\\", message.toString());
}
public void testMessageTagWithTextAndHtmlEscapeAndJavaScriptEscape() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
protected void writeMessage(String msg) {
message.append(msg);
}
};
tag.setPageContext(pc);
tag.setText("' test & text \\");
tag.setHtmlEscape("true");
tag.setJavaScriptEscape("true");
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
assertEquals("Correct message", "\\' test &amp; text \\\\", message.toString());
}
public void testMessageWithVarAndScope() throws JspException {
PageContext pc = createPageContext();
MessageTag tag = new MessageTag();
tag.setPageContext(pc);
tag.setText("text & text");
tag.setVar("testvar");
tag.setScope("page");
tag.doStartTag();
assertEquals("text & text", pc.getAttribute("testvar"));
tag.release();
tag = new MessageTag();
tag.setPageContext(pc);
tag.setCode("test");
tag.setVar("testvar2");
tag.doStartTag();
assertEquals("Correct message", "test message", pc.getAttribute("testvar2"));
tag.release();
}
public void testMessageWithVar() throws JspException {
PageContext pc = createPageContext();
MessageTag tag = new MessageTag();
tag.setPageContext(pc);
tag.setText("text & text");
tag.setVar("testvar");
tag.doStartTag();
assertEquals("text & text", pc.getAttribute("testvar"));
tag.release();
// try to reuse
tag.setPageContext(pc);
tag.setCode("test");
tag.setVar("testvar");
tag.doStartTag();
assertEquals("Correct message", "test message", pc.getAttribute("testvar"));
}
public void testNullMessageSource() throws JspException {
PageContext pc = createPageContext();
ConfigurableWebApplicationContext ctx = (ConfigurableWebApplicationContext)
RequestContextUtils.getWebApplicationContext(pc.getRequest(), pc.getServletContext());
ctx.close();
MessageTag tag = new MessageTag();
tag.setPageContext(pc);
tag.setCode("test");
tag.setVar("testvar2");
tag.doStartTag();
}
public void testRequestContext() throws ServletException {
PageContext pc = createPageContext();
RequestContext rc = new RequestContext((HttpServletRequest) pc.getRequest(), pc.getServletContext());
assertEquals("test message", rc.getMessage("test"));
assertEquals("test message", rc.getMessage("test", (Object[]) null));
assertEquals("test message", rc.getMessage("test", "default"));
assertEquals("test message", rc.getMessage("test", (Object[]) null, "default"));
assertEquals("test arg1 message arg2",
rc.getMessage("testArgs", new String[] {"arg1", "arg2"}, "default"));
assertEquals("test arg1 message arg2",
rc.getMessage("testArgs", Arrays.asList(new String[] {"arg1", "arg2"}), "default"));
assertEquals("default", rc.getMessage("testa", "default"));
assertEquals("default", rc.getMessage("testa", (List) null, "default"));
MessageSourceResolvable resolvable = new DefaultMessageSourceResolvable(new String[] {"test"});
assertEquals("test message", rc.getMessage(resolvable));
}
}

View File

@@ -0,0 +1,69 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.tags;
import java.util.Arrays;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.web.servlet.support.RequestContext;
/**
* @author Juergen Hoeller
* @author Alef Arendsen
*/
public class ThemeTagTests extends AbstractTagTests {
public void testThemeTag() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
ThemeTag tag = new ThemeTag() {
protected void writeMessage(String msg) {
message.append(msg);
}
};
tag.setPageContext(pc);
tag.setCode("themetest");
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
assertEquals("theme test message", message.toString());
}
public void testRequestContext() throws ServletException {
PageContext pc = createPageContext();
RequestContext rc = new RequestContext((HttpServletRequest) pc.getRequest());
assertEquals("theme test message", rc.getThemeMessage("themetest"));
assertEquals("theme test message", rc.getThemeMessage("themetest", (String[]) null));
assertEquals("theme test message", rc.getThemeMessage("themetest", "default"));
assertEquals("theme test message", rc.getThemeMessage("themetest", (Object[]) null, "default"));
assertEquals("theme test message arg1",
rc.getThemeMessage("themetestArgs", new String[] {"arg1"}));
assertEquals("theme test message arg1",
rc.getThemeMessage("themetestArgs", Arrays.asList(new String[] {"arg1"})));
assertEquals("default", rc.getThemeMessage("themetesta", "default"));
assertEquals("default", rc.getThemeMessage("themetesta", (List) null, "default"));
MessageSourceResolvable resolvable = new DefaultMessageSourceResolvable(new String[] {"themetest"});
assertEquals("theme test message", rc.getThemeMessage(resolvable));
}
}

View File

@@ -0,0 +1,51 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.tags.form;
import javax.servlet.jsp.JspException;
import org.springframework.beans.TestBean;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockPageContext;
/**
* @author Rob Harrop
* @author Juergen Hoeller
*/
public abstract class AbstractFormTagTests extends AbstractHtmlElementTagTests {
private FormTag formTag = new FormTag();
protected void extendRequest(MockHttpServletRequest request) {
request.setAttribute(COMMAND_NAME, createTestBean());
}
protected abstract TestBean createTestBean();
protected void extendPageContext(MockPageContext pageContext) throws JspException {
this.formTag.setCommandName(COMMAND_NAME);
this.formTag.setAction("myAction");
this.formTag.setPageContext(pageContext);
this.formTag.doStartTag();
}
protected final FormTag getFormTag() {
return this.formTag;
}
}

View File

@@ -0,0 +1,125 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.tags.form;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockPageContext;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.web.servlet.support.JspAwareRequestContext;
import org.springframework.web.servlet.support.RequestContext;
import org.springframework.web.servlet.tags.AbstractTagTests;
import org.springframework.web.servlet.tags.RequestContextAwareTag;
/**
* @author Rob Harrop
* @author Juergen Hoeller
*/
public abstract class AbstractHtmlElementTagTests extends AbstractTagTests {
public static final String COMMAND_NAME = "testBean";
private StringWriter writer;
private MockPageContext pageContext;
protected final void setUp() throws Exception {
// set up a writer for the tag content to be written to
this.writer = new StringWriter();
// configure the page context
this.pageContext = createAndPopulatePageContext();
onSetUp();
}
protected MockPageContext createAndPopulatePageContext() throws JspException {
MockPageContext pageContext = createPageContext();
MockHttpServletRequest request = (MockHttpServletRequest) pageContext.getRequest();
RequestContext requestContext = new JspAwareRequestContext(pageContext);
pageContext.setAttribute(RequestContextAwareTag.REQUEST_CONTEXT_PAGE_ATTRIBUTE, requestContext);
extendRequest(request);
extendPageContext(pageContext);
return pageContext;
}
protected void extendPageContext(MockPageContext pageContext) throws JspException {
}
protected void extendRequest(MockHttpServletRequest request) {
}
protected void onSetUp() {
}
protected MockPageContext getPageContext() {
return this.pageContext;
}
protected Writer getWriter() {
return this.writer;
}
protected String getOutput() {
return this.writer.toString();
}
protected final RequestContext getRequestContext() {
return (RequestContext) getPageContext().getAttribute(RequestContextAwareTag.REQUEST_CONTEXT_PAGE_ATTRIBUTE);
}
protected void exposeBindingResult(Errors errors) {
// wrap errors in a Model
Map model = new HashMap();
model.put(BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, errors);
// replace the request context with one containing the errors
MockPageContext pageContext = getPageContext();
RequestContext context = new RequestContext((HttpServletRequest) pageContext.getRequest(), model);
pageContext.setAttribute(RequestContextAwareTag.REQUEST_CONTEXT_PAGE_ATTRIBUTE, context);
}
protected final void assertContainsAttribute(String output, String attributeName, String attributeValue) {
String attributeString = attributeName + "=\"" + attributeValue + "\"";
assertTrue("Expected to find attribute '" + attributeName +
"' with value '" + attributeValue +
"' in output + '" + output + "'",
output.indexOf(attributeString) > -1);
}
protected final void assertAttributeNotPresent(String output, String attributeName) {
assertTrue("Unexpected attribute '" + attributeName + "' in output '" + output + "'.",
output.indexOf(attributeName + "=\"") < 0);
}
protected final void assertBlockTagContains(String output, String desiredContents) {
String contents = output.substring(output.indexOf(">") + 1, output.lastIndexOf("<"));
assertTrue("Expected to find '" + desiredContents + "' in the contents of block tag '" + output + "'",
contents.indexOf(desiredContents) > -1);
}
}

View File

@@ -0,0 +1,624 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.tags.form;
import java.beans.PropertyEditorSupport;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.servlet.jsp.tagext.Tag;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.Colour;
import org.springframework.beans.Pet;
import org.springframework.beans.TestBean;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
/**
* @author Rob Harrop
* @author Juergen Hoeller
*/
public class CheckboxTagTests extends AbstractFormTagTests {
private CheckboxTag tag;
private TestBean bean;
protected void onSetUp() {
this.tag = new CheckboxTag() {
protected TagWriter createTagWriter() {
return new TagWriter(getWriter());
}
};
this.tag.setPageContext(getPageContext());
}
public void testWithSingleValueBooleanObjectChecked() throws Exception {
this.tag.setPath("someBoolean");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element rootElement = document.getRootElement();
assertEquals("Both tag and hidden element not rendered", 2, rootElement.elements().size());
Element checkboxElement = (Element) rootElement.elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("someBoolean", checkboxElement.attribute("name").getValue());
assertEquals("checked", checkboxElement.attribute("checked").getValue());
assertEquals("true", checkboxElement.attribute("value").getValue());
}
public void testWithSingleValueBooleanChecked() throws Exception {
this.tag.setPath("jedi");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element checkboxElement = (Element) document.getRootElement().elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("jedi", checkboxElement.attribute("name").getValue());
assertEquals("checked", checkboxElement.attribute("checked").getValue());
assertEquals("true", checkboxElement.attribute("value").getValue());
}
public void testWithSingleValueBooleanObjectUnchecked() throws Exception {
this.bean.setSomeBoolean(new Boolean(false));
this.tag.setPath("someBoolean");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element checkboxElement = (Element) document.getRootElement().elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("someBoolean", checkboxElement.attribute("name").getValue());
assertNull(checkboxElement.attribute("checked"));
assertEquals("true", checkboxElement.attribute("value").getValue());
}
public void testWithSingleValueBooleanUnchecked() throws Exception {
this.bean.setJedi(false);
this.tag.setPath("jedi");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element checkboxElement = (Element) document.getRootElement().elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("jedi", checkboxElement.attribute("name").getValue());
assertNull(checkboxElement.attribute("checked"));
assertEquals("true", checkboxElement.attribute("value").getValue());
}
public void testWithSingleValueNull() throws Exception {
this.bean.setName(null);
this.tag.setPath("name");
this.tag.setValue("Rob Harrop");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element checkboxElement = (Element) document.getRootElement().elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("name", checkboxElement.attribute("name").getValue());
assertNull(checkboxElement.attribute("checked"));
assertEquals("Rob Harrop", checkboxElement.attribute("value").getValue());
}
public void testWithSingleValueNotNull() throws Exception {
this.bean.setName("Rob Harrop");
this.tag.setPath("name");
this.tag.setValue("Rob Harrop");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element checkboxElement = (Element) document.getRootElement().elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("name", checkboxElement.attribute("name").getValue());
assertEquals("checked", checkboxElement.attribute("checked").getValue());
assertEquals("Rob Harrop", checkboxElement.attribute("value").getValue());
}
public void testWithSingleValueAndEditor() throws Exception {
this.bean.setName("Rob Harrop");
this.tag.setPath("name");
this.tag.setValue(" Rob Harrop");
BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
bindingResult.getPropertyEditorRegistry().registerCustomEditor(String.class, new StringTrimmerEditor(false));
getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, bindingResult);
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element checkboxElement = (Element) document.getRootElement().elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("name", checkboxElement.attribute("name").getValue());
assertEquals("checked", checkboxElement.attribute("checked").getValue());
assertEquals(" Rob Harrop", checkboxElement.attribute("value").getValue());
}
public void testWithMultiValueChecked() throws Exception {
this.tag.setPath("stringArray");
this.tag.setValue("foo");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element checkboxElement = (Element) document.getRootElement().elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("stringArray", checkboxElement.attribute("name").getValue());
assertEquals("checked", checkboxElement.attribute("checked").getValue());
assertEquals("foo", checkboxElement.attribute("value").getValue());
}
public void testWithMultiValueUnchecked() throws Exception {
this.tag.setPath("stringArray");
this.tag.setValue("abc");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element checkboxElement = (Element) document.getRootElement().elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("stringArray", checkboxElement.attribute("name").getValue());
assertNull(checkboxElement.attribute("checked"));
assertEquals("abc", checkboxElement.attribute("value").getValue());
}
public void testWithMultiValueWithEditor() throws Exception {
this.tag.setPath("stringArray");
this.tag.setValue(" foo");
BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
MyStringTrimmerEditor editor = new MyStringTrimmerEditor();
bindingResult.getPropertyEditorRegistry().registerCustomEditor(String.class, editor);
getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, bindingResult);
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
assertEquals(1, editor.count);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element checkboxElement = (Element) document.getRootElement().elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("stringArray", checkboxElement.attribute("name").getValue());
assertEquals("checked", checkboxElement.attribute("checked").getValue());
assertEquals(" foo", checkboxElement.attribute("value").getValue());
}
public void testWithMultiValueIntegerWithEditor() throws Exception {
this.tag.setPath("someIntegerArray");
this.tag.setValue(" 1");
BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
MyIntegerEditor editor = new MyIntegerEditor();
bindingResult.getPropertyEditorRegistry().registerCustomEditor(Integer.class, editor);
getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, bindingResult);
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
assertEquals(1, editor.count);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element checkboxElement = (Element) document.getRootElement().elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("someIntegerArray", checkboxElement.attribute("name").getValue());
assertEquals("checked", checkboxElement.attribute("checked").getValue());
assertEquals(" 1", checkboxElement.attribute("value").getValue());
}
public void testWithCollection() throws Exception {
this.tag.setPath("someList");
this.tag.setValue("foo");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element checkboxElement = (Element) document.getRootElement().elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("someList", checkboxElement.attribute("name").getValue());
assertEquals("checked", checkboxElement.attribute("checked").getValue());
assertEquals("foo", checkboxElement.attribute("value").getValue());
}
public void testWithObjectChecked() throws Exception {
this.tag.setPath("date");
this.tag.setValue(getDate());
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element checkboxElement = (Element) document.getRootElement().elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("date", checkboxElement.attribute("name").getValue());
assertEquals("checked", checkboxElement.attribute("checked").getValue());
assertEquals(getDate().toString(), checkboxElement.attribute("value").getValue());
}
public void testWithObjectUnchecked() throws Exception {
this.tag.setPath("date");
Date date = new Date();
this.tag.setValue(date);
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element checkboxElement = (Element) document.getRootElement().elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("date", checkboxElement.attribute("name").getValue());
assertNull(checkboxElement.attribute("checked"));
assertEquals(date.toString(), checkboxElement.attribute("value").getValue());
}
public void testCollectionOfColoursSelected() throws Exception {
this.tag.setPath("otherColours");
this.tag.setValue("RED");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element checkboxElement = (Element) document.getRootElement().elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("otherColours", checkboxElement.attribute("name").getValue());
assertEquals("checked", checkboxElement.attribute("checked").getValue());
}
public void testCollectionOfColoursNotSelected() throws Exception {
this.tag.setPath("otherColours");
this.tag.setValue("PURPLE");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element checkboxElement = (Element) document.getRootElement().elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("otherColours", checkboxElement.attribute("name").getValue());
assertNull(checkboxElement.attribute("checked"));
}
public void testCollectionOfPetsAsString() throws Exception {
this.tag.setPath("pets");
this.tag.setValue("Spot");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element checkboxElement = (Element) document.getRootElement().elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("pets", checkboxElement.attribute("name").getValue());
assertEquals("checked", checkboxElement.attribute("checked").getValue());
}
public void testCollectionOfPetsAsStringNotSelected() throws Exception {
this.tag.setPath("pets");
this.tag.setValue("Santa's Little Helper");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element checkboxElement = (Element) document.getRootElement().elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("pets", checkboxElement.attribute("name").getValue());
assertNull(checkboxElement.attribute("checked"));
}
public void testCollectionOfPets() throws Exception {
this.tag.setPath("pets");
this.tag.setValue(new Pet("Rudiger"));
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element checkboxElement = (Element) document.getRootElement().elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("pets", checkboxElement.attribute("name").getValue());
assertEquals("Rudiger", checkboxElement.attribute("value").getValue());
assertEquals("checked", checkboxElement.attribute("checked").getValue());
}
public void testCollectionOfPetsNotSelected() throws Exception {
this.tag.setPath("pets");
this.tag.setValue(new Pet("Santa's Little Helper"));
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element checkboxElement = (Element) document.getRootElement().elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("pets", checkboxElement.attribute("name").getValue());
assertEquals("Santa's Little Helper", checkboxElement.attribute("value").getValue());
assertNull(checkboxElement.attribute("checked"));
}
public void testCollectionOfPetsWithEditor() throws Exception {
this.tag.setPath("pets");
this.tag.setValue(new ItemPet("Rudiger"));
BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
PropertyEditorSupport editor = new ItemPet.CustomEditor();
bindingResult.getPropertyEditorRegistry().registerCustomEditor(ItemPet.class, editor);
getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, bindingResult);
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element checkboxElement = (Element) document.getRootElement().elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("pets", checkboxElement.attribute("name").getValue());
assertEquals("Rudiger", checkboxElement.attribute("value").getValue());
assertEquals("checked", checkboxElement.attribute("checked").getValue());
}
public void testWithNullValue() throws Exception {
try {
this.tag.setPath("name");
this.tag.doStartTag();
fail("Should not be able to render with a null value when binding to a non-boolean.");
}
catch (IllegalArgumentException e) {
// success
}
}
public void testHiddenElementOmittedOnDisabled() throws Exception {
this.tag.setPath("someBoolean");
this.tag.setDisabled("true");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element rootElement = document.getRootElement();
assertEquals("Both tag and hidden element rendered incorrectly", 1, rootElement.elements().size());
Element checkboxElement = (Element) rootElement.elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("someBoolean", checkboxElement.attribute("name").getValue());
assertEquals("checked", checkboxElement.attribute("checked").getValue());
assertEquals("true", checkboxElement.attribute("value").getValue());
}
private Date getDate() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 10);
cal.set(Calendar.MONTH, 10);
cal.set(Calendar.DATE, 10);
cal.set(Calendar.HOUR, 10);
cal.set(Calendar.MINUTE, 10);
cal.set(Calendar.SECOND, 10);
return cal.getTime();
}
protected TestBean createTestBean() {
List colours = new ArrayList();
colours.add(Colour.BLUE);
colours.add(Colour.RED);
colours.add(Colour.GREEN);
List pets = new ArrayList();
pets.add(new Pet("Rudiger"));
pets.add(new Pet("Spot"));
pets.add(new Pet("Fluffy"));
pets.add(new Pet("Mufty"));
this.bean = new TestBean();
this.bean.setDate(getDate());
this.bean.setName("Rob Harrop");
this.bean.setJedi(true);
this.bean.setSomeBoolean(new Boolean(true));
this.bean.setStringArray(new String[] {"bar", "foo"});
this.bean.setSomeIntegerArray(new Integer[] {new Integer(2), new Integer(1)});
this.bean.setOtherColours(colours);
this.bean.setPets(pets);
List list = new ArrayList();
list.add("foo");
list.add("bar");
this.bean.setSomeList(list);
return this.bean;
}
private class MyStringTrimmerEditor extends StringTrimmerEditor {
public int count = 0;
public MyStringTrimmerEditor() {
super(false);
}
public void setAsText(String text) {
this.count++;
super.setAsText(text);
}
}
private class MyIntegerEditor extends PropertyEditorSupport {
public int count = 0;
public void setAsText(String text) {
this.count++;
setValue(new Integer(text.trim()));
}
}
}

View File

@@ -0,0 +1,671 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.tags.form;
import java.beans.PropertyEditorSupport;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.jsp.tagext.Tag;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.Colour;
import org.springframework.beans.Pet;
import org.springframework.beans.TestBean;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
/**
* @author Thomas Risberg
* @author Mark Fisher
* @author Juergen Hoeller
* @author Benjamin Hoffmann
*/
public class CheckboxesTagTests extends AbstractFormTagTests {
private CheckboxesTag tag;
private TestBean bean;
protected void onSetUp() {
this.tag = new CheckboxesTag() {
protected TagWriter createTagWriter() {
return new TagWriter(getWriter());
}
};
this.tag.setPageContext(getPageContext());
}
public void testWithMultiValueArray() throws Exception {
this.tag.setPath("stringArray");
this.tag.setItems(new Object[] {"foo", "bar", "baz"});
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element spanElement1 = (Element) document.getRootElement().elements().get(0);
Element checkboxElement1 = (Element) spanElement1.elements().get(0);
assertEquals("input", checkboxElement1.getName());
assertEquals("checkbox", checkboxElement1.attribute("type").getValue());
assertEquals("stringArray", checkboxElement1.attribute("name").getValue());
assertEquals("checked", checkboxElement1.attribute("checked").getValue());
assertEquals("foo", checkboxElement1.attribute("value").getValue());
assertEquals("foo", spanElement1.getStringValue());
Element spanElement2 = (Element) document.getRootElement().elements().get(1);
Element checkboxElement2 = (Element) spanElement2.elements().get(0);
assertEquals("input", checkboxElement2.getName());
assertEquals("checkbox", checkboxElement2.attribute("type").getValue());
assertEquals("stringArray", checkboxElement2.attribute("name").getValue());
assertEquals("checked", checkboxElement2.attribute("checked").getValue());
assertEquals("bar", checkboxElement2.attribute("value").getValue());
assertEquals("bar", spanElement2.getStringValue());
Element spanElement3 = (Element) document.getRootElement().elements().get(2);
Element checkboxElement3 = (Element) spanElement3.elements().get(0);
assertEquals("input", checkboxElement3.getName());
assertEquals("checkbox", checkboxElement3.attribute("type").getValue());
assertEquals("stringArray", checkboxElement3.attribute("name").getValue());
assertNull("not checked", checkboxElement3.attribute("checked"));
assertEquals("baz", checkboxElement3.attribute("value").getValue());
assertEquals("baz", spanElement3.getStringValue());
}
public void testWithMultiValueArrayWithDelimiter() throws Exception {
this.tag.setDelimiter("<br/>");
this.tag.setPath("stringArray");
this.tag.setItems(new Object[] {"foo", "bar", "baz"});
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element spanElement1 = (Element) document.getRootElement().elements().get(0);
Element delimiterElement1 = spanElement1.element("br");
assertNull(delimiterElement1);
Element checkboxElement1 = (Element) spanElement1.elements().get(0);
assertEquals("input", checkboxElement1.getName());
assertEquals("checkbox", checkboxElement1.attribute("type").getValue());
assertEquals("stringArray", checkboxElement1.attribute("name").getValue());
assertEquals("checked", checkboxElement1.attribute("checked").getValue());
assertEquals("foo", checkboxElement1.attribute("value").getValue());
assertEquals("foo", spanElement1.getStringValue());
Element spanElement2 = (Element) document.getRootElement().elements().get(1);
Element delimiterElement2 = (Element) spanElement2.elements().get(0);
assertEquals("br", delimiterElement2.getName());
Element checkboxElement2 = (Element) spanElement2.elements().get(1);
assertEquals("input", checkboxElement2.getName());
assertEquals("checkbox", checkboxElement2.attribute("type").getValue());
assertEquals("stringArray", checkboxElement2.attribute("name").getValue());
assertEquals("checked", checkboxElement2.attribute("checked").getValue());
assertEquals("bar", checkboxElement2.attribute("value").getValue());
assertEquals("bar", spanElement2.getStringValue());
Element spanElement3 = (Element) document.getRootElement().elements().get(2);
Element delimiterElement3 = (Element) spanElement3.elements().get(0);
assertEquals("br", delimiterElement3.getName());
Element checkboxElement3 = (Element) spanElement3.elements().get(1);
assertEquals("input", checkboxElement3.getName());
assertEquals("checkbox", checkboxElement3.attribute("type").getValue());
assertEquals("stringArray", checkboxElement3.attribute("name").getValue());
assertNull("not checked", checkboxElement3.attribute("checked"));
assertEquals("baz", checkboxElement3.attribute("value").getValue());
assertEquals("baz", spanElement3.getStringValue());
}
public void testWithMultiValueMap() throws Exception {
this.tag.setPath("stringArray");
Map m = new LinkedHashMap();
m.put("foo", "FOO");
m.put("bar", "BAR");
m.put("baz", "BAZ");
this.tag.setItems(m);
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element spanElement1 = (Element) document.getRootElement().elements().get(0);
Element checkboxElement1 = (Element) spanElement1.elements().get(0);
assertEquals("input", checkboxElement1.getName());
assertEquals("checkbox", checkboxElement1.attribute("type").getValue());
assertEquals("stringArray", checkboxElement1.attribute("name").getValue());
assertEquals("checked", checkboxElement1.attribute("checked").getValue());
assertEquals("foo", checkboxElement1.attribute("value").getValue());
assertEquals("FOO", spanElement1.getStringValue());
Element spanElement2 = (Element) document.getRootElement().elements().get(1);
Element checkboxElement2 = (Element) spanElement2.elements().get(0);
assertEquals("input", checkboxElement2.getName());
assertEquals("checkbox", checkboxElement2.attribute("type").getValue());
assertEquals("stringArray", checkboxElement2.attribute("name").getValue());
assertEquals("checked", checkboxElement2.attribute("checked").getValue());
assertEquals("bar", checkboxElement2.attribute("value").getValue());
assertEquals("BAR", spanElement2.getStringValue());
Element spanElement3 = (Element) document.getRootElement().elements().get(2);
Element checkboxElement3 = (Element) spanElement3.elements().get(0);
assertEquals("input", checkboxElement3.getName());
assertEquals("checkbox", checkboxElement3.attribute("type").getValue());
assertEquals("stringArray", checkboxElement3.attribute("name").getValue());
assertNull("not checked", checkboxElement3.attribute("checked"));
assertEquals("baz", checkboxElement3.attribute("value").getValue());
assertEquals("BAZ", spanElement3.getStringValue());
}
public void testWithPetItemsMap() throws Exception {
this.tag.setPath("someSet");
Map m = new LinkedHashMap();
m.put(new ItemPet("PET1"), "PET1Label");
m.put(new ItemPet("PET2"), "PET2Label");
m.put(new ItemPet("PET3"), "PET3Label");
this.tag.setItems(m);
tag.setItemValue("name");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element spanElement1 = (Element) document.getRootElement().elements().get(0);
Element checkboxElement1 = (Element) spanElement1.elements().get(0);
assertEquals("input", checkboxElement1.getName());
assertEquals("checkbox", checkboxElement1.attribute("type").getValue());
assertEquals("someSet", checkboxElement1.attribute("name").getValue());
assertEquals("checked", checkboxElement1.attribute("checked").getValue());
assertEquals("PET1", checkboxElement1.attribute("value").getValue());
assertEquals("PET1Label", spanElement1.getStringValue());
Element spanElement2 = (Element) document.getRootElement().elements().get(1);
Element checkboxElement2 = (Element) spanElement2.elements().get(0);
assertEquals("input", checkboxElement2.getName());
assertEquals("checkbox", checkboxElement2.attribute("type").getValue());
assertEquals("someSet", checkboxElement2.attribute("name").getValue());
assertEquals("checked", checkboxElement2.attribute("checked").getValue());
assertEquals("PET2", checkboxElement2.attribute("value").getValue());
assertEquals("PET2Label", spanElement2.getStringValue());
Element spanElement3 = (Element) document.getRootElement().elements().get(2);
Element checkboxElement3 = (Element) spanElement3.elements().get(0);
assertEquals("input", checkboxElement3.getName());
assertEquals("checkbox", checkboxElement3.attribute("type").getValue());
assertEquals("someSet", checkboxElement3.attribute("name").getValue());
assertNull("not checked", checkboxElement3.attribute("checked"));
assertEquals("PET3", checkboxElement3.attribute("value").getValue());
assertEquals("PET3Label", spanElement3.getStringValue());
}
public void testWithMultiValueMapWithDelimiter() throws Exception {
String delimiter = " | ";
this.tag.setDelimiter(delimiter);
this.tag.setPath("stringArray");
Map m = new LinkedHashMap();
m.put("foo", "FOO");
m.put("bar", "BAR");
m.put("baz", "BAZ");
this.tag.setItems(m);
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element spanElement1 = (Element) document.getRootElement().elements().get(0);
Element checkboxElement1 = (Element) spanElement1.elements().get(0);
assertEquals("input", checkboxElement1.getName());
assertEquals("checkbox", checkboxElement1.attribute("type").getValue());
assertEquals("stringArray", checkboxElement1.attribute("name").getValue());
assertEquals("checked", checkboxElement1.attribute("checked").getValue());
assertEquals("foo", checkboxElement1.attribute("value").getValue());
assertEquals("FOO", spanElement1.getStringValue());
Element spanElement2 = (Element) document.getRootElement().elements().get(1);
Element checkboxElement2 = (Element) spanElement2.elements().get(0);
assertEquals("input", checkboxElement2.getName());
assertEquals("checkbox", checkboxElement2.attribute("type").getValue());
assertEquals("stringArray", checkboxElement2.attribute("name").getValue());
assertEquals("checked", checkboxElement2.attribute("checked").getValue());
assertEquals("bar", checkboxElement2.attribute("value").getValue());
assertEquals(delimiter + "BAR", spanElement2.getStringValue());
Element spanElement3 = (Element) document.getRootElement().elements().get(2);
Element checkboxElement3 = (Element) spanElement3.elements().get(0);
assertEquals("input", checkboxElement3.getName());
assertEquals("checkbox", checkboxElement3.attribute("type").getValue());
assertEquals("stringArray", checkboxElement3.attribute("name").getValue());
assertNull("not checked", checkboxElement3.attribute("checked"));
assertEquals("baz", checkboxElement3.attribute("value").getValue());
assertEquals(delimiter + "BAZ", spanElement3.getStringValue());
}
public void testWithMultiValueWithEditor() throws Exception {
this.tag.setPath("stringArray");
this.tag.setItems(new Object[] {" foo", " bar", " baz"});
BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
MyStringTrimmerEditor editor = new MyStringTrimmerEditor();
bindingResult.getPropertyEditorRegistry().registerCustomEditor(String.class, editor);
getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, bindingResult);
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
assertEquals(3, editor.allProcessedValues.size());
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element spanElement1 = (Element) document.getRootElement().elements().get(0);
Element checkboxElement1 = (Element) spanElement1.elements().get(0);
assertEquals("input", checkboxElement1.getName());
assertEquals("checkbox", checkboxElement1.attribute("type").getValue());
assertEquals("stringArray", checkboxElement1.attribute("name").getValue());
assertEquals("checked", checkboxElement1.attribute("checked").getValue());
assertEquals(" foo", checkboxElement1.attribute("value").getValue());
Element spanElement2 = (Element) document.getRootElement().elements().get(1);
Element checkboxElement2 = (Element) spanElement2.elements().get(0);
assertEquals("input", checkboxElement2.getName());
assertEquals("checkbox", checkboxElement2.attribute("type").getValue());
assertEquals("stringArray", checkboxElement2.attribute("name").getValue());
assertEquals("checked", checkboxElement2.attribute("checked").getValue());
assertEquals(" bar", checkboxElement2.attribute("value").getValue());
Element spanElement3 = (Element) document.getRootElement().elements().get(2);
Element checkboxElement3 = (Element) spanElement3.elements().get(0);
assertEquals("input", checkboxElement3.getName());
assertEquals("checkbox", checkboxElement3.attribute("type").getValue());
assertEquals("stringArray", checkboxElement3.attribute("name").getValue());
assertNull("not checked", checkboxElement3.attribute("checked"));
assertEquals(" baz", checkboxElement3.attribute("value").getValue());
}
public void testWithMultiValueWithReverseEditor() throws Exception {
this.tag.setPath("stringArray");
this.tag.setItems(new Object[] {"FOO", "BAR", "BAZ"});
BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
MyLowerCaseEditor editor = new MyLowerCaseEditor();
bindingResult.getPropertyEditorRegistry().registerCustomEditor(String.class, editor);
getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, bindingResult);
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element spanElement1 = (Element) document.getRootElement().elements().get(0);
Element checkboxElement1 = (Element) spanElement1.elements().get(0);
assertEquals("input", checkboxElement1.getName());
assertEquals("checkbox", checkboxElement1.attribute("type").getValue());
assertEquals("stringArray", checkboxElement1.attribute("name").getValue());
assertEquals("checked", checkboxElement1.attribute("checked").getValue());
assertEquals("FOO", checkboxElement1.attribute("value").getValue());
Element spanElement2 = (Element) document.getRootElement().elements().get(1);
Element checkboxElement2 = (Element) spanElement2.elements().get(0);
assertEquals("input", checkboxElement2.getName());
assertEquals("checkbox", checkboxElement2.attribute("type").getValue());
assertEquals("stringArray", checkboxElement2.attribute("name").getValue());
assertEquals("checked", checkboxElement2.attribute("checked").getValue());
assertEquals("BAR", checkboxElement2.attribute("value").getValue());
Element spanElement3 = (Element) document.getRootElement().elements().get(2);
Element checkboxElement3 = (Element) spanElement3.elements().get(0);
assertEquals("input", checkboxElement3.getName());
assertEquals("checkbox", checkboxElement3.attribute("type").getValue());
assertEquals("stringArray", checkboxElement3.attribute("name").getValue());
assertNull("not checked", checkboxElement3.attribute("checked"));
assertEquals("BAZ", checkboxElement3.attribute("value").getValue());
}
public void testCollectionOfPets() throws Exception {
this.tag.setPath("pets");
List allPets = new ArrayList();
allPets.add(new ItemPet("Rudiger"));
allPets.add(new ItemPet("Spot"));
allPets.add(new ItemPet("Checkers"));
allPets.add(new ItemPet("Fluffy"));
allPets.add(new ItemPet("Mufty"));
this.tag.setItems(allPets);
this.tag.setItemValue("name");
this.tag.setItemLabel("label");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element spanElement1 = (Element) document.getRootElement().elements().get(0);
Element checkboxElement1 = (Element) spanElement1.elements().get(0);
assertEquals("input", checkboxElement1.getName());
assertEquals("checkbox", checkboxElement1.attribute("type").getValue());
assertEquals("pets", checkboxElement1.attribute("name").getValue());
assertEquals("checked", checkboxElement1.attribute("checked").getValue());
assertEquals("Rudiger", checkboxElement1.attribute("value").getValue());
assertEquals("RUDIGER", spanElement1.getStringValue());
Element spanElement2 = (Element) document.getRootElement().elements().get(1);
Element checkboxElement2 = (Element) spanElement2.elements().get(0);
assertEquals("input", checkboxElement2.getName());
assertEquals("checkbox", checkboxElement2.attribute("type").getValue());
assertEquals("pets", checkboxElement2.attribute("name").getValue());
assertEquals("checked", checkboxElement2.attribute("checked").getValue());
assertEquals("Spot", checkboxElement2.attribute("value").getValue());
assertEquals("SPOT", spanElement2.getStringValue());
Element spanElement3 = (Element) document.getRootElement().elements().get(2);
Element checkboxElement3 = (Element) spanElement3.elements().get(0);
assertEquals("input", checkboxElement3.getName());
assertEquals("checkbox", checkboxElement3.attribute("type").getValue());
assertEquals("pets", checkboxElement3.attribute("name").getValue());
assertNull("not checked", checkboxElement3.attribute("checked"));
assertEquals("Checkers", checkboxElement3.attribute("value").getValue());
assertEquals("CHECKERS", spanElement3.getStringValue());
Element spanElement4 = (Element) document.getRootElement().elements().get(3);
Element checkboxElement4 = (Element) spanElement4.elements().get(0);
assertEquals("input", checkboxElement4.getName());
assertEquals("checkbox", checkboxElement4.attribute("type").getValue());
assertEquals("pets", checkboxElement4.attribute("name").getValue());
assertEquals("checked", checkboxElement4.attribute("checked").getValue());
assertEquals("Fluffy", checkboxElement4.attribute("value").getValue());
assertEquals("FLUFFY", spanElement4.getStringValue());
Element spanElement5 = (Element) document.getRootElement().elements().get(4);
Element checkboxElement5 = (Element) spanElement5.elements().get(0);
assertEquals("input", checkboxElement5.getName());
assertEquals("checkbox", checkboxElement5.attribute("type").getValue());
assertEquals("pets", checkboxElement5.attribute("name").getValue());
assertEquals("checked", checkboxElement5.attribute("checked").getValue());
assertEquals("Mufty", checkboxElement5.attribute("value").getValue());
assertEquals("MUFTY", spanElement5.getStringValue());
}
/**
* Test case where items toString() doesn't fit the item ID
*/
public void testCollectionOfItemPets() throws Exception {
this.tag.setPath("someSet");
List allPets = new ArrayList();
allPets.add(new ItemPet("PET1"));
allPets.add(new ItemPet("PET2"));
allPets.add(new ItemPet("PET3"));
this.tag.setItems(allPets);
this.tag.setItemValue("name");
this.tag.setItemLabel("label");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element spanElement1 = (Element) document.getRootElement().elements().get(0);
Element checkboxElement1 = (Element) spanElement1.elements().get(0);
assertEquals("input", checkboxElement1.getName());
assertEquals("checkbox", checkboxElement1.attribute("type").getValue());
assertEquals("someSet", checkboxElement1.attribute("name").getValue());
assertNotNull("should be checked", checkboxElement1.attribute("checked"));
assertEquals("checked", checkboxElement1.attribute("checked").getValue());
assertEquals("PET1", checkboxElement1.attribute("value").getValue());
assertEquals("PET1", spanElement1.getStringValue());
Element spanElement2 = (Element) document.getRootElement().elements().get(1);
Element checkboxElement2 = (Element) spanElement2.elements().get(0);
assertEquals("input", checkboxElement2.getName());
assertEquals("checkbox", checkboxElement2.attribute("type").getValue());
assertEquals("someSet", checkboxElement2.attribute("name").getValue());
assertNotNull("should be checked", checkboxElement2.attribute("checked"));
assertEquals("checked", checkboxElement2.attribute("checked").getValue());
assertEquals("PET2", checkboxElement2.attribute("value").getValue());
assertEquals("PET2", spanElement2.getStringValue());
Element spanElement3 = (Element) document.getRootElement().elements().get(2);
Element checkboxElement3 = (Element) spanElement3.elements().get(0);
assertEquals("input", checkboxElement3.getName());
assertEquals("checkbox", checkboxElement3.attribute("type").getValue());
assertEquals("someSet", checkboxElement3.attribute("name").getValue());
assertNull("not checked", checkboxElement3.attribute("checked"));
assertEquals("PET3", checkboxElement3.attribute("value").getValue());
assertEquals("PET3", spanElement3.getStringValue());
}
public void testCollectionOfPetsWithEditor() throws Exception {
this.tag.setPath("pets");
List allPets = new ArrayList();
allPets.add(new ItemPet("Rudiger"));
allPets.add(new ItemPet("Spot"));
allPets.add(new ItemPet("Checkers"));
allPets.add(new ItemPet("Fluffy"));
allPets.add(new ItemPet("Mufty"));
this.tag.setItems(allPets);
this.tag.setItemLabel("label");
this.tag.setId("myId");
BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
PropertyEditorSupport editor = new ItemPet.CustomEditor();
bindingResult.getPropertyEditorRegistry().registerCustomEditor(ItemPet.class, editor);
getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, bindingResult);
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element spanElement1 = (Element) document.getRootElement().elements().get(0);
Element checkboxElement1 = (Element) spanElement1.elements().get(0);
assertEquals("input", checkboxElement1.getName());
assertEquals("checkbox", checkboxElement1.attribute("type").getValue());
assertEquals("pets", checkboxElement1.attribute("name").getValue());
assertEquals("checked", checkboxElement1.attribute("checked").getValue());
assertEquals("Rudiger", checkboxElement1.attribute("value").getValue());
assertEquals("RUDIGER", spanElement1.getStringValue());
Element spanElement2 = (Element) document.getRootElement().elements().get(1);
Element checkboxElement2 = (Element) spanElement2.elements().get(0);
assertEquals("input", checkboxElement2.getName());
assertEquals("checkbox", checkboxElement2.attribute("type").getValue());
assertEquals("pets", checkboxElement2.attribute("name").getValue());
assertEquals("checked", checkboxElement2.attribute("checked").getValue());
assertEquals("Spot", checkboxElement2.attribute("value").getValue());
assertEquals("SPOT", spanElement2.getStringValue());
Element spanElement3 = (Element) document.getRootElement().elements().get(2);
Element checkboxElement3 = (Element) spanElement3.elements().get(0);
assertEquals("input", checkboxElement3.getName());
assertEquals("checkbox", checkboxElement3.attribute("type").getValue());
assertEquals("pets", checkboxElement3.attribute("name").getValue());
assertNull("not checked", checkboxElement3.attribute("checked"));
assertEquals("Checkers", checkboxElement3.attribute("value").getValue());
assertEquals("CHECKERS", spanElement3.getStringValue());
Element spanElement4 = (Element) document.getRootElement().elements().get(3);
Element checkboxElement4 = (Element) spanElement4.elements().get(0);
assertEquals("input", checkboxElement4.getName());
assertEquals("checkbox", checkboxElement4.attribute("type").getValue());
assertEquals("pets", checkboxElement4.attribute("name").getValue());
assertEquals("checked", checkboxElement4.attribute("checked").getValue());
assertEquals("Fluffy", checkboxElement4.attribute("value").getValue());
assertEquals("FLUFFY", spanElement4.getStringValue());
Element spanElement5 = (Element) document.getRootElement().elements().get(4);
Element checkboxElement5 = (Element) spanElement5.elements().get(0);
assertEquals("input", checkboxElement5.getName());
assertEquals("checkbox", checkboxElement5.attribute("type").getValue());
assertEquals("pets", checkboxElement5.attribute("name").getValue());
assertEquals("checked", checkboxElement5.attribute("checked").getValue());
assertEquals("Mufty", checkboxElement5.attribute("value").getValue());
assertEquals("MUFTY", spanElement5.getStringValue());
}
public void testWithNullValue() throws Exception {
try {
this.tag.setPath("name");
this.tag.doStartTag();
fail("Should not be able to render with a null value when binding to a non-boolean.");
}
catch (IllegalArgumentException ex) {
// success
}
}
public void testHiddenElementOmittedOnDisabled() throws Exception {
this.tag.setPath("stringArray");
this.tag.setItems(new Object[] {"foo", "bar", "baz"});
this.tag.setDisabled("true");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element rootElement = document.getRootElement();
assertEquals("Both tag and hidden element rendered incorrectly", 3, rootElement.elements().size());
Element spanElement = (Element) document.getRootElement().elements().get(0);
Element checkboxElement = (Element) spanElement.elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("stringArray", checkboxElement.attribute("name").getValue());
assertEquals("checked", checkboxElement.attribute("checked").getValue());
assertEquals("disabled", checkboxElement.attribute("disabled").getValue());
assertEquals("foo", checkboxElement.attribute("value").getValue());
}
public void testSpanElementCustomizable() throws Exception {
this.tag.setPath("stringArray");
this.tag.setItems(new Object[] {"foo", "bar", "baz"});
this.tag.setElement("element");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element spanElement = (Element) document.getRootElement().elements().get(0);
assertEquals("element", spanElement.getName());
}
private Date getDate() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 10);
cal.set(Calendar.MONTH, 10);
cal.set(Calendar.DATE, 10);
cal.set(Calendar.HOUR, 10);
cal.set(Calendar.MINUTE, 10);
cal.set(Calendar.SECOND, 10);
return cal.getTime();
}
protected TestBean createTestBean() {
List colours = new ArrayList();
colours.add(Colour.BLUE);
colours.add(Colour.RED);
colours.add(Colour.GREEN);
List pets = new ArrayList();
pets.add(new Pet("Rudiger"));
pets.add(new Pet("Spot"));
pets.add(new Pet("Fluffy"));
pets.add(new Pet("Mufty"));
Set someObjects = new HashSet();
someObjects.add(new ItemPet("PET1"));
someObjects.add(new ItemPet("PET2"));
this.bean = new TestBean();
this.bean.setDate(getDate());
this.bean.setName("Rob Harrop");
this.bean.setJedi(true);
this.bean.setSomeBoolean(new Boolean(true));
this.bean.setStringArray(new String[] {"bar", "foo"});
this.bean.setSomeIntegerArray(new Integer[] {new Integer(2), new Integer(1)});
this.bean.setOtherColours(colours);
this.bean.setPets(pets);
this.bean.setSomeSet(someObjects);
List list = new ArrayList();
list.add("foo");
list.add("bar");
this.bean.setSomeList(list);
return this.bean;
}
private static class MyStringTrimmerEditor extends StringTrimmerEditor {
public final Set allProcessedValues = new HashSet();
public MyStringTrimmerEditor() {
super(false);
}
public void setAsText(String text) {
super.setAsText(text);
this.allProcessedValues.add(getValue());
}
}
private static class MyLowerCaseEditor extends PropertyEditorSupport {
public void setAsText(String text) throws IllegalArgumentException {
setValue(text.toLowerCase());
}
public String getAsText() {
return ObjectUtils.nullSafeToString(getValue()).toUpperCase();
}
}
}

View File

@@ -0,0 +1,86 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.tags.form;
import java.util.ArrayList;
import java.util.List;
/**
* @author Rob Harrop
* @author Sam Brannen
*/
public class Country {
public static final Country COUNTRY_AT = new Country("AT", "Austria");
public static final Country COUNTRY_NL = new Country("NL", "Netherlands");
public static final Country COUNTRY_UK = new Country("UK", "United Kingdom");
public static final Country COUNTRY_US = new Country("US", "United States");
private final String isoCode;
private final String name;
public Country(String isoCode, String name) {
this.isoCode = isoCode;
this.name = name;
}
public String getIsoCode() {
return this.isoCode;
}
public String getName() {
return this.name;
}
public String toString() {
return this.name + "(" + this.isoCode + ")";
}
public static Country getCountryWithIsoCode(final String isoCode) {
if (COUNTRY_AT.isoCode.equals(isoCode)) {
return COUNTRY_AT;
}
if (COUNTRY_NL.isoCode.equals(isoCode)) {
return COUNTRY_NL;
}
if (COUNTRY_UK.isoCode.equals(isoCode)) {
return COUNTRY_UK;
}
if (COUNTRY_US.isoCode.equals(isoCode)) {
return COUNTRY_US;
}
return null;
}
public static List getCountries() {
List countries = new ArrayList();
countries.add(COUNTRY_AT);
countries.add(COUNTRY_NL);
countries.add(COUNTRY_UK);
countries.add(COUNTRY_US);
return countries;
}
}

View File

@@ -0,0 +1,408 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.tags.form;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyTag;
import javax.servlet.jsp.tagext.Tag;
import org.springframework.beans.TestBean;
import org.springframework.mock.web.MockBodyContent;
import org.springframework.mock.web.MockPageContext;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.web.servlet.support.RequestContext;
import org.springframework.web.servlet.tags.RequestContextAwareTag;
/**
* @author Rob Harrop
* @author Rick Evans
* @author Juergen Hoeller
* @author Mark Fisher
*/
public class ErrorsTagTests extends AbstractFormTagTests {
private static final String COMMAND_NAME = "testBean";
private ErrorsTag tag;
protected void onSetUp() {
this.tag = new ErrorsTag() {
protected TagWriter createTagWriter() {
return new TagWriter(getWriter());
}
};
this.tag.setPath("name");
this.tag.setParent(getFormTag());
this.tag.setPageContext(getPageContext());
}
protected TestBean createTestBean() {
return new TestBean();
}
public void testWithExplicitNonWhitespaceBodyContent() throws Exception {
String mockContent = "This is some explicit body content";
this.tag.setBodyContent(new MockBodyContent(mockContent, getWriter()));
// construct an errors instance of the tag
TestBean target = new TestBean();
target.setName("Rob Harrop");
Errors errors = new BeanPropertyBindingResult(target, COMMAND_NAME);
errors.rejectValue("name", "some.code", "Default Message");
exposeBindingResult(errors);
int result = this.tag.doStartTag();
assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
assertEquals(mockContent, getOutput());
}
public void testWithExplicitWhitespaceBodyContent() throws Exception {
this.tag.setBodyContent(new MockBodyContent("\t\n ", getWriter()));
// construct an errors instance of the tag
TestBean target = new TestBean();
target.setName("Rob Harrop");
Errors errors = new BeanPropertyBindingResult(target, COMMAND_NAME);
errors.rejectValue("name", "some.code", "Default Message");
exposeBindingResult(errors);
int result = this.tag.doStartTag();
assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
assertElementTagOpened(output);
assertElementTagClosed(output);
assertContainsAttribute(output, "id", "name.errors");
assertBlockTagContains(output, "Default Message");
}
public void testWithExplicitEmptyWhitespaceBodyContent() throws Exception {
this.tag.setBodyContent(new MockBodyContent("", getWriter()));
// construct an errors instance of the tag
TestBean target = new TestBean();
target.setName("Rob Harrop");
Errors errors = new BeanPropertyBindingResult(target, COMMAND_NAME);
errors.rejectValue("name", "some.code", "Default Message");
exposeBindingResult(errors);
int result = this.tag.doStartTag();
assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
assertElementTagOpened(output);
assertElementTagClosed(output);
assertContainsAttribute(output, "id", "name.errors");
assertBlockTagContains(output, "Default Message");
}
public void testWithErrors() throws Exception {
// construct an errors instance of the tag
TestBean target = new TestBean();
target.setName("Rob Harrop");
Errors errors = new BeanPropertyBindingResult(target, COMMAND_NAME);
errors.rejectValue("name", "some.code", "Default Message");
errors.rejectValue("name", "too.short", "Too Short");
exposeBindingResult(errors);
int result = this.tag.doStartTag();
assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
assertElementTagOpened(output);
assertElementTagClosed(output);
assertContainsAttribute(output, "id", "name.errors");
assertBlockTagContains(output, "<br/>");
assertBlockTagContains(output, "Default Message");
assertBlockTagContains(output, "Too Short");
}
public void testWithEscapedErrors() throws Exception {
// construct an errors instance of the tag
TestBean target = new TestBean();
target.setName("Rob Harrop");
Errors errors = new BeanPropertyBindingResult(target, COMMAND_NAME);
errors.rejectValue("name", "some.code", "Default <> Message");
errors.rejectValue("name", "too.short", "Too & Short");
exposeBindingResult(errors);
int result = this.tag.doStartTag();
assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
assertElementTagOpened(output);
assertElementTagClosed(output);
assertContainsAttribute(output, "id", "name.errors");
assertBlockTagContains(output, "<br/>");
assertBlockTagContains(output, "Default &lt;&gt; Message");
assertBlockTagContains(output, "Too &amp; Short");
}
public void testWithNonEscapedErrors() throws Exception {
this.tag.setHtmlEscape("false");
// construct an errors instance of the tag
TestBean target = new TestBean();
target.setName("Rob Harrop");
Errors errors = new BeanPropertyBindingResult(target, COMMAND_NAME);
errors.rejectValue("name", "some.code", "Default <> Message");
errors.rejectValue("name", "too.short", "Too & Short");
exposeBindingResult(errors);
int result = this.tag.doStartTag();
assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
assertElementTagOpened(output);
assertElementTagClosed(output);
assertContainsAttribute(output, "id", "name.errors");
assertBlockTagContains(output, "<br/>");
assertBlockTagContains(output, "Default <> Message");
assertBlockTagContains(output, "Too & Short");
}
public void testWithErrorsAndCustomElement() throws Exception {
// construct an errors instance of the tag
TestBean target = new TestBean();
target.setName("Rob Harrop");
Errors errors = new BeanPropertyBindingResult(target, COMMAND_NAME);
errors.rejectValue("name", "some.code", "Default Message");
errors.rejectValue("name", "too.short", "Too Short");
exposeBindingResult(errors);
this.tag.setElement("div");
int result = this.tag.doStartTag();
assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
assertElementTagOpened(output);
assertElementTagClosed(output);
assertContainsAttribute(output, "id", "name.errors");
assertBlockTagContains(output, "<br/>");
assertBlockTagContains(output, "Default Message");
assertBlockTagContains(output, "Too Short");
}
public void testWithoutErrors() throws Exception {
Errors errors = new BeanPropertyBindingResult(new TestBean(), "COMMAND_NAME");
exposeBindingResult(errors);
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
assertEquals(0, output.length());
}
public void testWithoutErrorsInstance() throws Exception {
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
assertEquals(0, output.length());
}
public void testAsBodyTag() throws Exception {
Errors errors = new BeanPropertyBindingResult(new TestBean(), "COMMAND_NAME");
errors.rejectValue("name", "some.code", "Default Message");
errors.rejectValue("name", "too.short", "Too Short");
exposeBindingResult(errors);
int result = this.tag.doStartTag();
assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
assertNotNull(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE));
String bodyContent = "Foo";
this.tag.setBodyContent(new MockBodyContent(bodyContent, getWriter()));
this.tag.doEndTag();
this.tag.doFinally();
assertEquals(bodyContent, getOutput());
assertNull(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE));
}
public void testAsBodyTagWithExistingMessagesAttribute() throws Exception {
String existingAttribute = "something";
getPageContext().setAttribute(ErrorsTag.MESSAGES_ATTRIBUTE, existingAttribute);
Errors errors = new BeanPropertyBindingResult(new TestBean(), "COMMAND_NAME");
errors.rejectValue("name", "some.code", "Default Message");
errors.rejectValue("name", "too.short", "Too Short");
exposeBindingResult(errors);
int result = this.tag.doStartTag();
assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
assertNotNull(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE));
assertTrue(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE) instanceof List);
String bodyContent = "Foo";
this.tag.setBodyContent(new MockBodyContent(bodyContent, getWriter()));
this.tag.doEndTag();
this.tag.doFinally();
assertEquals(bodyContent, getOutput());
assertEquals(existingAttribute, getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE));
}
/**
* http://opensource.atlassian.com/projects/spring/browse/SPR-2788
*/
public void testAsBodyTagWithErrorsAndExistingMessagesAttributeInNonPageScopeAreNotClobbered() throws Exception {
String existingAttribute = "something";
getPageContext().setAttribute(ErrorsTag.MESSAGES_ATTRIBUTE, existingAttribute, PageContext.APPLICATION_SCOPE);
Errors errors = new BeanPropertyBindingResult(new TestBean(), "COMMAND_NAME");
errors.rejectValue("name", "some.code", "Default Message");
errors.rejectValue("name", "too.short", "Too Short");
exposeBindingResult(errors);
int result = this.tag.doStartTag();
assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
assertNotNull(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE));
assertTrue(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE) instanceof List);
String bodyContent = "Foo";
this.tag.setBodyContent(new MockBodyContent(bodyContent, getWriter()));
this.tag.doEndTag();
this.tag.doFinally();
assertEquals(bodyContent, getOutput());
assertEquals(existingAttribute,
getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE, PageContext.APPLICATION_SCOPE));
}
/**
* http://opensource.atlassian.com/projects/spring/browse/SPR-2788
*/
public void testAsBodyTagWithNoErrorsAndExistingMessagesAttributeInApplicationScopeAreNotClobbered() throws Exception {
assertWhenNoErrorsExistingMessagesInScopeAreNotClobbered(PageContext.APPLICATION_SCOPE);
}
/**
* http://opensource.atlassian.com/projects/spring/browse/SPR-2788
*/
public void testAsBodyTagWithNoErrorsAndExistingMessagesAttributeInSessionScopeAreNotClobbered() throws Exception {
assertWhenNoErrorsExistingMessagesInScopeAreNotClobbered(PageContext.SESSION_SCOPE);
}
/**
* http://opensource.atlassian.com/projects/spring/browse/SPR-2788
*/
public void testAsBodyTagWithNoErrorsAndExistingMessagesAttributeInPageScopeAreNotClobbered() throws Exception {
assertWhenNoErrorsExistingMessagesInScopeAreNotClobbered(PageContext.PAGE_SCOPE);
}
/**
* http://opensource.atlassian.com/projects/spring/browse/SPR-2788
*/
public void testAsBodyTagWithNoErrorsAndExistingMessagesAttributeInRequestScopeAreNotClobbered() throws Exception {
assertWhenNoErrorsExistingMessagesInScopeAreNotClobbered(PageContext.REQUEST_SCOPE);
}
/**
* http://opensource.atlassian.com/projects/spring/browse/SPR-4005
*/
public void testOmittedPathMatchesObjectErrorsOnly() throws Exception {
this.tag.setPath(null);
Errors errors = new BeanPropertyBindingResult(new TestBean(), "COMMAND_NAME");
errors.reject("some.code", "object error");
errors.rejectValue("name", "some.code", "field error");
exposeBindingResult(errors);
this.tag.doStartTag();
assertNotNull(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE));
this.tag.doEndTag();
String output = getOutput();
assertBlockTagContains(output, "object error");
assertFalse(output.indexOf("field error") != -1);
}
protected void exposeBindingResult(Errors errors) {
// wrap errors in a Model
Map model = new HashMap();
model.put(BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, errors);
// replace the request context with one containing the errors
MockPageContext pageContext = getPageContext();
RequestContext context = new RequestContext((HttpServletRequest) pageContext.getRequest(), model);
pageContext.setAttribute(RequestContextAwareTag.REQUEST_CONTEXT_PAGE_ATTRIBUTE, context);
}
private void assertElementTagOpened(String output) {
assertTrue(output.startsWith("<" + this.tag.getElement() + " "));
}
private void assertElementTagClosed(String output) {
assertTrue(output.endsWith("</" + this.tag.getElement() + ">"));
}
private void assertWhenNoErrorsExistingMessagesInScopeAreNotClobbered(int scope) throws JspException {
String existingAttribute = "something";
getPageContext().setAttribute(ErrorsTag.MESSAGES_ATTRIBUTE, existingAttribute, scope);
Errors errors = new BeanPropertyBindingResult(new TestBean(), "COMMAND_NAME");
exposeBindingResult(errors);
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
assertEquals(0, output.length());
assertEquals(existingAttribute, getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE, scope));
}
}

View File

@@ -0,0 +1,182 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.tags.form;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
import org.springframework.mock.web.MockHttpServletRequest;
/**
* @author Rob Harrop
* @author Rick Evans
* @author Juergen Hoeller
*/
public class FormTagTests extends AbstractHtmlElementTagTests {
private static final String REQUEST_URI = "/my/form";
private static final String QUERY_STRING = "foo=bar";
private FormTag tag;
private MockHttpServletRequest request;
protected void onSetUp() {
this.tag = new FormTag() {
protected TagWriter createTagWriter() {
return new TagWriter(getWriter());
}
};
this.tag.setPageContext(getPageContext());
}
protected void extendRequest(MockHttpServletRequest request) {
request.setRequestURI(REQUEST_URI);
request.setQueryString(QUERY_STRING);
this.request = request;
}
public void testWriteForm() throws Exception {
String commandName = "myCommand";
String name = "formName";
String action = "/form.html";
String method = "POST";
String target = "myTarget";
String enctype = "my/enctype";
String acceptCharset = "iso-8859-1";
String onsubmit = "onsubmit";
String onreset = "onreset";
String autocomplete = "off";
String cssClass = "myClass";
String cssStyle = "myStyle";
this.tag.setName(name);
this.tag.setCssClass(cssClass);
this.tag.setCssStyle(cssStyle);
this.tag.setCommandName(commandName);
this.tag.setAction(action);
this.tag.setMethod(method);
this.tag.setTarget(target);
this.tag.setEnctype(enctype);
this.tag.setAcceptCharset(acceptCharset);
this.tag.setOnsubmit(onsubmit);
this.tag.setOnreset(onreset);
this.tag.setAutocomplete(autocomplete);
int result = this.tag.doStartTag();
assertEquals(Tag.EVAL_BODY_INCLUDE, result);
assertEquals("Form attribute not exposed", commandName,
getPageContext().getRequest().getAttribute(FormTag.MODEL_ATTRIBUTE_VARIABLE_NAME));
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
this.tag.doFinally();
assertNull("Form attribute not cleared after tag ends",
getPageContext().getRequest().getAttribute(FormTag.MODEL_ATTRIBUTE_VARIABLE_NAME));
String output = getOutput();
assertFormTagOpened(output);
assertFormTagClosed(output);
assertContainsAttribute(output, "class", cssClass);
assertContainsAttribute(output, "style", cssStyle);
assertContainsAttribute(output, "action", action);
assertContainsAttribute(output, "method", method);
assertContainsAttribute(output, "target", target);
assertContainsAttribute(output, "enctype", enctype);
assertContainsAttribute(output, "accept-charset", acceptCharset);
assertContainsAttribute(output, "onsubmit", onsubmit);
assertContainsAttribute(output, "onreset", onreset);
assertContainsAttribute(output, "autocomplete", autocomplete);
assertContainsAttribute(output, "id", commandName);
assertContainsAttribute(output, "name", name);
}
public void testWithActionFromRequest() throws Exception {
String commandName = "myCommand";
String enctype = "my/enctype";
String method = "POST";
String onsubmit = "onsubmit";
String onreset = "onreset";
this.tag.setCommandName(commandName);
this.tag.setMethod(method);
this.tag.setEnctype(enctype);
this.tag.setOnsubmit(onsubmit);
this.tag.setOnreset(onreset);
int result = this.tag.doStartTag();
assertEquals(Tag.EVAL_BODY_INCLUDE, result);
assertEquals("Form attribute not exposed", commandName,
getPageContext().getAttribute(FormTag.MODEL_ATTRIBUTE_VARIABLE_NAME, PageContext.REQUEST_SCOPE));
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
this.tag.doFinally();
assertNull("Form attribute not cleared after tag ends",
getPageContext().getAttribute(FormTag.MODEL_ATTRIBUTE_VARIABLE_NAME, PageContext.REQUEST_SCOPE));
String output = getOutput();
assertFormTagOpened(output);
assertFormTagClosed(output);
assertContainsAttribute(output, "action", REQUEST_URI + "?" + QUERY_STRING);
assertContainsAttribute(output, "method", method);
assertContainsAttribute(output, "enctype", enctype);
assertContainsAttribute(output, "onsubmit", onsubmit);
assertContainsAttribute(output, "onreset", onreset);
assertAttributeNotPresent(output, "name");
}
public void testWithNullResolvedCommand() throws Exception {
try {
tag.setCommandName("${null}");
tag.doStartTag();
fail("Must not be able to have a command name that resolves to null");
}
catch (IllegalArgumentException ex) {
// expected
}
}
/*
* See http://opensource.atlassian.com/projects/spring/browse/SPR-2645
*/
public void testXSSScriptingExploitWhenActionIsResolvedFromQueryString() throws Exception {
String xssQueryString = QUERY_STRING + "&stuff=\"><script>alert('XSS!')</script>";
request.setQueryString(xssQueryString);
tag.doStartTag();
assertEquals("<form id=\"command\" action=\"/my/form?foo=bar&amp;stuff=&quot;&gt;&lt;script&gt;alert('XSS!')&lt;/script&gt;\" method=\"post\">",
getOutput());
}
private static void assertFormTagOpened(String output) {
assertTrue(output.startsWith("<form "));
}
private static void assertFormTagClosed(String output) {
assertTrue(output.endsWith("</form>"));
}
}

View File

@@ -0,0 +1,89 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.tags.form;
import org.springframework.beans.TestBean;
import org.springframework.validation.BeanPropertyBindingResult;
import javax.servlet.jsp.tagext.Tag;
/**
* @author Rob Harrop
*/
public class HiddenInputTagTests extends AbstractFormTagTests {
private HiddenInputTag tag;
private TestBean bean;
protected void onSetUp() {
this.tag = new HiddenInputTag() {
protected TagWriter createTagWriter() {
return new TagWriter(getWriter());
}
};
this.tag.setPageContext(getPageContext());
}
public void testRender() throws Exception {
this.tag.setPath("name");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
assertTagOpened(output);
assertTagClosed(output);
assertContainsAttribute(output, "type", "hidden");
assertContainsAttribute(output, "value", "Sally Greenwood");
}
public void testWithCustomBinder() throws Exception {
this.tag.setPath("myFloat");
BeanPropertyBindingResult errors = new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
errors.getPropertyAccessor().registerCustomEditor(Float.class, new SimpleFloatEditor());
exposeBindingResult(errors);
assertEquals(Tag.SKIP_BODY, this.tag.doStartTag());
String output = getOutput();
assertTagOpened(output);
assertTagClosed(output);
assertContainsAttribute(output, "type", "hidden");
assertContainsAttribute(output, "value", "12.34f");
}
private void assertTagClosed(String output) {
assertTrue(output.endsWith("/>"));
}
private void assertTagOpened(String output) {
assertTrue(output.startsWith("<input "));
}
protected TestBean createTestBean() {
this.bean = new TestBean();
bean.setName("Sally Greenwood");
bean.setMyFloat(new Float("12.34"));
return bean;
}
}

View File

@@ -0,0 +1,359 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.tags.form;
import java.io.Writer;
import javax.servlet.jsp.tagext.Tag;
import org.springframework.beans.TestBean;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.web.servlet.support.BindStatus;
import org.springframework.web.servlet.tags.BindTag;
import org.springframework.web.servlet.tags.NestedPathTag;
/**
* @author Rob Harrop
* @author Rick Evans
*/
public class InputTagTests extends AbstractFormTagTests {
private InputTag tag;
private TestBean rob;
protected void onSetUp() {
this.tag = createTag(getWriter());
this.tag.setParent(getFormTag());
this.tag.setPageContext(getPageContext());
}
protected TestBean createTestBean() {
// set up test data
this.rob = new TestBean();
this.rob.setName("Rob");
this.rob.setMyFloat(new Float(12.34));
TestBean sally = new TestBean();
sally.setName("Sally");
this.rob.setSpouse(sally);
return this.rob;
}
protected final InputTag getTag() {
return this.tag;
}
public void testSimpleBind() throws Exception {
this.tag.setPath("name");
assertEquals(Tag.SKIP_BODY, this.tag.doStartTag());
String output = getOutput();
assertTagOpened(output);
assertTagClosed(output);
assertContainsAttribute(output, "type", getType());
assertValueAttribute(output, "Rob");
}
public void testSimpleBindTagWithinForm() throws Exception {
BindTag bindTag = new BindTag();
bindTag.setPath("name");
bindTag.setPageContext(getPageContext());
bindTag.doStartTag();
BindStatus bindStatus = (BindStatus) getPageContext().findAttribute(BindTag.STATUS_VARIABLE_NAME);
assertEquals("Rob", bindStatus.getValue());
}
public void testSimpleBindWithHtmlEscaping() throws Exception {
final String NAME = "Rob \"I Love Mangos\" Harrop";
final String HTML_ESCAPED_NAME = "Rob &quot;I Love Mangos&quot; Harrop";
this.tag.setPath("name");
this.rob.setName(NAME);
assertEquals(Tag.SKIP_BODY, this.tag.doStartTag());
String output = getOutput();
assertTagOpened(output);
assertTagClosed(output);
assertContainsAttribute(output, "type", getType());
assertValueAttribute(output, HTML_ESCAPED_NAME);
}
protected void assertValueAttribute(String output, String expectedValue) {
assertContainsAttribute(output, "value", expectedValue);
}
public void testComplexBind() throws Exception {
this.tag.setPath("spouse.name");
assertEquals(Tag.SKIP_BODY, this.tag.doStartTag());
String output = getOutput();
assertTagOpened(output);
assertTagClosed(output);
assertContainsAttribute(output, "id", "spouse.name");
assertContainsAttribute(output, "name", "spouse.name");
assertContainsAttribute(output, "type", getType());
assertValueAttribute(output, "Sally");
}
public void testWithAllAttributes() throws Exception {
String title = "aTitle";
String id = "123";
String size = "12";
String cssClass = "textfield";
String cssStyle = "width:10px";
String lang = "en";
String dir = "ltr";
String tabindex = "2";
String disabled = "true";
String onclick = "doClick()";
String ondblclick = "doDblclick()";
String onkeydown = "doKeydown()";
String onkeypress = "doKeypress()";
String onkeyup = "doKeyup()";
String onmousedown = "doMouseDown()";
String onmousemove = "doMouseMove()";
String onmouseout = "doMouseOut()";
String onmouseover = "doMouseOver()";
String onmouseup = "doMouseUp()";
String onfocus = "doFocus()";
String onblur = "doBlur()";
String onchange = "doChange()";
String accesskey = "a";
String maxlength = "12";
String alt = "Some text";
String onselect = "doSelect()";
String readonly = "true";
String autocomplete = "off";
this.tag.setId(id);
this.tag.setPath("name");
this.tag.setSize(size);
this.tag.setCssClass(cssClass);
this.tag.setCssStyle(cssStyle);
this.tag.setTitle(title);
this.tag.setLang(lang);
this.tag.setDir(dir);
this.tag.setTabindex(tabindex);
this.tag.setDisabled(disabled);
this.tag.setOnclick(onclick);
this.tag.setOndblclick(ondblclick);
this.tag.setOnkeydown(onkeydown);
this.tag.setOnkeypress(onkeypress);
this.tag.setOnkeyup(onkeyup);
this.tag.setOnmousedown(onmousedown);
this.tag.setOnmousemove(onmousemove);
this.tag.setOnmouseout(onmouseout);
this.tag.setOnmouseover(onmouseover);
this.tag.setOnmouseup(onmouseup);
this.tag.setOnfocus(onfocus);
this.tag.setOnblur(onblur);
this.tag.setOnchange(onchange);
this.tag.setAccesskey(accesskey);
this.tag.setMaxlength(maxlength);
this.tag.setAlt(alt);
this.tag.setOnselect(onselect);
this.tag.setReadonly(readonly);
this.tag.setAutocomplete(autocomplete);
assertEquals(Tag.SKIP_BODY, this.tag.doStartTag());
String output = getOutput();
assertTagOpened(output);
assertTagClosed(output);
assertContainsAttribute(output, "type", getType());
assertContainsAttribute(output, "id", id);
assertValueAttribute(output, "Rob");
assertContainsAttribute(output, "size", size);
assertContainsAttribute(output, "class", cssClass);
assertContainsAttribute(output, "style", cssStyle);
assertContainsAttribute(output, "title", title);
assertContainsAttribute(output, "lang", lang);
assertContainsAttribute(output, "dir", dir);
assertContainsAttribute(output, "tabindex", tabindex);
assertContainsAttribute(output, "disabled", "disabled");
assertContainsAttribute(output, "onclick", onclick);
assertContainsAttribute(output, "ondblclick", ondblclick);
assertContainsAttribute(output, "onkeydown", onkeydown);
assertContainsAttribute(output, "onkeypress", onkeypress);
assertContainsAttribute(output, "onkeyup", onkeyup);
assertContainsAttribute(output, "onmousedown", onmousedown);
assertContainsAttribute(output, "onmousemove", onmousemove);
assertContainsAttribute(output, "onmouseout", onmouseout);
assertContainsAttribute(output, "onmouseover", onmouseover);
assertContainsAttribute(output, "onmouseup", onmouseup);
assertContainsAttribute(output, "onfocus", onfocus);
assertContainsAttribute(output, "onblur", onblur);
assertContainsAttribute(output, "onchange", onchange);
assertContainsAttribute(output, "accesskey", accesskey);
assertContainsAttribute(output, "maxlength", maxlength);
assertContainsAttribute(output, "alt", alt);
assertContainsAttribute(output, "onselect", onselect);
assertContainsAttribute(output, "readonly", "readonly");
assertContainsAttribute(output, "autocomplete", autocomplete);
}
public void testWithNestedBind() throws Exception {
NestedPathTag nestedPathTag = new NestedPathTag();
nestedPathTag.setPath("spouse.");
nestedPathTag.setPageContext(getPageContext());
nestedPathTag.doStartTag();
this.tag.setPath("name");
assertEquals(Tag.SKIP_BODY, this.tag.doStartTag());
String output = getOutput();
assertTagOpened(output);
assertTagClosed(output);
assertContainsAttribute(output, "type", getType());
assertValueAttribute(output, "Sally");
}
public void testWithNestedBindTagWithinForm() throws Exception {
NestedPathTag nestedPathTag = new NestedPathTag();
nestedPathTag.setPath("spouse.");
nestedPathTag.setPageContext(getPageContext());
nestedPathTag.doStartTag();
BindTag bindTag = new BindTag();
bindTag.setPath("name");
bindTag.setPageContext(getPageContext());
bindTag.doStartTag();
BindStatus bindStatus = (BindStatus) getPageContext().findAttribute(BindTag.STATUS_VARIABLE_NAME);
assertEquals("Sally", bindStatus.getValue());
}
public void testWithErrors() throws Exception {
this.tag.setPath("name");
this.tag.setCssClass("good");
this.tag.setCssErrorClass("bad");
BeanPropertyBindingResult errors = new BeanPropertyBindingResult(this.rob, COMMAND_NAME);
errors.rejectValue("name", "some.code", "Default Message");
errors.rejectValue("name", "too.short", "Too Short");
exposeBindingResult(errors);
assertEquals(Tag.SKIP_BODY, this.tag.doStartTag());
String output = getOutput();
assertTagOpened(output);
assertTagClosed(output);
assertContainsAttribute(output, "type", getType());
assertValueAttribute(output, "Rob");
assertContainsAttribute(output, "class", "bad");
}
public void testDisabledFalse() throws Exception {
this.tag.setPath("name");
this.tag.setDisabled("false");
this.tag.doStartTag();
String output = getOutput();
assertAttributeNotPresent(output, "disabled");
}
public void testWithCustomBinder() throws Exception {
this.tag.setPath("myFloat");
BeanPropertyBindingResult errors = new BeanPropertyBindingResult(this.rob, COMMAND_NAME);
errors.getPropertyAccessor().registerCustomEditor(Float.class, new SimpleFloatEditor());
exposeBindingResult(errors);
assertEquals(Tag.SKIP_BODY, this.tag.doStartTag());
String output = getOutput();
assertTagOpened(output);
assertTagClosed(output);
assertContainsAttribute(output, "type", getType());
assertValueAttribute(output, "12.34f");
}
/**
* See SPR-3127 (http://opensource.atlassian.com/projects/spring/browse/SPR-3127)
*/
public void testReadOnlyAttributeRenderingWhenReadonlyIsTrue() throws Exception {
this.tag.setPath("name");
this.tag.setReadonly("true");
assertEquals(Tag.SKIP_BODY, this.tag.doStartTag());
String output = getOutput();
assertTagOpened(output);
assertTagClosed(output);
assertContainsAttribute(output, "type", getType());
assertContainsAttribute(output, "readonly", "readonly");
assertValueAttribute(output, "Rob");
}
/**
* See SPR-3127 (http://opensource.atlassian.com/projects/spring/browse/SPR-3127)
*/
public void testReadOnlyAttributeRenderingWhenReadonlyIsFalse() throws Exception {
this.tag.setPath("name");
this.tag.setReadonly("nope, this is not readonly");
assertEquals(Tag.SKIP_BODY, this.tag.doStartTag());
String output = getOutput();
assertTagOpened(output);
assertTagClosed(output);
assertContainsAttribute(output, "type", getType());
assertAttributeNotPresent(output, "readonly");
assertValueAttribute(output, "Rob");
}
protected final void assertTagClosed(String output) {
assertTrue("Tag not closed properly", output.endsWith("/>"));
}
protected final void assertTagOpened(String output) {
assertTrue("Tag not opened properly", output.startsWith("<input "));
}
protected InputTag createTag(final Writer writer) {
return new InputTag() {
protected TagWriter createTagWriter() {
return new TagWriter(writer);
}
};
}
protected String getType() {
return "text";
}
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.tags.form;
import java.beans.PropertyEditorSupport;
/**
* @author Juergen Hoeller
*/
public class ItemPet {
private String name;
public ItemPet(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLabel() {
return this.name.toUpperCase();
}
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof ItemPet)) {
return false;
}
ItemPet otherPet = (ItemPet) other;
return (this.name != null && this.name.equals(otherPet.getName()));
}
public int hashCode() {
return this.name.hashCode();
}
public static class CustomEditor extends PropertyEditorSupport {
public void setAsText(String text) throws IllegalArgumentException {
setValue(new ItemPet(text));
}
public String getAsText() {
return ((ItemPet) getValue()).getName();
}
}
}

View File

@@ -0,0 +1,119 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.tags.form;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.Tag;
import org.springframework.beans.TestBean;
import org.springframework.mock.web.MockPageContext;
import org.springframework.web.servlet.tags.NestedPathTag;
/**
* @author Rob Harrop
* @author Rick Evans
* @author Juergen Hoeller
*/
public class LabelTagTests extends AbstractFormTagTests {
private LabelTag tag;
protected void onSetUp() {
this.tag = new LabelTag() {
protected TagWriter createTagWriter() {
return new TagWriter(getWriter());
}
};
this.tag.setPageContext(getPageContext());
}
protected void extendPageContext(MockPageContext pageContext) throws JspException {
super.extendPageContext(pageContext);
NestedPathTag nestedPathTag = new NestedPathTag();
nestedPathTag.setPath("spouse.");
nestedPathTag.setPageContext(pageContext);
nestedPathTag.doStartTag();
}
public void testSimpleRender() throws Exception {
this.tag.setPath("name");
int startResult = this.tag.doStartTag();
int endResult = this.tag.doEndTag();
assertEquals(Tag.EVAL_BODY_INCLUDE, startResult);
assertEquals(Tag.EVAL_PAGE, endResult);
String output = getOutput();
// we are using a nexted path (see extendPageContext(..)), so...
assertContainsAttribute(output, "for", "spouse.name");
// name attribute is not supported by <label/>
assertAttributeNotPresent(output, "name");
// id attribute is supported, but we don't want it
assertAttributeNotPresent(output, "id");
assertTrue(output.startsWith("<label "));
assertTrue(output.endsWith("</label>"));
}
public void testSimpleRenderWithMapElement() throws Exception {
this.tag.setPath("someMap[1]");
int startResult = this.tag.doStartTag();
int endResult = this.tag.doEndTag();
assertEquals(Tag.EVAL_BODY_INCLUDE, startResult);
assertEquals(Tag.EVAL_PAGE, endResult);
String output = getOutput();
// we are using a nexted path (see extendPageContext(..)), so...
assertContainsAttribute(output, "for", "spouse.someMap1");
// name attribute is not supported by <label/>
assertAttributeNotPresent(output, "name");
// id attribute is supported, but we don't want it
assertAttributeNotPresent(output, "id");
assertTrue(output.startsWith("<label "));
assertTrue(output.endsWith("</label>"));
}
public void testOverrideFor() throws Exception {
this.tag.setPath("name");
this.tag.setFor("myElement");
int startResult = this.tag.doStartTag();
int endResult = this.tag.doEndTag();
assertEquals(Tag.EVAL_BODY_INCLUDE, startResult);
assertEquals(Tag.EVAL_PAGE, endResult);
String output = getOutput();
assertContainsAttribute(output, "for", "myElement");
// name attribute is not supported by <label/>
assertAttributeNotPresent(output, "name");
// id attribute is supported, but we don't want it
assertAttributeNotPresent(output, "id");
assertTrue(output.startsWith("<label "));
assertTrue(output.endsWith("</label>"));
}
protected TestBean createTestBean() {
TestBean bean = new TestBean();
bean.setSpouse(new TestBean("Hoopy"));
return bean;
}
}

View File

@@ -0,0 +1,72 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.tags.form;
import javax.servlet.jsp.tagext.BodyTag;
import javax.servlet.jsp.tagext.Tag;
import org.springframework.beans.CustomEnum;
import org.springframework.beans.GenericBean;
import org.springframework.web.servlet.support.BindStatus;
/**
* @author Juergen Hoeller
*/
public class OptionTagEnumTests extends AbstractHtmlElementTagTests {
private OptionTag tag;
protected void onSetUp() {
this.tag = new OptionTag() {
protected TagWriter createTagWriter() {
return new TagWriter(getWriter());
}
};
this.tag.setParent(new SelectTag());
this.tag.setPageContext(getPageContext());
}
public void testWithJavaEnum() throws Exception {
GenericBean testBean = new GenericBean();
testBean.setCustomEnum(CustomEnum.VALUE_1);
getPageContext().getRequest().setAttribute("testBean", testBean);
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, new BindStatus(getRequestContext(), "testBean.customEnum", false));
this.tag.setValue("VALUE_1");
int result = this.tag.doStartTag();
assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
String output = getWriter().toString();
assertOptionTagOpened(output);
assertOptionTagClosed(output);
assertContainsAttribute(output, "value", "VALUE_1");
assertContainsAttribute(output, "selected", "selected");
}
private void assertOptionTagOpened(String output) {
assertTrue(output.startsWith("<option"));
}
private void assertOptionTagClosed(String output) {
assertTrue(output.endsWith("</option>"));
}
}

View File

@@ -0,0 +1,562 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.tags.form;
import java.beans.PropertyEditor;
import java.beans.PropertyEditorSupport;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.jsp.tagext.BodyTag;
import javax.servlet.jsp.tagext.Tag;
import org.springframework.beans.Colour;
import org.springframework.beans.TestBean;
import org.springframework.beans.propertyeditors.StringArrayPropertyEditor;
import org.springframework.mock.web.MockBodyContent;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.util.StringUtils;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.web.servlet.support.BindStatus;
/**
* @author Rob Harrop
* @author Juergen Hoeller
* @author Rick Evans
*/
public class OptionTagTests extends AbstractHtmlElementTagTests {
private static final String ARRAY_SOURCE = "abc,123,def";
private static final String[] ARRAY = StringUtils.commaDelimitedListToStringArray(ARRAY_SOURCE);
private OptionTag tag;
protected void onSetUp() {
this.tag = new OptionTag() {
protected TagWriter createTagWriter() {
return new TagWriter(getWriter());
}
};
this.tag.setParent(new SelectTag());
this.tag.setPageContext(getPageContext());
}
public void testCanBeDisabledEvenWhenSelected() throws Exception {
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, new BindStatus(getRequestContext(), "testBean.name", false));
this.tag.setValue("bar");
this.tag.setLabel("Bar");
this.tag.setDisabled("true");
int result = this.tag.doStartTag();
assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
assertOptionTagOpened(output);
assertOptionTagClosed(output);
assertContainsAttribute(output, "value", "bar");
assertContainsAttribute(output, "disabled", "disabled");
assertBlockTagContains(output, "Bar");
}
public void testRenderNotSelected() throws Exception {
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, new BindStatus(getRequestContext(), "testBean.name", false));
this.tag.setValue("bar");
this.tag.setLabel("Bar");
int result = this.tag.doStartTag();
assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
assertOptionTagOpened(output);
assertOptionTagClosed(output);
assertContainsAttribute(output, "value", "bar");
assertBlockTagContains(output, "Bar");
}
public void testRenderSelected() throws Exception {
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, new BindStatus(getRequestContext(), "testBean.name", false));
this.tag.setId("myOption");
this.tag.setValue("foo");
this.tag.setLabel("Foo");
int result = this.tag.doStartTag();
assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
assertOptionTagOpened(output);
assertOptionTagClosed(output);
assertContainsAttribute(output, "id", "myOption");
assertContainsAttribute(output, "value", "foo");
assertContainsAttribute(output, "selected", "selected");
assertBlockTagContains(output, "Foo");
}
public void testWithNoLabel() throws Exception {
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, new BindStatus(getRequestContext(), "testBean.name", false));
this.tag.setValue("bar");
this.tag.setCssClass("myClass");
this.tag.setOnclick("CLICK");
int result = this.tag.doStartTag();
assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
assertOptionTagOpened(output);
assertOptionTagClosed(output);
assertContainsAttribute(output, "value", "bar");
assertContainsAttribute(output, "class", "myClass");
assertContainsAttribute(output, "onclick", "CLICK");
assertBlockTagContains(output, "bar");
}
public void testWithoutContext() throws Exception {
this.tag.setParent(null);
this.tag.setValue("foo");
this.tag.setLabel("Foo");
try {
tag.doStartTag();
fail("Must not be able to use <option> tag without exposed context.");
} catch (IllegalStateException ex) {
// expected
}
}
public void testWithEnum() throws Exception {
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, new BindStatus(getRequestContext(), "testBean.favouriteColour", false));
String value = Colour.GREEN.getCode().toString();
String label = Colour.GREEN.getLabel();
this.tag.setValue(value);
this.tag.setLabel(label);
int result = this.tag.doStartTag();
assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
assertOptionTagOpened(output);
assertOptionTagClosed(output);
assertContainsAttribute(output, "value", value);
assertContainsAttribute(output, "selected", "selected");
assertBlockTagContains(output, label);
}
public void testWithEnumNotSelected() throws Exception {
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, new BindStatus(getRequestContext(), "testBean.favouriteColour", false));
String value = Colour.BLUE.getCode().toString();
String label = Colour.BLUE.getLabel();
this.tag.setValue(value);
this.tag.setLabel(label);
int result = this.tag.doStartTag();
assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
assertOptionTagOpened(output);
assertOptionTagClosed(output);
assertContainsAttribute(output, "value", value);
assertAttributeNotPresent(output, "selected");
assertBlockTagContains(output, label);
}
public void testWithPropertyEditor() throws Exception {
BindStatus bindStatus = new BindStatus(getRequestContext(), "testBean.stringArray", false) {
public PropertyEditor getEditor() {
return new StringArrayPropertyEditor();
}
};
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus);
this.tag.setValue(ARRAY_SOURCE);
this.tag.setLabel("someArray");
int result = this.tag.doStartTag();
assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
assertOptionTagOpened(output);
assertOptionTagClosed(output);
assertContainsAttribute(output, "value", ARRAY_SOURCE);
assertContainsAttribute(output, "selected", "selected");
assertBlockTagContains(output, "someArray");
}
public void testWithPropertyEditorStringComparison() throws Exception {
final PropertyEditor testBeanEditor = new TestBeanPropertyEditor();
testBeanEditor.setValue(new TestBean("Sally"));
BindStatus bindStatus = new BindStatus(getRequestContext(), "testBean.spouse", false) {
public PropertyEditor getEditor() {
return testBeanEditor;
}
};
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus);
this.tag.setValue("Sally");
int result = this.tag.doStartTag();
assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
assertOptionTagOpened(output);
assertOptionTagClosed(output);
assertContainsAttribute(output, "value", "Sally");
assertContainsAttribute(output, "selected", "selected");
assertBlockTagContains(output, "Sally");
}
public void testWithCustomObjectSelected() throws Exception {
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, new BindStatus(getRequestContext(), "testBean.someNumber", false));
this.tag.setValue("${myNumber}");
this.tag.setLabel("GBP ${myNumber}");
int result = this.tag.doStartTag();
assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
assertOptionTagOpened(output);
assertOptionTagClosed(output);
assertContainsAttribute(output, "value", "12.34");
assertContainsAttribute(output, "selected", "selected");
assertBlockTagContains(output, "GBP 12.34");
}
public void testWithCustomObjectNotSelected() throws Exception {
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, new BindStatus(getRequestContext(), "testBean.someNumber", false));
this.tag.setValue("${myOtherNumber}");
this.tag.setLabel("GBP ${myOtherNumber}");
int result = this.tag.doStartTag();
assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
assertOptionTagOpened(output);
assertOptionTagClosed(output);
assertContainsAttribute(output, "value", "12.35");
assertAttributeNotPresent(output, "selected");
assertBlockTagContains(output, "GBP 12.35");
}
public void testWithCustomObjectAndEditorSelected() throws Exception {
final PropertyEditor floatEditor = new SimpleFloatEditor();
floatEditor.setValue(new Float("12.34"));
BindStatus bindStatus = new BindStatus(getRequestContext(), "testBean.someNumber", false) {
public PropertyEditor getEditor() {
return floatEditor;
}
};
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus);
this.tag.setValue("${myNumber}");
this.tag.setLabel("${myNumber}");
int result = this.tag.doStartTag();
assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
assertOptionTagOpened(output);
assertOptionTagClosed(output);
assertContainsAttribute(output, "selected", "selected");
assertBlockTagContains(output, "12.34f");
}
public void testWithCustomObjectAndEditorNotSelected() throws Exception {
final PropertyEditor floatEditor = new SimpleFloatEditor();
BindStatus bindStatus = new BindStatus(getRequestContext(), "testBean.someNumber", false) {
public PropertyEditor getEditor() {
return floatEditor;
}
};
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus);
this.tag.setValue("${myOtherNumber}");
this.tag.setLabel("${myOtherNumber}");
int result = this.tag.doStartTag();
assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
assertOptionTagOpened(output);
assertOptionTagClosed(output);
assertAttributeNotPresent(output, "selected");
assertBlockTagContains(output, "12.35f");
}
public void testAsBodyTag() throws Exception {
BindStatus bindStatus = new BindStatus(getRequestContext(), "testBean.name", false);
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus);
String bodyContent = "some content";
this.tag.setValue("foo");
int result = this.tag.doStartTag();
assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
this.tag.setBodyContent(new MockBodyContent(bodyContent, getWriter()));
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
assertOptionTagOpened(output);
assertOptionTagClosed(output);
assertContainsAttribute(output, "selected", "selected");
assertBlockTagContains(output, bodyContent);
}
public void testAsBodyTagSelected() throws Exception {
BindStatus bindStatus = new BindStatus(getRequestContext(), "testBean.name", false);
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus);
String bodyContent = "some content";
this.tag.setValue("Rob Harrop");
int result = this.tag.doStartTag();
assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
this.tag.setBodyContent(new MockBodyContent(bodyContent, getWriter()));
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
assertOptionTagOpened(output);
assertOptionTagClosed(output);
assertBlockTagContains(output, bodyContent);
}
public void testAsBodyTagCollapsed() throws Exception {
BindStatus bindStatus = new BindStatus(getRequestContext(), "testBean.name", false);
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus);
String bodyContent = "some content";
this.tag.setValue(bodyContent);
int result = this.tag.doStartTag();
assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
this.tag.setBodyContent(new MockBodyContent(bodyContent, getWriter()));
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
String output = getOutput();
assertOptionTagOpened(output);
assertOptionTagClosed(output);
assertContainsAttribute(output, "value", bodyContent);
assertBlockTagContains(output, bodyContent);
}
public void testAsBodyTagWithEditor() throws Exception {
BindStatus bindStatus = new BindStatus(getRequestContext(), "testBean.stringArray", false) {
public PropertyEditor getEditor() {
return new RulesVariantEditor();
}
};
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus);
RulesVariant rulesVariant = new RulesVariant("someRules", "someVariant");
getPageContext().getRequest().setAttribute("rule", rulesVariant);
this.tag.setValue("${rule}");
int result = this.tag.doStartTag();
assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
assertEquals(rulesVariant, getPageContext().getAttribute("value"));
assertEquals(rulesVariant.toId(), getPageContext().getAttribute("displayValue"));
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
}
public void testMultiBind() throws Exception {
BeanPropertyBindingResult result = new BeanPropertyBindingResult(new TestBean(), "testBean");
result.getPropertyAccessor().registerCustomEditor(TestBean.class, "friends", new FriendEditor());
exposeBindingResult(result);
BindStatus bindStatus = new BindStatus(getRequestContext(), "testBean.friends", false);
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus);
this.tag.setValue(new TestBean("foo"));
this.tag.doStartTag();
this.tag.doEndTag();
assertEquals("<option value=\"foo\">foo</option>", getOutput());
}
public void testOptionTagNotNestedWithinSelectTag() throws Exception {
try {
tag.setParent(null);
tag.setValue("foo");
tag.doStartTag();
fail("Must throw an IllegalStateException when not nested within a <select/> tag.");
} catch (IllegalStateException ex) {
// expected
}
}
private void assertOptionTagOpened(String output) {
assertTrue(output.startsWith("<option"));
}
private void assertOptionTagClosed(String output) {
assertTrue(output.endsWith("</option>"));
}
protected void extendRequest(MockHttpServletRequest request) {
TestBean bean = new TestBean();
bean.setName("foo");
bean.setFavouriteColour(Colour.GREEN);
bean.setStringArray(ARRAY);
bean.setSpouse(new TestBean("Sally"));
bean.setSomeNumber(new Float("12.34"));
List friends = new ArrayList();
friends.add(new TestBean("bar"));
friends.add(new TestBean("penc"));
bean.setFriends(friends);
request.setAttribute("testBean", bean);
request.setAttribute("myNumber", new Float(12.34));
request.setAttribute("myOtherNumber", new Float(12.35));
}
private static class TestBeanPropertyEditor extends PropertyEditorSupport {
public void setAsText(String text) throws IllegalArgumentException {
setValue(new TestBean(text + "k", 123));
}
public String getAsText() {
return ((TestBean) getValue()).getName();
}
}
public static class RulesVariant implements Serializable {
private String rules;
private String variant;
public RulesVariant(String rules, String variant) {
this.setRules(rules);
this.setVariant(variant);
}
private void setRules(String rules) {
this.rules = rules;
}
public String getRules() {
return rules;
}
private void setVariant(String variant) {
this.variant = variant;
}
public String getVariant() {
return variant;
}
public String toId() {
if (this.variant != null) {
return this.rules + "-" + this.variant;
} else {
return rules;
}
}
public static RulesVariant fromId(String id) {
String[] s = id.split("-", 2);
String rules = s[0];
String variant = s.length > 1 ? s[1] : null;
return new RulesVariant(rules, variant);
}
public boolean equals(Object obj) {
if (obj instanceof RulesVariant) {
RulesVariant other = (RulesVariant) obj;
return this.toId().equals(other.toId());
}
return false;
}
public int hashCode() {
return this.toId().hashCode();
}
}
public class RulesVariantEditor extends PropertyEditorSupport {
public void setAsText(String text) throws IllegalArgumentException {
setValue(RulesVariant.fromId(text));
}
public String getAsText() {
RulesVariant rulesVariant = (RulesVariant) getValue();
return rulesVariant.toId();
}
}
private static class FriendEditor extends PropertyEditorSupport {
public void setAsText(String text) throws IllegalArgumentException {
setValue(new TestBean(text));
}
public String getAsText() {
return ((TestBean) getValue()).getName();
}
}
}

View File

@@ -0,0 +1,199 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.tags.form;
import java.beans.PropertyEditor;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.tagext.Tag;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.TestBean;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockPageContext;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.web.servlet.support.BindStatus;
import org.springframework.web.servlet.support.RequestContext;
import org.springframework.web.servlet.tags.RequestContextAwareTag;
/**
* @author Rob Harrop
* @author Juergen Hoeller
*/
public class OptionsTagTests extends AbstractHtmlElementTagTests {
private static final String COMMAND_NAME = "testBean";
private OptionsTag tag;
protected void onSetUp() {
this.tag = new OptionsTag() {
protected TagWriter createTagWriter() {
return new TagWriter(getWriter());
}
};
this.tag.setParent(new SelectTag());
this.tag.setPageContext(getPageContext());
}
public void testWithCollection() throws Exception {
getPageContext().setAttribute(
SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, new BindStatus(getRequestContext(), "testBean.country", false));
this.tag.setItems("${countries}");
this.tag.setItemValue("isoCode");
this.tag.setItemLabel("name");
this.tag.setId("myOption");
this.tag.setCssClass("myClass");
this.tag.setOnclick("CLICK");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element rootElement = document.getRootElement();
List children = rootElement.elements();
assertEquals("Incorrect number of children", 4, children.size());
Element element = (Element) rootElement.selectSingleNode("option[@value = 'UK']");
assertEquals("UK node not selected", "selected", element.attribute("selected").getValue());
assertEquals("myOption3", element.attribute("id").getValue());
assertEquals("myClass", element.attribute("class").getValue());
assertEquals("CLICK", element.attribute("onclick").getValue());
}
public void testWithCollectionAndCustomEditor() throws Exception {
PropertyEditor propertyEditor = new SimpleFloatEditor();
TestBean target = new TestBean();
target.setMyFloat(new Float("12.34"));
BeanPropertyBindingResult errors = new BeanPropertyBindingResult(target, COMMAND_NAME);
errors.getPropertyAccessor().registerCustomEditor(Float.class, propertyEditor);
exposeBindingResult(errors);
getPageContext().setAttribute(
SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, new BindStatus(getRequestContext(), "testBean.myFloat", false));
this.tag.setItems("${floats}");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element rootElement = document.getRootElement();
List children = rootElement.elements();
assertEquals("Incorrect number of children", 6, children.size());
Element element = (Element) rootElement.selectSingleNode("option[text() = '12.34f']");
assertNotNull("Option node should not be null", element);
assertEquals("12.34 node not selected", "selected", element.attribute("selected").getValue());
assertNull("No id rendered", element.attribute("id"));
element = (Element) rootElement.selectSingleNode("option[text() = '12.35f']");
assertNotNull("Option node should not be null", element);
assertNull("12.35 node incorrectly selected", element.attribute("selected"));
assertNull("No id rendered", element.attribute("id"));
}
public void testWithItemsNullReference() throws Exception {
getPageContext().getRequest().removeAttribute("countries");
getPageContext().setAttribute(
SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, new BindStatus(getRequestContext(), "testBean.country", false));
this.tag.setItems("${countries}");
this.tag.setItemValue("isoCode");
this.tag.setItemLabel("name");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element rootElement = document.getRootElement();
List children = rootElement.elements();
assertEquals("Incorrect number of children", 0, children.size());
}
public void testWithoutItems() throws Exception {
getPageContext().setAttribute(
SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, new BindStatus(getRequestContext(), "testBean.country", false));
this.tag.setItemValue("isoCode");
this.tag.setItemLabel("name");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element rootElement = document.getRootElement();
List children = rootElement.elements();
assertEquals("Incorrect number of children", 0, children.size());
}
protected void extendRequest(MockHttpServletRequest request) {
TestBean bean = new TestBean();
bean.setName("foo");
bean.setCountry("UK");
bean.setMyFloat(new Float("12.34"));
request.setAttribute(COMMAND_NAME, bean);
request.setAttribute("countries", Country.getCountries());
List floats = new ArrayList();
floats.add(new Float("12.30"));
floats.add(new Float("12.31"));
floats.add(new Float("12.32"));
floats.add(new Float("12.33"));
floats.add(new Float("12.34"));
floats.add(new Float("12.35"));
request.setAttribute("floats", floats);
}
protected void exposeBindingResult(Errors errors) {
// wrap errors in a Model
Map model = new HashMap();
model.put(BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, errors);
// replace the request context with one containing the errors
MockPageContext pageContext = getPageContext();
RequestContext context = new RequestContext((HttpServletRequest) pageContext.getRequest(), model);
pageContext.setAttribute(RequestContextAwareTag.REQUEST_CONTEXT_PAGE_ATTRIBUTE, context);
}
}

View File

@@ -0,0 +1,103 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.tags.form;
import java.io.Writer;
import javax.servlet.jsp.tagext.Tag;
/**
* @author Rob Harrop
* @author Rick Evans
*/
public class PasswordInputTagTests extends InputTagTests {
/*
* http://opensource.atlassian.com/projects/spring/browse/SPR-2866
*/
public void testPasswordValueIsNotRenderedByDefault() throws Exception {
this.getTag().setPath("name");
assertEquals(Tag.SKIP_BODY, this.getTag().doStartTag());
String output = getOutput();
assertTagOpened(output);
assertTagClosed(output);
assertContainsAttribute(output, "type", getType());
assertValueAttribute(output, "");
}
/*
* http://opensource.atlassian.com/projects/spring/browse/SPR-2866
*/
public void testPasswordValueIsRenderedIfShowPasswordAttributeIsSetToTrue() throws Exception {
this.getTag().setPath("name");
this.getPasswordTag().setShowPassword(true);
assertEquals(Tag.SKIP_BODY, this.getTag().doStartTag());
String output = getOutput();
assertTagOpened(output);
assertTagClosed(output);
assertContainsAttribute(output, "type", getType());
assertValueAttribute(output, "Rob");
}
/*
* http://opensource.atlassian.com/projects/spring/browse/SPR-2866
*/
public void testPasswordValueIsNotRenderedIfShowPasswordAttributeIsSetToFalse() throws Exception {
this.getTag().setPath("name");
this.getPasswordTag().setShowPassword(false);
assertEquals(Tag.SKIP_BODY, this.getTag().doStartTag());
String output = getOutput();
assertTagOpened(output);
assertTagClosed(output);
assertContainsAttribute(output, "type", getType());
assertValueAttribute(output, "");
}
protected void assertValueAttribute(String output, String expectedValue) {
if (this.getPasswordTag().isShowPassword()) {
super.assertValueAttribute(output, expectedValue);
} else {
super.assertValueAttribute(output, "");
}
}
protected String getType() {
return "password";
}
protected InputTag createTag(final Writer writer) {
return new PasswordInputTag() {
protected TagWriter createTagWriter() {
return new TagWriter(writer);
}
};
}
private PasswordInputTag getPasswordTag() {
return (PasswordInputTag) this.getTag();
}
}

View File

@@ -0,0 +1,238 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.tags.form;
import java.beans.PropertyEditorSupport;
import java.io.StringReader;
import java.util.Collections;
import javax.servlet.jsp.tagext.Tag;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.Pet;
import org.springframework.beans.TestBean;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
/**
* @author Rob Harrop
* @author Juergen Hoeller
*/
public class RadioButtonTagTests extends AbstractFormTagTests {
private RadioButtonTag tag;
private TestBean bean;
protected void onSetUp() {
this.tag = new RadioButtonTag() {
protected TagWriter createTagWriter() {
return new TagWriter(getWriter());
}
};
this.tag.setPageContext(getPageContext());
}
public void testWithCheckedValue() throws Exception {
this.tag.setPath("sex");
this.tag.setValue("M");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
assertTagOpened(output);
assertTagClosed(output);
assertContainsAttribute(output, "name", "sex");
assertContainsAttribute(output, "type", "radio");
assertContainsAttribute(output, "value", "M");
assertContainsAttribute(output, "checked", "checked");
}
public void testWithCheckedObjectValue() throws Exception {
this.tag.setPath("myFloat");
this.tag.setValue(getFloat());
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
assertTagOpened(output);
assertTagClosed(output);
assertContainsAttribute(output, "name", "myFloat");
assertContainsAttribute(output, "type", "radio");
assertContainsAttribute(output, "value", getFloat().toString());
assertContainsAttribute(output, "checked", "checked");
}
public void testWithCheckedObjectValueAndEditor() throws Exception {
this.tag.setPath("myFloat");
this.tag.setValue("F12.99");
BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
MyFloatEditor editor = new MyFloatEditor();
bindingResult.getPropertyEditorRegistry().registerCustomEditor(Float.class, editor);
getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, bindingResult);
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
assertTagOpened(output);
assertTagClosed(output);
assertContainsAttribute(output, "name", "myFloat");
assertContainsAttribute(output, "type", "radio");
assertContainsAttribute(output, "value", "F" + getFloat().toString());
assertContainsAttribute(output, "checked", "checked");
}
public void testWithUncheckedObjectValue() throws Exception {
Float value = new Float("99.45");
this.tag.setPath("myFloat");
this.tag.setValue(value);
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
assertTagOpened(output);
assertTagClosed(output);
assertContainsAttribute(output, "name", "myFloat");
assertContainsAttribute(output, "type", "radio");
assertContainsAttribute(output, "value", value.toString());
assertAttributeNotPresent(output, "checked");
}
public void testWithUncheckedValue() throws Exception {
this.tag.setPath("sex");
this.tag.setValue("F");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
assertTagOpened(output);
assertTagClosed(output);
assertContainsAttribute(output, "name", "sex");
assertContainsAttribute(output, "type", "radio");
assertContainsAttribute(output, "value", "F");
assertAttributeNotPresent(output, "checked");
}
public void testCollectionOfPets() throws Exception {
this.tag.setPath("pets");
this.tag.setValue(new Pet("Rudiger"));
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element checkboxElement = (Element) document.getRootElement().elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("radio", checkboxElement.attribute("type").getValue());
assertEquals("pets", checkboxElement.attribute("name").getValue());
assertEquals("Rudiger", checkboxElement.attribute("value").getValue());
assertEquals("checked", checkboxElement.attribute("checked").getValue());
}
public void testCollectionOfPetsNotSelected() throws Exception {
this.tag.setPath("pets");
this.tag.setValue(new Pet("Santa's Little Helper"));
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element checkboxElement = (Element) document.getRootElement().elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("radio", checkboxElement.attribute("type").getValue());
assertEquals("pets", checkboxElement.attribute("name").getValue());
assertEquals("Santa's Little Helper", checkboxElement.attribute("value").getValue());
assertNull(checkboxElement.attribute("checked"));
}
public void testCollectionOfPetsWithEditor() throws Exception {
this.tag.setPath("pets");
this.tag.setValue(new ItemPet("Rudiger"));
BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
PropertyEditorSupport editor = new ItemPet.CustomEditor();
bindingResult.getPropertyEditorRegistry().registerCustomEditor(ItemPet.class, editor);
getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, bindingResult);
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element checkboxElement = (Element) document.getRootElement().elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("radio", checkboxElement.attribute("type").getValue());
assertEquals("pets", checkboxElement.attribute("name").getValue());
assertEquals("Rudiger", checkboxElement.attribute("value").getValue());
assertEquals("checked", checkboxElement.attribute("checked").getValue());
}
private void assertTagOpened(String output) {
assertTrue(output.indexOf("<input ") > -1);
}
private void assertTagClosed(String output) {
assertTrue(output.indexOf("/>") > -1);
}
private Float getFloat() {
return new Float("12.99");
}
protected TestBean createTestBean() {
this.bean = new TestBean();
bean.setSex("M");
bean.setMyFloat(getFloat());
bean.setPets(Collections.singletonList(new Pet("Rudiger")));
return bean;
}
private static class MyFloatEditor extends PropertyEditorSupport {
public void setAsText(String text) throws IllegalArgumentException {
setValue(text.substring(1));
}
public String getAsText() {
return "F" + (Float) getValue();
}
}
}

View File

@@ -0,0 +1,515 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.tags.form;
import java.beans.PropertyEditorSupport;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.jsp.tagext.Tag;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.Colour;
import org.springframework.beans.Pet;
import org.springframework.beans.TestBean;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
/**
* @author Thomas Risberg
* @author Juergen Hoeller
*/
public class RadioButtonsTagTests extends AbstractFormTagTests {
private RadioButtonsTag tag;
private TestBean bean;
protected void onSetUp() {
this.tag = new RadioButtonsTag() {
protected TagWriter createTagWriter() {
return new TagWriter(getWriter());
}
};
this.tag.setPageContext(getPageContext());
}
public void testWithMultiValueArray() throws Exception {
this.tag.setPath("stringArray");
this.tag.setItems(new Object[] {"foo", "bar", "baz"});
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element spanElement1 = (Element) document.getRootElement().elements().get(0);
Element radioButtonElement1 = (Element) spanElement1.elements().get(0);
assertEquals("input", radioButtonElement1.getName());
assertEquals("radio", radioButtonElement1.attribute("type").getValue());
assertEquals("stringArray", radioButtonElement1.attribute("name").getValue());
assertEquals("checked", radioButtonElement1.attribute("checked").getValue());
assertEquals("foo", radioButtonElement1.attribute("value").getValue());
assertEquals("foo", spanElement1.getStringValue());
Element spanElement2 = (Element) document.getRootElement().elements().get(1);
Element radioButtonElement2 = (Element) spanElement2.elements().get(0);
assertEquals("input", radioButtonElement2.getName());
assertEquals("radio", radioButtonElement2.attribute("type").getValue());
assertEquals("stringArray", radioButtonElement2.attribute("name").getValue());
assertEquals("checked", radioButtonElement2.attribute("checked").getValue());
assertEquals("bar", radioButtonElement2.attribute("value").getValue());
assertEquals("bar", spanElement2.getStringValue());
Element spanElement3 = (Element) document.getRootElement().elements().get(2);
Element radioButtonElement3 = (Element) spanElement3.elements().get(0);
assertEquals("input", radioButtonElement3.getName());
assertEquals("radio", radioButtonElement3.attribute("type").getValue());
assertEquals("stringArray", radioButtonElement3.attribute("name").getValue());
assertNull("not checked", radioButtonElement3.attribute("checked"));
assertEquals("baz", radioButtonElement3.attribute("value").getValue());
assertEquals("baz", spanElement3.getStringValue());
}
public void testWithMultiValueArrayWithDelimiter() throws Exception {
this.tag.setDelimiter("<br/>");
this.tag.setPath("stringArray");
this.tag.setItems(new Object[] {"foo", "bar", "baz"});
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element spanElement1 = (Element) document.getRootElement().elements().get(0);
Element delimiterElement1 = spanElement1.element("br");
assertNull(delimiterElement1);
Element radioButtonElement1 = (Element) spanElement1.elements().get(0);
assertEquals("input", radioButtonElement1.getName());
assertEquals("radio", radioButtonElement1.attribute("type").getValue());
assertEquals("stringArray", radioButtonElement1.attribute("name").getValue());
assertEquals("checked", radioButtonElement1.attribute("checked").getValue());
assertEquals("foo", radioButtonElement1.attribute("value").getValue());
assertEquals("foo", spanElement1.getStringValue());
Element spanElement2 = (Element) document.getRootElement().elements().get(1);
Element delimiterElement2 = (Element) spanElement2.elements().get(0);
assertEquals("br", delimiterElement2.getName());
Element radioButtonElement2 = (Element) spanElement2.elements().get(1);
assertEquals("input", radioButtonElement2.getName());
assertEquals("radio", radioButtonElement2.attribute("type").getValue());
assertEquals("stringArray", radioButtonElement2.attribute("name").getValue());
assertEquals("checked", radioButtonElement2.attribute("checked").getValue());
assertEquals("bar", radioButtonElement2.attribute("value").getValue());
assertEquals("bar", spanElement2.getStringValue());
Element spanElement3 = (Element) document.getRootElement().elements().get(2);
Element delimiterElement3 = (Element) spanElement3.elements().get(0);
assertEquals("br", delimiterElement3.getName());
Element radioButtonElement3 = (Element) spanElement3.elements().get(1);
assertEquals("input", radioButtonElement3.getName());
assertEquals("radio", radioButtonElement3.attribute("type").getValue());
assertEquals("stringArray", radioButtonElement3.attribute("name").getValue());
assertNull("not checked", radioButtonElement3.attribute("checked"));
assertEquals("baz", radioButtonElement3.attribute("value").getValue());
assertEquals("baz", spanElement3.getStringValue());
}
public void testWithMultiValueMap() throws Exception {
this.tag.setPath("stringArray");
Map m = new LinkedHashMap();
m.put("foo", "FOO");
m.put("bar", "BAR");
m.put("baz", "BAZ");
this.tag.setItems(m);
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element spanElement1 = (Element) document.getRootElement().elements().get(0);
Element radioButtonElement1 = (Element) spanElement1.elements().get(0);
assertEquals("input", radioButtonElement1.getName());
assertEquals("radio", radioButtonElement1.attribute("type").getValue());
assertEquals("stringArray", radioButtonElement1.attribute("name").getValue());
assertEquals("checked", radioButtonElement1.attribute("checked").getValue());
assertEquals("foo", radioButtonElement1.attribute("value").getValue());
assertEquals("FOO", spanElement1.getStringValue());
Element spanElement2 = (Element) document.getRootElement().elements().get(1);
Element radioButtonElement2 = (Element) spanElement2.elements().get(0);
assertEquals("input", radioButtonElement2.getName());
assertEquals("radio", radioButtonElement2.attribute("type").getValue());
assertEquals("stringArray", radioButtonElement2.attribute("name").getValue());
assertEquals("checked", radioButtonElement2.attribute("checked").getValue());
assertEquals("bar", radioButtonElement2.attribute("value").getValue());
assertEquals("BAR", spanElement2.getStringValue());
Element spanElement3 = (Element) document.getRootElement().elements().get(2);
Element radioButtonElement3 = (Element) spanElement3.elements().get(0);
assertEquals("input", radioButtonElement3.getName());
assertEquals("radio", radioButtonElement3.attribute("type").getValue());
assertEquals("stringArray", radioButtonElement3.attribute("name").getValue());
assertNull("not checked", radioButtonElement3.attribute("checked"));
assertEquals("baz", radioButtonElement3.attribute("value").getValue());
assertEquals("BAZ", spanElement3.getStringValue());
}
public void testWithMultiValueMapWithDelimiter() throws Exception {
String delimiter = " | ";
this.tag.setDelimiter(delimiter);
this.tag.setPath("stringArray");
Map m = new LinkedHashMap();
m.put("foo", "FOO");
m.put("bar", "BAR");
m.put("baz", "BAZ");
this.tag.setItems(m);
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element spanElement1 = (Element) document.getRootElement().elements().get(0);
Element radioButtonElement1 = (Element) spanElement1.elements().get(0);
assertEquals("input", radioButtonElement1.getName());
assertEquals("radio", radioButtonElement1.attribute("type").getValue());
assertEquals("stringArray", radioButtonElement1.attribute("name").getValue());
assertEquals("checked", radioButtonElement1.attribute("checked").getValue());
assertEquals("foo", radioButtonElement1.attribute("value").getValue());
assertEquals("FOO", spanElement1.getStringValue());
Element spanElement2 = (Element) document.getRootElement().elements().get(1);
Element radioButtonElement2 = (Element) spanElement2.elements().get(0);
assertEquals("input", radioButtonElement2.getName());
assertEquals("radio", radioButtonElement2.attribute("type").getValue());
assertEquals("stringArray", radioButtonElement2.attribute("name").getValue());
assertEquals("checked", radioButtonElement2.attribute("checked").getValue());
assertEquals("bar", radioButtonElement2.attribute("value").getValue());
assertEquals(delimiter + "BAR", spanElement2.getStringValue());
Element spanElement3 = (Element) document.getRootElement().elements().get(2);
Element radioButtonElement3 = (Element) spanElement3.elements().get(0);
assertEquals("input", radioButtonElement3.getName());
assertEquals("radio", radioButtonElement3.attribute("type").getValue());
assertEquals("stringArray", radioButtonElement3.attribute("name").getValue());
assertNull("not checked", radioButtonElement3.attribute("checked"));
assertEquals("baz", radioButtonElement3.attribute("value").getValue());
assertEquals(delimiter + "BAZ", spanElement3.getStringValue());
}
public void testWithMultiValueWithEditor() throws Exception {
this.tag.setPath("stringArray");
this.tag.setItems(new Object[] {" foo", " bar", " baz"});
BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
MyStringTrimmerEditor editor = new MyStringTrimmerEditor();
bindingResult.getPropertyEditorRegistry().registerCustomEditor(String.class, editor);
getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, bindingResult);
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
assertEquals(3, editor.allProcessedValues.size());
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element spanElement1 = (Element) document.getRootElement().elements().get(0);
Element radioButtonElement1 = (Element) spanElement1.elements().get(0);
assertEquals("input", radioButtonElement1.getName());
assertEquals("radio", radioButtonElement1.attribute("type").getValue());
assertEquals("stringArray", radioButtonElement1.attribute("name").getValue());
assertEquals("checked", radioButtonElement1.attribute("checked").getValue());
assertEquals(" foo", radioButtonElement1.attribute("value").getValue());
Element spanElement2 = (Element) document.getRootElement().elements().get(1);
Element radioButtonElement2 = (Element) spanElement2.elements().get(0);
assertEquals("input", radioButtonElement2.getName());
assertEquals("radio", radioButtonElement2.attribute("type").getValue());
assertEquals("stringArray", radioButtonElement2.attribute("name").getValue());
assertEquals("checked", radioButtonElement2.attribute("checked").getValue());
assertEquals(" bar", radioButtonElement2.attribute("value").getValue());
Element spanElement3 = (Element) document.getRootElement().elements().get(2);
Element radioButtonElement3 = (Element) spanElement3.elements().get(0);
assertEquals("input", radioButtonElement3.getName());
assertEquals("radio", radioButtonElement3.attribute("type").getValue());
assertEquals("stringArray", radioButtonElement3.attribute("name").getValue());
assertNull("not checked", radioButtonElement3.attribute("checked"));
assertEquals(" baz", radioButtonElement3.attribute("value").getValue());
}
public void testCollectionOfPets() throws Exception {
this.tag.setPath("pets");
List allPets = new ArrayList();
allPets.add(new ItemPet("Rudiger"));
allPets.add(new ItemPet("Spot"));
allPets.add(new ItemPet("Checkers"));
allPets.add(new ItemPet("Fluffy"));
allPets.add(new ItemPet("Mufty"));
this.tag.setItems(allPets);
this.tag.setItemValue("name");
this.tag.setItemLabel("label");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element spanElement1 = (Element) document.getRootElement().elements().get(0);
Element radioButtonElement1 = (Element) spanElement1.elements().get(0);
assertEquals("input", radioButtonElement1.getName());
assertEquals("radio", radioButtonElement1.attribute("type").getValue());
assertEquals("pets", radioButtonElement1.attribute("name").getValue());
assertEquals("checked", radioButtonElement1.attribute("checked").getValue());
assertEquals("Rudiger", radioButtonElement1.attribute("value").getValue());
assertEquals("RUDIGER", spanElement1.getStringValue());
Element spanElement2 = (Element) document.getRootElement().elements().get(1);
Element radioButtonElement2 = (Element) spanElement2.elements().get(0);
assertEquals("input", radioButtonElement2.getName());
assertEquals("radio", radioButtonElement2.attribute("type").getValue());
assertEquals("pets", radioButtonElement2.attribute("name").getValue());
assertEquals("checked", radioButtonElement2.attribute("checked").getValue());
assertEquals("Spot", radioButtonElement2.attribute("value").getValue());
assertEquals("SPOT", spanElement2.getStringValue());
Element spanElement3 = (Element) document.getRootElement().elements().get(2);
Element radioButtonElement3 = (Element) spanElement3.elements().get(0);
assertEquals("input", radioButtonElement3.getName());
assertEquals("radio", radioButtonElement3.attribute("type").getValue());
assertEquals("pets", radioButtonElement3.attribute("name").getValue());
assertNull("not checked", radioButtonElement3.attribute("checked"));
assertEquals("Checkers", radioButtonElement3.attribute("value").getValue());
assertEquals("CHECKERS", spanElement3.getStringValue());
Element spanElement4 = (Element) document.getRootElement().elements().get(3);
Element radioButtonElement4 = (Element) spanElement4.elements().get(0);
assertEquals("input", radioButtonElement4.getName());
assertEquals("radio", radioButtonElement4.attribute("type").getValue());
assertEquals("pets", radioButtonElement4.attribute("name").getValue());
assertEquals("checked", radioButtonElement4.attribute("checked").getValue());
assertEquals("Fluffy", radioButtonElement4.attribute("value").getValue());
assertEquals("FLUFFY", spanElement4.getStringValue());
Element spanElement5 = (Element) document.getRootElement().elements().get(4);
Element radioButtonElement5 = (Element) spanElement5.elements().get(0);
assertEquals("input", radioButtonElement5.getName());
assertEquals("radio", radioButtonElement5.attribute("type").getValue());
assertEquals("pets", radioButtonElement5.attribute("name").getValue());
assertEquals("checked", radioButtonElement5.attribute("checked").getValue());
assertEquals("Mufty", radioButtonElement5.attribute("value").getValue());
assertEquals("MUFTY", spanElement5.getStringValue());
}
public void testCollectionOfPetsWithEditor() throws Exception {
this.tag.setPath("pets");
List allPets = new ArrayList();
allPets.add(new ItemPet("Rudiger"));
allPets.add(new ItemPet("Spot"));
allPets.add(new ItemPet("Checkers"));
allPets.add(new ItemPet("Fluffy"));
allPets.add(new ItemPet("Mufty"));
this.tag.setItems(allPets);
this.tag.setItemLabel("label");
this.tag.setId("myId");
BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
PropertyEditorSupport editor = new ItemPet.CustomEditor();
bindingResult.getPropertyEditorRegistry().registerCustomEditor(ItemPet.class, editor);
getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, bindingResult);
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element spanElement1 = (Element) document.getRootElement().elements().get(0);
Element radioButtonElement1 = (Element) spanElement1.elements().get(0);
assertEquals("input", radioButtonElement1.getName());
assertEquals("radio", radioButtonElement1.attribute("type").getValue());
assertEquals("pets", radioButtonElement1.attribute("name").getValue());
assertEquals("checked", radioButtonElement1.attribute("checked").getValue());
assertEquals("Rudiger", radioButtonElement1.attribute("value").getValue());
assertEquals("RUDIGER", spanElement1.getStringValue());
Element spanElement2 = (Element) document.getRootElement().elements().get(1);
Element radioButtonElement2 = (Element) spanElement2.elements().get(0);
assertEquals("input", radioButtonElement2.getName());
assertEquals("radio", radioButtonElement2.attribute("type").getValue());
assertEquals("pets", radioButtonElement2.attribute("name").getValue());
assertEquals("checked", radioButtonElement2.attribute("checked").getValue());
assertEquals("Spot", radioButtonElement2.attribute("value").getValue());
assertEquals("SPOT", spanElement2.getStringValue());
Element spanElement3 = (Element) document.getRootElement().elements().get(2);
Element radioButtonElement3 = (Element) spanElement3.elements().get(0);
assertEquals("input", radioButtonElement3.getName());
assertEquals("radio", radioButtonElement3.attribute("type").getValue());
assertEquals("pets", radioButtonElement3.attribute("name").getValue());
assertNull("not checked", radioButtonElement3.attribute("checked"));
assertEquals("Checkers", radioButtonElement3.attribute("value").getValue());
assertEquals("CHECKERS", spanElement3.getStringValue());
Element spanElement4 = (Element) document.getRootElement().elements().get(3);
Element radioButtonElement4 = (Element) spanElement4.elements().get(0);
assertEquals("input", radioButtonElement4.getName());
assertEquals("radio", radioButtonElement4.attribute("type").getValue());
assertEquals("pets", radioButtonElement4.attribute("name").getValue());
assertEquals("checked", radioButtonElement4.attribute("checked").getValue());
assertEquals("Fluffy", radioButtonElement4.attribute("value").getValue());
assertEquals("FLUFFY", spanElement4.getStringValue());
Element spanElement5 = (Element) document.getRootElement().elements().get(4);
Element radioButtonElement5 = (Element) spanElement5.elements().get(0);
assertEquals("input", radioButtonElement5.getName());
assertEquals("radio", radioButtonElement5.attribute("type").getValue());
assertEquals("pets", radioButtonElement5.attribute("name").getValue());
assertEquals("checked", radioButtonElement5.attribute("checked").getValue());
assertEquals("Mufty", radioButtonElement5.attribute("value").getValue());
assertEquals("MUFTY", spanElement5.getStringValue());
}
public void testWithNullValue() throws Exception {
try {
this.tag.setPath("name");
this.tag.doStartTag();
fail("Should not be able to render with a null value when binding to a non-boolean.");
}
catch (IllegalArgumentException ex) {
// success
}
}
public void testHiddenElementOmittedOnDisabled() throws Exception {
this.tag.setPath("stringArray");
this.tag.setItems(new Object[] {"foo", "bar", "baz"});
this.tag.setDisabled("true");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element rootElement = document.getRootElement();
assertEquals("Both tag and hidden element rendered incorrectly", 3, rootElement.elements().size());
Element spanElement = (Element) document.getRootElement().elements().get(0);
Element radioButtonElement = (Element) spanElement.elements().get(0);
assertEquals("input", radioButtonElement.getName());
assertEquals("radio", radioButtonElement.attribute("type").getValue());
assertEquals("stringArray", radioButtonElement.attribute("name").getValue());
assertEquals("checked", radioButtonElement.attribute("checked").getValue());
assertEquals("disabled", radioButtonElement.attribute("disabled").getValue());
assertEquals("foo", radioButtonElement.attribute("value").getValue());
}
public void testSpanElementCustomizable() throws Exception {
this.tag.setPath("stringArray");
this.tag.setItems(new Object[] {"foo", "bar", "baz"});
this.tag.setElement("element");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element spanElement = (Element) document.getRootElement().elements().get(0);
assertEquals("element", spanElement.getName());
}
private Date getDate() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 10);
cal.set(Calendar.MONTH, 10);
cal.set(Calendar.DATE, 10);
cal.set(Calendar.HOUR, 10);
cal.set(Calendar.MINUTE, 10);
cal.set(Calendar.SECOND, 10);
return cal.getTime();
}
protected TestBean createTestBean() {
List colours = new ArrayList();
colours.add(Colour.BLUE);
colours.add(Colour.RED);
colours.add(Colour.GREEN);
List pets = new ArrayList();
pets.add(new Pet("Rudiger"));
pets.add(new Pet("Spot"));
pets.add(new Pet("Fluffy"));
pets.add(new Pet("Mufty"));
this.bean = new TestBean();
this.bean.setDate(getDate());
this.bean.setName("Rob Harrop");
this.bean.setJedi(true);
this.bean.setSomeBoolean(new Boolean(true));
this.bean.setStringArray(new String[] {"bar", "foo"});
this.bean.setSomeIntegerArray(new Integer[] {new Integer(2), new Integer(1)});
this.bean.setOtherColours(colours);
this.bean.setPets(pets);
List list = new ArrayList();
list.add("foo");
list.add("bar");
this.bean.setSomeList(list);
return this.bean;
}
private static class MyStringTrimmerEditor extends StringTrimmerEditor {
public final Set allProcessedValues = new HashSet();
public MyStringTrimmerEditor() {
super(false);
}
public void setAsText(String text) {
super.setAsText(text);
this.allProcessedValues.add(getValue());
}
}
}

View File

@@ -0,0 +1,622 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.tags.form;
import java.beans.PropertyEditor;
import java.beans.PropertyEditorSupport;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.Tag;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.TestBean;
import org.springframework.beans.propertyeditors.CustomCollectionEditor;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.support.BindStatus;
import org.springframework.web.servlet.tags.TransformTag;
/**
* @author Rob Harrop
* @author Juergen Hoeller
*/
public class SelectTagTests extends AbstractFormTagTests {
private static final Locale LOCALE_AT = new Locale("de", "AT");
private static final Locale LOCALE_NL = new Locale("nl", "NL");
private SelectTag tag;
private TestBean bean;
protected void onSetUp() {
this.tag = new SelectTag() {
protected TagWriter createTagWriter() {
return new TagWriter(getWriter());
}
};
this.tag.setPageContext(getPageContext());
}
public void testEmptyItems() throws Exception {
this.tag.setPath("country");
this.tag.setItems(Collections.EMPTY_LIST);
this.tag.setItemValue("isoCode");
this.tag.setItemLabel("name");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
assertEquals("<select id=\"country\" name=\"country\"></select>", output);
}
public void testNullItems() throws Exception {
this.tag.setPath("country");
this.tag.setItems(null);
this.tag.setItemValue("isoCode");
this.tag.setItemLabel("name");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
assertEquals("<select id=\"country\" name=\"country\"></select>", output);
}
public void testWithList() throws Exception {
this.tag.setPath("country");
this.tag.setItems(Country.getCountries());
assertList(true);
}
public void testWithResolvedList() throws Exception {
this.tag.setPath("country");
this.tag.setItems("${countries}");
assertList(true);
}
public void testWithOtherValue() throws Exception {
TestBean tb = getTestBean();
tb.setCountry("AT");
this.tag.setPath("country");
this.tag.setItems(Country.getCountries());
assertList(false);
}
public void testWithNullValue() throws Exception {
TestBean tb = getTestBean();
tb.setCountry(null);
this.tag.setPath("country");
this.tag.setItems(Country.getCountries());
assertList(false);
}
public void testWithListAndNoLabel() throws Exception {
this.tag.setPath("country");
this.tag.setItems("${countries}");
this.tag.setItemValue("isoCode");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
validateOutput(getOutput(), true);
}
public void testWithListAndTransformTag() throws Exception {
this.tag.setPath("country");
this.tag.setItems(Country.getCountries());
assertList(true);
TransformTag transformTag = new TransformTag();
transformTag.setValue(Country.getCountries().get(0));
transformTag.setVar("key");
transformTag.setParent(this.tag);
transformTag.setPageContext(getPageContext());
transformTag.doStartTag();
assertEquals("Austria(AT)", getPageContext().findAttribute("key"));
}
public void testWithListAndTransformTagAndEditor() throws Exception {
this.tag.setPath("realCountry");
this.tag.setItems("${countries}");
BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(getTestBean(), "testBean");
bindingResult.getPropertyAccessor().registerCustomEditor(Country.class, new PropertyEditorSupport() {
public void setAsText(String text) throws IllegalArgumentException {
setValue(new Country(text, ""));
}
public String getAsText() {
return ((Country) getValue()).getName();
}
});
getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "testBean", bindingResult);
this.tag.doStartTag();
TransformTag transformTag = new TransformTag();
transformTag.setValue(Country.getCountries().get(0));
transformTag.setVar("key");
transformTag.setParent(this.tag);
transformTag.setPageContext(getPageContext());
transformTag.doStartTag();
assertEquals("Austria", getPageContext().findAttribute("key"));
}
public void testWithMap() throws Exception {
this.tag.setPath("sex");
this.tag.setItems("${sexes}");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
}
public void testWithInvalidList() throws Exception {
this.tag.setPath("country");
this.tag.setItems("${other}");
this.tag.setItemValue("isoCode");
try {
this.tag.doStartTag();
fail("Must not be able to use a non-Collection typed value as the value of 'items'");
}
catch (JspException expected) {
String message = expected.getMessage();
assertTrue(message.indexOf("items") > -1);
assertTrue(message.indexOf("org.springframework.beans.TestBean") > -1);
}
}
public void testWithNestedOptions() throws Exception {
this.tag.setPath("country");
int result = this.tag.doStartTag();
assertEquals(Tag.EVAL_BODY_INCLUDE, result);
BindStatus value = (BindStatus) getPageContext().getAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE);
assertEquals("Selected country not exposed in page context", "UK", value.getValue());
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
this.tag.doFinally();
String output = getOutput();
assertTrue(output.startsWith("<select "));
assertTrue(output.endsWith("</select>"));
assertContainsAttribute(output, "name", "country");
}
public void testWithStringArray() throws Exception {
this.tag.setPath("name");
this.tag.setItems(getNames());
assertStringArray();
}
public void testWithResolvedStringArray() throws Exception {
this.tag.setPath("name");
this.tag.setItems("${names}");
assertStringArray();
}
public void testWithIntegerArray() throws Exception {
this.tag.setPath("someIntegerArray");
Integer[] array = new Integer[50];
for (int i = 0; i < array.length; i++) {
array[i] = new Integer(i);
}
this.tag.setItems(array);
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element rootElement = document.getRootElement();
assertEquals(2, rootElement.elements().size());
Element selectElement = rootElement.element("select");
assertEquals("select", selectElement.getName());
assertEquals("someIntegerArray", selectElement.attribute("name").getValue());
List children = selectElement.elements();
assertEquals("Incorrect number of children", array.length, children.size());
Element e = (Element) selectElement.selectSingleNode("option[text() = '12']");
assertEquals("'12' node not selected", "selected", e.attribute("selected").getValue());
e = (Element) selectElement.selectSingleNode("option[text() = '34']");
assertEquals("'34' node not selected", "selected", e.attribute("selected").getValue());
}
public void testWithFloatCustom() throws Exception {
PropertyEditor propertyEditor = new SimpleFloatEditor();
BeanPropertyBindingResult errors = new BeanPropertyBindingResult(getTestBean(), COMMAND_NAME);
errors.getPropertyAccessor().registerCustomEditor(Float.class, propertyEditor);
exposeBindingResult(errors);
this.tag.setPath("myFloat");
Float[] array = new Float[] {
new Float("12.30"), new Float("12.32"), new Float("12.34"), new Float("12.36"),
new Float("12.38"), new Float("12.40"), new Float("12.42"), new Float("12.44"),
new Float("12.46"), new Float("12.48")
};
this.tag.setItems(array);
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
assertTrue(output.startsWith("<select "));
assertTrue(output.endsWith("</select>"));
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element rootElement = document.getRootElement();
assertEquals("select", rootElement.getName());
assertEquals("myFloat", rootElement.attribute("name").getValue());
List children = rootElement.elements();
assertEquals("Incorrect number of children", array.length, children.size());
Element e = (Element) rootElement.selectSingleNode("option[text() = '12.34f']");
assertEquals("'12.34' node not selected", "selected", e.attribute("selected").getValue());
e = (Element) rootElement.selectSingleNode("option[text() = '12.32f']");
assertNull("'12.32' node incorrectly selected", e.attribute("selected"));
}
public void testWithMultiList() throws Exception {
List list = new ArrayList();
list.add(Country.COUNTRY_UK);
list.add(Country.COUNTRY_AT);
this.bean.setSomeList(list);
this.tag.setPath("someList");
this.tag.setItems("${countries}");
this.tag.setItemValue("isoCode");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element rootElement = document.getRootElement();
assertEquals(2, rootElement.elements().size());
Element selectElement = rootElement.element("select");
assertEquals("select", selectElement.getName());
assertEquals("someList", selectElement.attribute("name").getValue());
List children = selectElement.elements();
assertEquals("Incorrect number of children", 4, children.size());
Element e = (Element) selectElement.selectSingleNode("option[@value = 'UK']");
assertEquals("UK node not selected", "selected", e.attribute("selected").getValue());
e = (Element) selectElement.selectSingleNode("option[@value = 'AT']");
assertEquals("AT node not selected", "selected", e.attribute("selected").getValue());
}
public void testWithMultiListAndCustomEditor() throws Exception {
List list = new ArrayList();
list.add(Country.COUNTRY_UK);
list.add(Country.COUNTRY_AT);
this.bean.setSomeList(list);
BeanPropertyBindingResult errors = new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
errors.getPropertyAccessor().registerCustomEditor(List.class, new CustomCollectionEditor(LinkedList.class) {
public String getAsText() {
return getValue().toString();
}
});
exposeBindingResult(errors);
this.tag.setPath("someList");
this.tag.setItems("${countries}");
this.tag.setItemValue("isoCode");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element rootElement = document.getRootElement();
assertEquals(2, rootElement.elements().size());
Element selectElement = rootElement.element("select");
assertEquals("select", selectElement.getName());
assertEquals("someList", selectElement.attribute("name").getValue());
List children = selectElement.elements();
assertEquals("Incorrect number of children", 4, children.size());
Element e = (Element) selectElement.selectSingleNode("option[@value = 'UK']");
assertEquals("UK node not selected", "selected", e.attribute("selected").getValue());
e = (Element) selectElement.selectSingleNode("option[@value = 'AT']");
assertEquals("AT node not selected", "selected", e.attribute("selected").getValue());
}
public void testWithMultiMap() throws Exception {
Map someMap = new HashMap();
someMap.put("M", "Male");
someMap.put("F", "Female");
this.bean.setSomeMap(someMap);
this.tag.setPath("someMap");
this.tag.setItems("${sexes}");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element rootElement = document.getRootElement();
assertEquals(2, rootElement.elements().size());
Element selectElement = rootElement.element("select");
assertEquals("select", selectElement.getName());
assertEquals("someMap", selectElement.attribute("name").getValue());
List children = selectElement.elements();
assertEquals("Incorrect number of children", 2, children.size());
Element e = (Element) selectElement.selectSingleNode("option[@value = 'M']");
assertEquals("M node not selected", "selected", e.attribute("selected").getValue());
e = (Element) selectElement.selectSingleNode("option[@value = 'F']");
assertEquals("F node not selected", "selected", e.attribute("selected").getValue());
}
/**
* Tests new support added as a result of <a
* href="http://opensource.atlassian.com/projects/spring/browse/SPR-2660"
* target="_blank">SPR-2660</a>.
* <p>
* Specifically, if the <code>items</code> attribute is supplied a
* {@link Map}, and <code>itemValue</code> and <code>itemLabel</code>
* are supplied non-null values, then:
* </p>
* <ul>
* <li><code>itemValue</code> will be used as the property name of the
* map's <em>key</em>, and</li>
* <li><code>itemLabel</code> will be used as the property name of the
* map's <em>value</em>.</li>
* </ul>
*/
public void testWithMultiMapWithItemValueAndItemLabel() throws Exception {
// Save original default locale.
final Locale defaultLocale = Locale.getDefault();
// Use a locale that doesn't result in the generation of HTML entities
// (e.g., not German, where ä becomes &auml;)
Locale.setDefault(Locale.US);
try {
final Country austria = Country.COUNTRY_AT;
final Country usa = Country.COUNTRY_US;
final Map someMap = new HashMap();
someMap.put(austria, LOCALE_AT);
someMap.put(usa, Locale.US);
this.bean.setSomeMap(someMap);
this.tag.setPath("someMap"); // see: TestBean
this.tag.setItems("${countryToLocaleMap}"); // see: extendRequest()
this.tag.setItemValue("isoCode"); // Map key: Country
this.tag.setItemLabel("displayLanguage"); // Map value: Locale
BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(getTestBean(), COMMAND_NAME);
bindingResult.getPropertyAccessor().registerCustomEditor(Country.class, new PropertyEditorSupport() {
public void setAsText(final String text) throws IllegalArgumentException {
setValue(Country.getCountryWithIsoCode(text));
}
public String getAsText() {
return ((Country) getValue()).getIsoCode();
}
});
exposeBindingResult(bindingResult);
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element rootElement = document.getRootElement();
assertEquals(2, rootElement.elements().size());
Element selectElement = rootElement.element("select");
assertEquals("select", selectElement.getName());
assertEquals("someMap", selectElement.attribute("name").getValue());
List children = selectElement.elements();
assertEquals("Incorrect number of children", 3, children.size());
Element e;
e = (Element) selectElement.selectSingleNode("option[@value = '" + austria.getIsoCode() + "']");
assertNotNull("Option node not found with Country ISO code value [" + austria.getIsoCode() + "].", e);
assertEquals("AT node not selected.", "selected", e.attribute("selected").getValue());
assertEquals("AT Locale displayLanguage property not used for option label.",
LOCALE_AT.getDisplayLanguage(), e.getData());
e = (Element) selectElement.selectSingleNode("option[@value = '" + usa.getIsoCode() + "']");
assertNotNull("Option node not found with Country ISO code value [" + usa.getIsoCode() + "].", e);
assertEquals("US node not selected.", "selected", e.attribute("selected").getValue());
assertEquals("US Locale displayLanguage property not used for option label.",
Locale.US.getDisplayLanguage(), e.getData());
}
finally {
// Restore original default locale.
Locale.setDefault(defaultLocale);
}
}
public void testMultiWithEmptyCollection() throws Exception {
this.bean.setSomeList(new ArrayList());
this.tag.setPath("someList");
this.tag.setItems("${countries}");
this.tag.setItemValue("isoCode");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element rootElement = document.getRootElement();
assertEquals(2, rootElement.elements().size());
Element selectElement = rootElement.element("select");
assertEquals("select", selectElement.getName());
assertEquals("someList", selectElement.attribute("name").getValue());
assertEquals("multiple", selectElement.attribute("multiple").getValue());
List children = selectElement.elements();
assertEquals("Incorrect number of children", 4, children.size());
Element inputElement = rootElement.element("input");
assertNotNull(inputElement);
}
private void assertStringArray() throws JspException, DocumentException {
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
assertTrue(output.startsWith("<select "));
assertTrue(output.endsWith("</select>"));
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element rootElement = document.getRootElement();
assertEquals("select", rootElement.getName());
assertEquals("name", rootElement.attribute("name").getValue());
List children = rootElement.elements();
assertEquals("Incorrect number of children", 4, children.size());
Element e = (Element) rootElement.selectSingleNode("option[text() = 'Rob']");
assertEquals("Rob node not selected", "selected", e.attribute("selected").getValue());
}
private Map getCountryToLocaleMap() {
Map map = new TreeMap(new Comparator() {
public int compare(Object o1, Object o2) {
return ((Country)o1).getName().compareTo(((Country)o2).getName());
}
});
map.put(Country.COUNTRY_AT, LOCALE_AT);
map.put(Country.COUNTRY_NL, LOCALE_NL);
map.put(Country.COUNTRY_US, Locale.US);
return map;
}
private String[] getNames() {
return new String[]{"Rod", "Rob", "Juergen", "Adrian"};
}
private Map getSexes() {
Map sexes = new HashMap();
sexes.put("F", "Female");
sexes.put("M", "Male");
return sexes;
}
protected void extendRequest(MockHttpServletRequest request) {
super.extendRequest(request);
request.setAttribute("countries", Country.getCountries());
request.setAttribute("countryToLocaleMap", getCountryToLocaleMap());
request.setAttribute("sexes", getSexes());
request.setAttribute("other", new TestBean());
request.setAttribute("names", getNames());
}
private void assertList(boolean selected) throws JspException, DocumentException {
this.tag.setItemValue("isoCode");
this.tag.setItemLabel("name");
this.tag.setSize("5");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
validateOutput(output, selected);
assertContainsAttribute(output, "size", "5");
}
private void validateOutput(String output, boolean selected) throws DocumentException {
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element rootElement = document.getRootElement();
assertEquals("select", rootElement.getName());
assertEquals("country", rootElement.attribute("name").getValue());
List children = rootElement.elements();
assertEquals("Incorrect number of children", 4, children.size());
Element e = (Element) rootElement.selectSingleNode("option[@value = 'UK']");
Attribute selectedAttr = e.attribute("selected");
if (selected) {
assertTrue(selectedAttr != null && "selected".equals(selectedAttr.getValue()));
}
else {
assertNull(selectedAttr);
}
}
protected TestBean createTestBean() {
this.bean = new TestBeanWithRealCountry();
this.bean.setName("Rob");
this.bean.setCountry("UK");
this.bean.setSex("M");
this.bean.setMyFloat(new Float("12.34"));
this.bean.setSomeIntegerArray(new Integer[]{new Integer(12), new Integer(34)});
return this.bean;
}
private TestBean getTestBean() {
return (TestBean) getPageContext().getRequest().getAttribute(COMMAND_NAME);
}
}

View File

@@ -0,0 +1,34 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.tags.form;
import java.beans.PropertyEditorSupport;
/**
* @author Rob Harrop
* @since 2.0
*/
class SimpleFloatEditor extends PropertyEditorSupport {
public void setAsText(String text) throws IllegalArgumentException {
setValue(new Float(text));
}
public String getAsText() {
return getValue() + "f";
}
}

View File

@@ -0,0 +1,47 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.tags.form;
import junit.framework.TestCase;
import javax.servlet.jsp.PageContext;
import org.springframework.mock.web.MockPageContext;
/**
* @author Rob Harrop
* @since 2.0
*/
public class TagIdGeneratorTests extends TestCase {
public void testNextId() throws Exception {
String name = "foo";
PageContext pageContext = new MockPageContext();
assertEquals("foo1", TagIdGenerator.nextId(name, pageContext));
assertEquals("foo2", TagIdGenerator.nextId(name, pageContext));
assertEquals("foo3", TagIdGenerator.nextId(name, pageContext));
assertEquals("foo4", TagIdGenerator.nextId(name, pageContext));
assertEquals("bar1", TagIdGenerator.nextId("bar", pageContext));
pageContext = new MockPageContext();
assertEquals("foo1", TagIdGenerator.nextId(name, pageContext));
assertEquals("foo2", TagIdGenerator.nextId(name, pageContext));
assertEquals("foo3", TagIdGenerator.nextId(name, pageContext));
assertEquals("foo4", TagIdGenerator.nextId(name, pageContext));
assertEquals("bar1", TagIdGenerator.nextId("bar", pageContext));
}
}

View File

@@ -0,0 +1,121 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.tags.form;
import java.io.StringWriter;
import junit.framework.TestCase;
/**
* @author Rob Harrop
* @author Rick Evans
*/
public class TagWriterTests extends TestCase {
private TagWriter writer;
private StringWriter data;
protected void setUp() throws Exception {
this.data = new StringWriter();
this.writer = new TagWriter(this.data);
}
public void testSimpleTag() throws Exception {
this.writer.startTag("br");
this.writer.endTag();
assertEquals("<br/>", this.data.toString());
}
public void testEmptyTag() throws Exception {
this.writer.startTag("input");
this.writer.writeAttribute("type", "text");
this.writer.endTag();
assertEquals("<input type=\"text\"/>", this.data.toString());
}
public void testSimpleBlockTag() throws Exception {
this.writer.startTag("textarea");
this.writer.appendValue("foobar");
this.writer.endTag();
assertEquals("<textarea>foobar</textarea>", this.data.toString());
}
public void testBlockTagWithAttributes() throws Exception {
this.writer.startTag("textarea");
this.writer.writeAttribute("width", "10");
this.writer.writeAttribute("height", "20");
this.writer.appendValue("foobar");
this.writer.endTag();
assertEquals("<textarea width=\"10\" height=\"20\">foobar</textarea>", this.data.toString());
}
public void testNestedTags() throws Exception {
this.writer.startTag("span");
this.writer.writeAttribute("style", "foo");
this.writer.startTag("strong");
this.writer.appendValue("Rob Harrop");
this.writer.endTag();
this.writer.endTag();
assertEquals("<span style=\"foo\"><strong>Rob Harrop</strong></span>", this.data.toString());
}
public void testMultipleNestedTags() throws Exception {
this.writer.startTag("span");
this.writer.writeAttribute("class", "highlight");
{
this.writer.startTag("strong");
this.writer.appendValue("Rob");
this.writer.endTag();
}
this.writer.appendValue(" ");
{
this.writer.startTag("emphasis");
this.writer.appendValue("Harrop");
this.writer.endTag();
}
this.writer.endTag();
assertEquals("<span class=\"highlight\"><strong>Rob</strong> <emphasis>Harrop</emphasis></span>", this.data.toString());
}
public void testWriteInterleavedWithForceBlock() throws Exception {
this.writer.startTag("span");
this.writer.forceBlock();
this.data.write("Rob Harrop"); // interleaved writing
this.writer.endTag();
assertEquals("<span>Rob Harrop</span>", this.data.toString());
}
public void testAppendingValue() throws Exception {
this.writer.startTag("span");
this.writer.appendValue("Rob ");
this.writer.appendValue("Harrop");
this.writer.endTag();
assertEquals("<span>Rob Harrop</span>", this.data.toString());
}
}

View File

@@ -0,0 +1,37 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.tags.form;
import org.springframework.beans.TestBean;
/**
* @author Juergen Hoeller
*/
public class TestBeanWithRealCountry extends TestBean {
private Country realCountry = Country.COUNTRY_AT;
public void setRealCountry(Country realCountry) {
this.realCountry = realCountry;
}
public Country getRealCountry() {
return realCountry;
}
}

View File

@@ -0,0 +1,106 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.tags.form;
import javax.servlet.jsp.tagext.Tag;
import org.springframework.beans.TestBean;
import org.springframework.validation.BeanPropertyBindingResult;
/**
* @author Rob Harrop
* @author Rick Evans
* @author Juergen Hoeller
*/
public class TextareaTagTests extends AbstractFormTagTests {
private TextareaTag tag;
private TestBean rob;
protected void onSetUp() {
this.tag = new TextareaTag() {
protected TagWriter createTagWriter() {
return new TagWriter(getWriter());
}
};
this.tag.setPageContext(getPageContext());
}
public void testSimpleBind() throws Exception {
this.tag.setPath("name");
this.tag.setReadonly("true");
assertEquals(Tag.SKIP_BODY, this.tag.doStartTag());
String output = getOutput();
assertContainsAttribute(output, "name", "name");
assertContainsAttribute(output, "readonly", "readonly");
assertBlockTagContains(output, "Rob");
}
public void testComplexBind() throws Exception {
String onselect = "doSelect()";
this.tag.setPath("spouse.name");
this.tag.setOnselect(onselect);
assertEquals(Tag.SKIP_BODY, this.tag.doStartTag());
String output = getOutput();
assertContainsAttribute(output, "name", "spouse.name");
assertContainsAttribute(output, "onselect", onselect);
assertAttributeNotPresent(output, "readonly");
}
public void testSimpleBindWithHtmlEscaping() throws Exception {
final String NAME = "Rob \"I Love Mangos\" Harrop";
final String HTML_ESCAPED_NAME = "Rob &quot;I Love Mangos&quot; Harrop";
this.tag.setPath("name");
this.rob.setName(NAME);
assertEquals(Tag.SKIP_BODY, this.tag.doStartTag());
String output = getOutput();
System.out.println(output);
assertContainsAttribute(output, "name", "name");
assertBlockTagContains(output, HTML_ESCAPED_NAME);
}
public void testCustomBind() throws Exception {
BeanPropertyBindingResult result = new BeanPropertyBindingResult(createTestBean(), "testBean");
result.getPropertyAccessor().registerCustomEditor(Float.class, new SimpleFloatEditor());
exposeBindingResult(result);
this.tag.setPath("myFloat");
assertEquals(Tag.SKIP_BODY, this.tag.doStartTag());
String output = getOutput();
assertContainsAttribute(output, "name", "myFloat");
assertBlockTagContains(output, "12.34f");
}
protected TestBean createTestBean() {
// set up test data
this.rob = new TestBean();
rob.setName("Rob");
rob.setMyFloat(new Float(12.34));
TestBean sally = new TestBean();
sally.setName("Sally");
rob.setSpouse(sally);
return rob;
}
}