EL container integration; support for contextual objects; removal of deprecated Spring 2.0 functionality; Java 5 code style

This commit is contained in:
Juergen Hoeller
2008-11-20 02:10:53 +00:00
parent 369821dd66
commit 347f34c68a
281 changed files with 6120 additions and 9903 deletions

View File

@@ -1,492 +0,0 @@
/*
* 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.bind;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.HttpRequestMethodNotSupportedException;
/**
* Parameter extraction methods, for an approach distinct from data binding,
* in which parameters of specific types are required.
*
* <p>This approach is very useful for simple submissions, where binding
* request parameters to a command object would be overkill.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Keith Donald
* @deprecated as of Spring 2.0: use ServletRequestUtils instead
* @see ServletRequestUtils
*/
@Deprecated
public abstract class RequestUtils {
/**
* Throw a ServletException if the given HTTP request method should be rejected.
* @param request request to check
* @param method method (such as "GET") which should be rejected
* @throws ServletException if the given HTTP request is rejected
*/
public static void rejectRequestMethod(HttpServletRequest request, String method) throws ServletException {
if (request.getMethod().equals(method)) {
throw new HttpRequestMethodNotSupportedException(method);
}
}
/**
* Get an Integer parameter, or <code>null</code> if not present.
* Throws an exception if it the parameter value isn't a number.
* @param request current HTTP request
* @param name the name of the parameter
* @return the Integer value, or <code>null</code> if not present
* @throws ServletRequestBindingException a subclass of ServletException,
* so it doesn't need to be caught
*/
public static Integer getIntParameter(HttpServletRequest request, String name)
throws ServletRequestBindingException {
return ServletRequestUtils.getIntParameter(request, name);
}
/**
* Get an int parameter, with a fallback value. Never throws an exception.
* Can pass a distinguished value as default to enable checks of whether it was supplied.
* @param request current HTTP request
* @param name the name of the parameter
* @param defaultVal the default value to use as fallback
*/
public static int getIntParameter(HttpServletRequest request, String name, int defaultVal) {
return ServletRequestUtils.getIntParameter(request, name, defaultVal);
}
/**
* Get an array of int parameters, return an empty array if not found.
* @param request current HTTP request
* @param name the name of the parameter with multiple possible values
*/
public static int[] getIntParameters(HttpServletRequest request, String name) {
return ServletRequestUtils.getIntParameters(request, name);
}
/**
* Get an int parameter, throwing an exception if it isn't found or isn't a number.
* @param request current HTTP request
* @param name the name of the parameter
* @throws ServletRequestBindingException a subclass of ServletException,
* so it doesn't need to be caught
*/
public static int getRequiredIntParameter(HttpServletRequest request, String name)
throws ServletRequestBindingException {
return ServletRequestUtils.getRequiredIntParameter(request, name);
}
/**
* Get an array of int parameters, throwing an exception if not found or one is not a number..
* @param request current HTTP request
* @param name the name of the parameter with multiple possible values
* @throws ServletRequestBindingException a subclass of ServletException,
* so it doesn't need to be caught
*/
public static int[] getRequiredIntParameters(HttpServletRequest request, String name)
throws ServletRequestBindingException {
return ServletRequestUtils.getRequiredIntParameters(request, name);
}
/**
* Get a Long parameter, or <code>null</code> if not present.
* Throws an exception if it the parameter value isn't a number.
* @param request current HTTP request
* @param name the name of the parameter
* @return the Long value, or <code>null</code> if not present
* @throws ServletRequestBindingException a subclass of ServletException,
* so it doesn't need to be caught
*/
public static Long getLongParameter(HttpServletRequest request, String name)
throws ServletRequestBindingException {
return ServletRequestUtils.getLongParameter(request, name);
}
/**
* Get a long parameter, with a fallback value. Never throws an exception.
* Can pass a distinguished value as default to enable checks of whether it was supplied.
* @param request current HTTP request
* @param name the name of the parameter
* @param defaultVal the default value to use as fallback
*/
public static long getLongParameter(HttpServletRequest request, String name, long defaultVal) {
return ServletRequestUtils.getLongParameter(request, name, defaultVal);
}
/**
* Get an array of long parameters, return an empty array if not found.
* @param request current HTTP request
* @param name the name of the parameter with multiple possible values
*/
public static long[] getLongParameters(HttpServletRequest request, String name) {
return ServletRequestUtils.getLongParameters(request, name);
}
/**
* Get a long parameter, throwing an exception if it isn't found or isn't a number.
* @param request current HTTP request
* @param name the name of the parameter
* @throws ServletRequestBindingException a subclass of ServletException,
* so it doesn't need to be caught
*/
public static long getRequiredLongParameter(HttpServletRequest request, String name)
throws ServletRequestBindingException {
return ServletRequestUtils.getRequiredLongParameter(request, name);
}
/**
* Get an array of long parameters, throwing an exception if not found or one is not a number.
* @param request current HTTP request
* @param name the name of the parameter with multiple possible values
* @throws ServletRequestBindingException a subclass of ServletException,
* so it doesn't need to be caught
*/
public static long[] getRequiredLongParameters(HttpServletRequest request, String name)
throws ServletRequestBindingException {
return ServletRequestUtils.getRequiredLongParameters(request, name);
}
/**
* Get a Float parameter, or <code>null</code> if not present.
* Throws an exception if it the parameter value isn't a number.
* @param request current HTTP request
* @param name the name of the parameter
* @return the Float value, or <code>null</code> if not present
* @throws ServletRequestBindingException a subclass of ServletException,
* so it doesn't need to be caught
*/
public static Float getFloatParameter(HttpServletRequest request, String name)
throws ServletRequestBindingException {
return ServletRequestUtils.getFloatParameter(request, name);
}
/**
* Get a float parameter, with a fallback value. Never throws an exception.
* Can pass a distinguished value as default to enable checks of whether it was supplied.
* @param request current HTTP request
* @param name the name of the parameter
* @param defaultVal the default value to use as fallback
*/
public static float getFloatParameter(HttpServletRequest request, String name, float defaultVal) {
return ServletRequestUtils.getFloatParameter(request, name, defaultVal);
}
/**
* Get an array of float parameters, return an empty array if not found.
* @param request current HTTP request
* @param name the name of the parameter with multiple possible values
*/
public static float[] getFloatParameters(HttpServletRequest request, String name) {
return ServletRequestUtils.getFloatParameters(request, name);
}
/**
* Get a float parameter, throwing an exception if it isn't found or isn't a number.
* @param request current HTTP request
* @param name the name of the parameter
* @throws ServletRequestBindingException a subclass of ServletException,
* so it doesn't need to be caught
*/
public static float getRequiredFloatParameter(HttpServletRequest request, String name)
throws ServletRequestBindingException {
return ServletRequestUtils.getRequiredFloatParameter(request, name);
}
/**
* Get an array of float parameters, throwing an exception if not found or one is not a number.
* @param request current HTTP request
* @param name the name of the parameter with multiple possible values
* @throws ServletRequestBindingException a subclass of ServletException,
* so it doesn't need to be caught
*/
public static float[] getRequiredFloatParameters(HttpServletRequest request, String name)
throws ServletRequestBindingException {
return ServletRequestUtils.getRequiredFloatParameters(request, name);
}
/**
* Get a Double parameter, or <code>null</code> if not present.
* Throws an exception if it the parameter value isn't a number.
* @param request current HTTP request
* @param name the name of the parameter
* @return the Double value, or <code>null</code> if not present
* @throws ServletRequestBindingException a subclass of ServletException,
* so it doesn't need to be caught
*/
public static Double getDoubleParameter(HttpServletRequest request, String name)
throws ServletRequestBindingException {
return ServletRequestUtils.getDoubleParameter(request, name);
}
/**
* Get a double parameter, with a fallback value. Never throws an exception.
* Can pass a distinguished value as default to enable checks of whether it was supplied.
* @param request current HTTP request
* @param name the name of the parameter
* @param defaultVal the default value to use as fallback
*/
public static double getDoubleParameter(HttpServletRequest request, String name, double defaultVal) {
return ServletRequestUtils.getDoubleParameter(request, name, defaultVal);
}
/**
* Get an array of double parameters, return an empty array if not found.
* @param request current HTTP request
* @param name the name of the parameter with multiple possible values
*/
public static double[] getDoubleParameters(HttpServletRequest request, String name) {
return ServletRequestUtils.getDoubleParameters(request, name);
}
/**
* Get a double parameter, throwing an exception if it isn't found or isn't a number.
* @param request current HTTP request
* @param name the name of the parameter
* @throws ServletRequestBindingException a subclass of ServletException,
* so it doesn't need to be caught
*/
public static double getRequiredDoubleParameter(HttpServletRequest request, String name)
throws ServletRequestBindingException {
return ServletRequestUtils.getRequiredDoubleParameter(request, name);
}
/**
* Get an array of double parameters, throwing an exception if not found or one is not a number.
* @param request current HTTP request
* @param name the name of the parameter with multiple possible values
* @throws ServletRequestBindingException a subclass of ServletException,
* so it doesn't need to be caught
*/
public static double[] getRequiredDoubleParameters(HttpServletRequest request, String name)
throws ServletRequestBindingException {
return ServletRequestUtils.getRequiredDoubleParameters(request, name);
}
/**
* Get a Boolean parameter, or <code>null</code> if not present.
* Throws an exception if it the parameter value isn't a boolean.
* <p>Accepts "true", "on", "yes" (any case) and "1" as values for true;
* treats every other non-empty value as false (i.e. parses leniently).
* @param request current HTTP request
* @param name the name of the parameter
* @return the Boolean value, or <code>null</code> if not present
* @throws ServletRequestBindingException a subclass of ServletException,
* so it doesn't need to be caught
*/
public static Boolean getBooleanParameter(HttpServletRequest request, String name)
throws ServletRequestBindingException {
if (request.getParameter(name) == null) {
return null;
}
return (getRequiredBooleanParameter(request, name) ? Boolean.TRUE : Boolean.FALSE);
}
/**
* Get a boolean parameter, with a fallback value. Never throws an exception.
* Can pass a distinguished value as default to enable checks of whether it was supplied.
* <p>Accepts "true", "on", "yes" (any case) and "1" as values for true;
* treats every other non-empty value as false (i.e. parses leniently).
* @param request current HTTP request
* @param name the name of the parameter
* @param defaultVal the default value to use as fallback
*/
public static boolean getBooleanParameter(HttpServletRequest request, String name, boolean defaultVal) {
if (request.getParameter(name) == null) {
return defaultVal;
}
try {
return getRequiredBooleanParameter(request, name);
}
catch (ServletRequestBindingException ex) {
return defaultVal;
}
}
/**
* Get an array of boolean parameters, return an empty array if not found.
* <p>Accepts "true", "on", "yes" (any case) and "1" as values for true;
* treats every other non-empty value as false (i.e. parses leniently).
* @param request current HTTP request
* @param name the name of the parameter with multiple possible values
*/
public static boolean[] getBooleanParameters(HttpServletRequest request, String name) {
try {
return getRequiredBooleanParameters(request, name);
}
catch (ServletRequestBindingException ex) {
return new boolean[0];
}
}
/**
* Get a boolean parameter, throwing an exception if it isn't found
* or isn't a boolean.
* <p>Accepts "true", "on", "yes" (any case) and "1" as values for true;
* treats every other non-empty value as false (i.e. parses leniently).
* @param request current HTTP request
* @param name the name of the parameter
* @throws ServletRequestBindingException a subclass of ServletException,
* so it doesn't need to be caught
*/
public static boolean getRequiredBooleanParameter(HttpServletRequest request, String name)
throws ServletRequestBindingException {
boolean value = ServletRequestUtils.getRequiredBooleanParameter(request, name);
if (!value && "".equals(request.getParameter(name))) {
throw new ServletRequestBindingException(
"Required boolean parameter '" + name + "' contains no value");
}
return value;
}
/**
* Get an array of boolean parameters, throwing an exception if not found
* or one isn't a boolean.
* <p>Accepts "true", "on", "yes" (any case) and "1" as values for true;
* treats every other non-empty value as false (i.e. parses leniently).
* @param request current HTTP request
* @param name the name of the parameter
* @throws ServletRequestBindingException a subclass of ServletException,
* so it doesn't need to be caught
*/
public static boolean[] getRequiredBooleanParameters(HttpServletRequest request, String name)
throws ServletRequestBindingException {
boolean[] values = ServletRequestUtils.getRequiredBooleanParameters(request, name);
for (int i = 0; i < values.length; i++) {
if (!values[i] && "".equals(request.getParameterValues(name)[i])) {
throw new ServletRequestBindingException(
"Required boolean parameter '" + name + "' contains no value");
}
}
return values;
}
/**
* Get a String parameter, or <code>null</code> if not present.
* Throws an exception if it the parameter value is empty.
* @param request current HTTP request
* @param name the name of the parameter
* @return the String value, or <code>null</code> if not present
* @throws ServletRequestBindingException a subclass of ServletException,
* so it doesn't need to be caught
*/
public static String getStringParameter(HttpServletRequest request, String name)
throws ServletRequestBindingException {
if (request.getParameter(name) == null) {
return null;
}
return getRequiredStringParameter(request, name);
}
/**
* Get a String parameter, with a fallback value. Never throws an exception.
* Can pass a distinguished value to default to enable checks of whether it was supplied.
* @param request current HTTP request
* @param name the name of the parameter
* @param defaultVal the default value to use as fallback
*/
public static String getStringParameter(HttpServletRequest request, String name, String defaultVal) {
if (request.getParameter(name) == null) {
return defaultVal;
}
try {
return getRequiredStringParameter(request, name);
}
catch (ServletRequestBindingException ex) {
return defaultVal;
}
}
/**
* Get an array of String parameters, return an empty array if not found.
* @param request current HTTP request
* @param name the name of the parameter with multiple possible values
*/
public static String[] getStringParameters(HttpServletRequest request, String name) {
try {
return getRequiredStringParameters(request, name);
}
catch (ServletRequestBindingException ex) {
return new String[0];
}
}
/**
* Get a String parameter, throwing an exception if it isn't found or is empty.
* @param request current HTTP request
* @param name the name of the parameter
* @throws ServletRequestBindingException a subclass of ServletException,
* so it doesn't need to be caught
*/
public static String getRequiredStringParameter(HttpServletRequest request, String name)
throws ServletRequestBindingException {
String value = ServletRequestUtils.getRequiredStringParameter(request, name);
if ("".equals(value)) {
throw new ServletRequestBindingException(
"Required string parameter '" + name + "' contains no value");
}
return value;
}
/**
* Get an array of String parameters, throwing an exception if not found or one is empty.
* @param request current HTTP request
* @param name the name of the parameter
* @throws ServletRequestBindingException a subclass of ServletException,
* so it doesn't need to be caught
*/
public static String[] getRequiredStringParameters(HttpServletRequest request, String name)
throws ServletRequestBindingException {
String[] values = ServletRequestUtils.getRequiredStringParameters(request, name);
for (int i = 0; i < values.length; i++) {
if ("".equals(values[i])) {
throw new ServletRequestBindingException(
"Required string parameter '" + name + "' contains no value");
}
}
return values;
}
}

View File

@@ -16,6 +16,7 @@
package org.springframework.web.bind.annotation.support;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
@@ -86,6 +87,7 @@ public class HandlerMethodInvoker {
private final SimpleSessionStatus sessionStatus = new SimpleSessionStatus();
public HandlerMethodInvoker(HandlerMethodResolver methodResolver) {
this(methodResolver, null);
}
@@ -94,11 +96,9 @@ public class HandlerMethodInvoker {
this(methodResolver, bindingInitializer, new DefaultSessionAttributeStore(), null);
}
public HandlerMethodInvoker(HandlerMethodResolver methodResolver,
WebBindingInitializer bindingInitializer,
SessionAttributeStore sessionAttributeStore,
ParameterNameDiscoverer parameterNameDiscoverer,
WebArgumentResolver... customArgumentResolvers) {
public HandlerMethodInvoker(HandlerMethodResolver methodResolver, WebBindingInitializer bindingInitializer,
SessionAttributeStore sessionAttributeStore, ParameterNameDiscoverer parameterNameDiscoverer,
WebArgumentResolver... customArgumentResolvers) {
this.methodResolver = methodResolver;
this.bindingInitializer = bindingInitializer;
@@ -107,10 +107,9 @@ public class HandlerMethodInvoker {
this.customArgumentResolvers = customArgumentResolvers;
}
public final Object invokeHandlerMethod(Method handlerMethod,
Object handler,
NativeWebRequest webRequest,
ExtendedModelMap implicitModel) throws Exception {
public final Object invokeHandlerMethod(Method handlerMethod, Object handler,
NativeWebRequest webRequest, ExtendedModelMap implicitModel) throws Exception {
Method handlerMethodToInvoke = BridgeMethodResolver.findBridgedMethod(handlerMethod);
try {
@@ -145,9 +144,9 @@ public class HandlerMethodInvoker {
@SuppressWarnings("unchecked")
private Object[] resolveHandlerArguments(Method handlerMethod,
Object handler,
NativeWebRequest webRequest,
ExtendedModelMap implicitModel) throws Exception {
Object handler,
NativeWebRequest webRequest,
ExtendedModelMap implicitModel) throws Exception {
Class[] paramTypes = handlerMethod.getParameterTypes();
Object[] args = new Object[paramTypes.length];
@@ -161,9 +160,9 @@ public class HandlerMethodInvoker {
String paramDefaultValue = null;
String pathVarName = null;
String attrName = null;
Object[] paramAnns = methodParam.getParameterAnnotations();
Annotation[] paramAnns = methodParam.getParameterAnnotations();
for (Object paramAnn : paramAnns) {
for (Annotation paramAnn : paramAnns) {
if (RequestParam.class.isInstance(paramAnn)) {
RequestParam requestParam = (RequestParam) paramAnn;
paramName = requestParam.value();
@@ -174,7 +173,8 @@ public class HandlerMethodInvoker {
else if (ModelAttribute.class.isInstance(paramAnn)) {
ModelAttribute attr = (ModelAttribute) paramAnn;
attrName = attr.value();
} else if (PathVariable.class.isInstance(paramAnn)) {
}
else if (PathVariable.class.isInstance(paramAnn)) {
PathVariable pathVar = (PathVariable) paramAnn;
pathVarName = pathVar.value();
}
@@ -185,7 +185,7 @@ public class HandlerMethodInvoker {
"choices - do not specify both on the same parameter: " + handlerMethod);
}
if (paramName == null && attrName == null && pathVarName == null) {
if (paramName == null && attrName == null && pathVarName == null) {
Object argValue = resolveCommonArgument(methodParam, webRequest);
if (argValue != WebArgumentResolver.UNRESOLVED) {
args[i] = argValue;
@@ -227,7 +227,8 @@ public class HandlerMethodInvoker {
i++;
}
implicitModel.putAll(binder.getBindingResult().getModel());
} else if (pathVarName != null) {
}
else if (pathVarName != null) {
args[i] = resolvePathVariable(pathVarName, methodParam, webRequest, handler);
}
}
@@ -265,10 +266,8 @@ public class HandlerMethodInvoker {
}
}
private Object[] resolveInitBinderArguments(Object handler,
Method initBinderMethod,
WebDataBinder binder,
NativeWebRequest webRequest) throws Exception {
private Object[] resolveInitBinderArguments(Object handler, Method initBinderMethod,
WebDataBinder binder, NativeWebRequest webRequest) throws Exception {
Class[] initBinderParams = initBinderMethod.getParameterTypes();
Object[] initBinderArgs = new Object[initBinderParams.length];
@@ -281,9 +280,9 @@ public class HandlerMethodInvoker {
boolean paramRequired = false;
String paramDefaultValue = null;
String pathVarName = null;
Object[] paramAnns = methodParam.getParameterAnnotations();
Annotation[] paramAnns = methodParam.getParameterAnnotations();
for (Object paramAnn : paramAnns) {
for (Annotation paramAnn : paramAnns) {
if (RequestParam.class.isInstance(paramAnn)) {
RequestParam requestParam = (RequestParam) paramAnn;
paramName = requestParam.value();
@@ -315,16 +314,18 @@ public class HandlerMethodInvoker {
paramName = "";
}
else {
throw new IllegalStateException("Unsupported argument [" + paramType.getName() +
"] for @InitBinder method: " + initBinderMethod);
throw new IllegalStateException(
"Unsupported argument [" + paramType.getName() + "] for @InitBinder method: " +
initBinderMethod);
}
}
}
if (paramName != null) {
initBinderArgs[i] =
resolveRequestParam(paramName, paramRequired, paramDefaultValue, methodParam, webRequest, null);
} else if (pathVarName != null) {
initBinderArgs[i] = resolveRequestParam(
paramName, paramRequired, paramDefaultValue, methodParam, webRequest, null);
}
else if (pathVarName != null) {
initBinderArgs[i] = resolvePathVariable(pathVarName, methodParam, webRequest, null);
}
}
@@ -332,19 +333,17 @@ public class HandlerMethodInvoker {
return initBinderArgs;
}
private Object resolveRequestParam(String paramName,
boolean paramRequired,
String paramDefaultValue,
MethodParameter methodParam,
NativeWebRequest webRequest,
Object handlerForInitBinderCall) throws Exception {
private Object resolveRequestParam(String paramName, boolean paramRequired, String paramDefaultValue,
MethodParameter methodParam, NativeWebRequest webRequest, Object handlerForInitBinderCall)
throws Exception {
Class paramType = methodParam.getParameterType();
if (paramName.length() == 0) {
paramName = methodParam.getParameterName();
if (paramName == null) {
throw new IllegalStateException("No parameter specified for @RequestParam argument of type [" +
paramType.getName() + "], and no parameter name information found in class file either.");
throw new IllegalStateException(
"No parameter specified for @RequestParam argument of type [" + paramType.getName() +
"], and no parameter name information found in class file either.");
}
}
Object paramValue = null;
@@ -375,11 +374,9 @@ public class HandlerMethodInvoker {
return binder.convertIfNecessary(paramValue, paramType, methodParam);
}
private WebDataBinder resolveModelAttribute(String attrName,
MethodParameter methodParam,
ExtendedModelMap implicitModel,
NativeWebRequest webRequest,
Object handler) throws Exception {
private WebDataBinder resolveModelAttribute(String attrName, MethodParameter methodParam,
ExtendedModelMap implicitModel, NativeWebRequest webRequest, Object handler)
throws Exception {
// Bind request parameter onto object...
String name = attrName;
@@ -406,22 +403,21 @@ public class HandlerMethodInvoker {
}
/**
* Resolves the given {@link org.springframework.web.bind.annotation.PathVariable @PathVariable} variable. Overriden in
* {@link org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.ServletHandlerMethodInvoker},
* throws an UnsupportedOperationException by default.
* Resolves the given {@link org.springframework.web.bind.annotation.PathVariable @PathVariable}
* variable. Throws an UnsupportedOperationException by default. Overridden in
* {@link org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.ServletHandlerMethodInvoker}.
*/
protected Object resolvePathVariable(String pathVarName,
MethodParameter methodParam,
NativeWebRequest webRequest,
Object handlerForInitBinderCall) throws Exception {
protected Object resolvePathVariable(String pathVarName, MethodParameter methodParam,
NativeWebRequest webRequest, Object handlerForInitBinderCall) throws Exception {
throw new UnsupportedOperationException("@PathVariable not supported");
}
@SuppressWarnings("unchecked")
public final void updateModelAttributes(Object handler,
Map mavModel,
ExtendedModelMap implicitModel,
NativeWebRequest webRequest) throws Exception {
Map mavModel,
ExtendedModelMap implicitModel,
NativeWebRequest webRequest) throws Exception {
if (this.methodResolver.hasSessionAttributes() && this.sessionStatus.isComplete()) {
for (String attrName : this.methodResolver.getActualSessionAttributeNames()) {
@@ -511,9 +507,10 @@ public class HandlerMethodInvoker {
Class paramType = methodParameter.getParameterType();
Object value = resolveStandardArgument(paramType, webRequest);
if (value != WebArgumentResolver.UNRESOLVED && !ClassUtils.isAssignableValue(paramType, value)) {
throw new IllegalStateException("Standard argument type [" + paramType.getName() +
"] resolved to incompatible value of type [" + (value != null ? value.getClass() : null) +
"]. Consider declaring the argument type in a less specific fashion.");
throw new IllegalStateException(
"Standard argument type [" + paramType.getName() + "] resolved to incompatible value of type [" +
(value != null ? value.getClass() : null) +
"]. Consider declaring the argument type in a less specific fashion.");
}
return value;
}

View File

@@ -17,7 +17,6 @@
package org.springframework.web.multipart.commons;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
@@ -26,10 +25,8 @@ import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
@@ -41,7 +38,7 @@ import org.springframework.web.util.WebUtils;
/**
* Servlet-based {@link org.springframework.web.multipart.MultipartResolver} implementation
* for <a href="http://jakarta.apache.org/commons/fileupload">Jakarta Commons FileUpload</a>
* 1.1 or above. Commons FileUpload 1.2 or above is recommended.
* 1.2 or above.
*
* <p>Provides "maxUploadSize", "maxInMemorySize" and "defaultEncoding" settings as
* bean properties (inherited from {@link CommonsFileUploadSupport}). See corresponding
@@ -64,9 +61,6 @@ import org.springframework.web.util.WebUtils;
public class CommonsMultipartResolver extends CommonsFileUploadSupport
implements MultipartResolver, ServletContextAware {
private final boolean commonsFileUpload12Present =
ClassUtils.hasMethod(ServletFileUpload.class, "isMultipartContent", new Class[] {HttpServletRequest.class});
private boolean resolveLazily = false;
@@ -127,11 +121,8 @@ public class CommonsMultipartResolver extends CommonsFileUploadSupport
if (request == null) {
return false;
}
else if (commonsFileUpload12Present) {
return ServletFileUpload.isMultipartContent(request);
}
else {
return ServletFileUpload.isMultipartContent(new ServletRequestContext(request));
return ServletFileUpload.isMultipartContent(request);
}
}

View File

@@ -38,9 +38,7 @@ public class ByteArrayMultipartFileEditor extends ByteArrayPropertyEditor {
super.setValue(multipartFile.getBytes());
}
catch (IOException ex) {
IllegalArgumentException iae = new IllegalArgumentException("Cannot read contents of multipart file");
iae.initCause(ex);
throw iae;
throw new IllegalArgumentException("Cannot read contents of multipart file", ex);
}
}
else if (value instanceof byte[]) {

View File

@@ -67,9 +67,7 @@ public class StringMultipartFileEditor extends PropertyEditorSupport {
new String(multipartFile.getBytes()));
}
catch (IOException ex) {
IllegalArgumentException iae = new IllegalArgumentException("Cannot read contents of multipart file");
iae.initCause(ex);
throw iae;
throw new IllegalArgumentException("Cannot read contents of multipart file", ex);
}
}
else {

View File

@@ -23,6 +23,7 @@ import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@@ -34,6 +35,7 @@ import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.BeanInitializationException;
@@ -41,7 +43,6 @@ import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.i18n.LocaleContext;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.JdkVersion;
import org.springframework.core.OrderComparator;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
@@ -83,11 +84,9 @@ import org.springframework.web.util.WebUtils;
*
* <li>It can use any {@link HandlerAdapter}; this allows for using any handler interface.
* Default adapters are {@link org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter},
* {@link org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter} and
* {@link org.springframework.web.servlet.mvc.throwaway.ThrowawayControllerHandlerAdapter},
* for Spring's {@link org.springframework.web.HttpRequestHandler},
* {@link org.springframework.web.servlet.mvc.Controller} and
* {@link org.springframework.web.servlet.mvc.throwaway.ThrowawayController} interfaces,
* {@link org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter},
* for Spring's {@link org.springframework.web.HttpRequestHandler} and
* {@link org.springframework.web.servlet.mvc.Controller} interfaces,
* respectively. When running in a Java 5+ environment, a default
* {@link org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter}
* will be registered as well. HandlerAdapter objects can be added as beans in the
@@ -298,19 +297,19 @@ public class DispatcherServlet extends FrameworkServlet {
private ThemeResolver themeResolver;
/** List of HandlerMappings used by this servlet */
private List handlerMappings;
private List<HandlerMapping> handlerMappings;
/** List of HandlerAdapters used by this servlet */
private List handlerAdapters;
private List<HandlerAdapter> handlerAdapters;
/** List of HandlerExceptionResolvers used by this servlet */
private List handlerExceptionResolvers;
private List<HandlerExceptionResolver> handlerExceptionResolvers;
/** RequestToViewNameTranslator used by this servlet */
private RequestToViewNameTranslator viewNameTranslator;
/** List of ViewResolvers used by this servlet */
private List viewResolvers;
private List<ViewResolver> viewResolvers;
/**
@@ -422,8 +421,7 @@ public class DispatcherServlet extends FrameworkServlet {
*/
private void initMultipartResolver(ApplicationContext context) {
try {
this.multipartResolver = (MultipartResolver)
context.getBean(MULTIPART_RESOLVER_BEAN_NAME, MultipartResolver.class);
this.multipartResolver = context.getBean(MULTIPART_RESOLVER_BEAN_NAME, MultipartResolver.class);
if (logger.isDebugEnabled()) {
logger.debug("Using MultipartResolver [" + this.multipartResolver + "]");
}
@@ -445,15 +443,14 @@ public class DispatcherServlet extends FrameworkServlet {
*/
private void initLocaleResolver(ApplicationContext context) {
try {
this.localeResolver = (LocaleResolver)
context.getBean(LOCALE_RESOLVER_BEAN_NAME, LocaleResolver.class);
this.localeResolver = context.getBean(LOCALE_RESOLVER_BEAN_NAME, LocaleResolver.class);
if (logger.isDebugEnabled()) {
logger.debug("Using LocaleResolver [" + this.localeResolver + "]");
}
}
catch (NoSuchBeanDefinitionException ex) {
// We need to use the default.
this.localeResolver = (LocaleResolver) getDefaultStrategy(context, LocaleResolver.class);
this.localeResolver = getDefaultStrategy(context, LocaleResolver.class);
if (logger.isDebugEnabled()) {
logger.debug("Unable to locate LocaleResolver with name '" + LOCALE_RESOLVER_BEAN_NAME +
"': using default [" + this.localeResolver + "]");
@@ -468,15 +465,14 @@ public class DispatcherServlet extends FrameworkServlet {
*/
private void initThemeResolver(ApplicationContext context) {
try {
this.themeResolver = (ThemeResolver)
context.getBean(THEME_RESOLVER_BEAN_NAME, ThemeResolver.class);
this.themeResolver = context.getBean(THEME_RESOLVER_BEAN_NAME, ThemeResolver.class);
if (logger.isDebugEnabled()) {
logger.debug("Using ThemeResolver [" + this.themeResolver + "]");
}
}
catch (NoSuchBeanDefinitionException ex) {
// We need to use the default.
this.themeResolver = (ThemeResolver) getDefaultStrategy(context, ThemeResolver.class);
this.themeResolver = getDefaultStrategy(context, ThemeResolver.class);
if (logger.isDebugEnabled()) {
logger.debug("Unable to locate ThemeResolver with name '" + THEME_RESOLVER_BEAN_NAME +
"': using default [" + this.themeResolver + "]");
@@ -493,19 +489,18 @@ public class DispatcherServlet extends FrameworkServlet {
this.handlerMappings = null;
if (this.detectAllHandlerMappings) {
// Find all HandlerMappings in the ApplicationContext,
// including ancestor contexts.
Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
// Find all HandlerMappings in the ApplicationContext, including ancestor contexts.
Map<String, HandlerMapping> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
context, HandlerMapping.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerMappings = new ArrayList(matchingBeans.values());
this.handlerMappings = new ArrayList<HandlerMapping>(matchingBeans.values());
// We keep HandlerMappings in sorted order.
Collections.sort(this.handlerMappings, new OrderComparator());
}
}
else {
try {
Object hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class);
HandlerMapping hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class);
this.handlerMappings = Collections.singletonList(hm);
}
catch (NoSuchBeanDefinitionException ex) {
@@ -532,19 +527,18 @@ public class DispatcherServlet extends FrameworkServlet {
this.handlerAdapters = null;
if (this.detectAllHandlerAdapters) {
// Find all HandlerAdapters in the ApplicationContext,
// including ancestor contexts.
Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
// Find all HandlerAdapters in the ApplicationContext, including ancestor contexts.
Map<String, HandlerAdapter> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
context, HandlerAdapter.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerAdapters = new ArrayList(matchingBeans.values());
this.handlerAdapters = new ArrayList<HandlerAdapter>(matchingBeans.values());
// We keep HandlerAdapters in sorted order.
Collections.sort(this.handlerAdapters, new OrderComparator());
}
}
else {
try {
Object ha = context.getBean(HANDLER_ADAPTER_BEAN_NAME, HandlerAdapter.class);
HandlerAdapter ha = context.getBean(HANDLER_ADAPTER_BEAN_NAME, HandlerAdapter.class);
this.handlerAdapters = Collections.singletonList(ha);
}
catch (NoSuchBeanDefinitionException ex) {
@@ -571,19 +565,18 @@ public class DispatcherServlet extends FrameworkServlet {
this.handlerExceptionResolvers = null;
if (this.detectAllHandlerExceptionResolvers) {
// Find all HandlerExceptionResolvers in the ApplicationContext,
// including ancestor contexts.
Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
// Find all HandlerExceptionResolvers in the ApplicationContext, including ancestor contexts.
Map<String, HandlerExceptionResolver> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
context, HandlerExceptionResolver.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerExceptionResolvers = new ArrayList(matchingBeans.values());
this.handlerExceptionResolvers = new ArrayList<HandlerExceptionResolver>(matchingBeans.values());
// We keep HandlerExceptionResolvers in sorted order.
Collections.sort(this.handlerExceptionResolvers, new OrderComparator());
}
}
else {
try {
Object her = context.getBean(
HandlerExceptionResolver her = context.getBean(
HANDLER_EXCEPTION_RESOLVER_BEAN_NAME, HandlerExceptionResolver.class);
this.handlerExceptionResolvers = Collections.singletonList(her);
}
@@ -608,7 +601,7 @@ public class DispatcherServlet extends FrameworkServlet {
*/
private void initRequestToViewNameTranslator(ApplicationContext context) {
try {
this.viewNameTranslator = (RequestToViewNameTranslator) context.getBean(
this.viewNameTranslator = context.getBean(
REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME, RequestToViewNameTranslator.class);
if (logger.isDebugEnabled()) {
logger.debug("Using RequestToViewNameTranslator [" + this.viewNameTranslator + "]");
@@ -616,8 +609,7 @@ public class DispatcherServlet extends FrameworkServlet {
}
catch (NoSuchBeanDefinitionException ex) {
// We need to use the default.
this.viewNameTranslator =
(RequestToViewNameTranslator) getDefaultStrategy(context, RequestToViewNameTranslator.class);
this.viewNameTranslator = getDefaultStrategy(context, RequestToViewNameTranslator.class);
if (logger.isDebugEnabled()) {
logger.debug("Unable to locate RequestToViewNameTranslator with name '" +
REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME +
@@ -635,19 +627,18 @@ public class DispatcherServlet extends FrameworkServlet {
this.viewResolvers = null;
if (this.detectAllViewResolvers) {
// Find all ViewResolvers in the ApplicationContext,
// including ancestor contexts.
Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
// Find all ViewResolvers in the ApplicationContext, including ancestor contexts.
Map<String, ViewResolver> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
context, ViewResolver.class, true, false);
if (!matchingBeans.isEmpty()) {
this.viewResolvers = new ArrayList(matchingBeans.values());
this.viewResolvers = new ArrayList<ViewResolver>(matchingBeans.values());
// We keep ViewResolvers in sorted order.
Collections.sort(this.viewResolvers, new OrderComparator());
}
}
else {
try {
Object vr = context.getBean(VIEW_RESOLVER_BEAN_NAME, ViewResolver.class);
ViewResolver vr = context.getBean(VIEW_RESOLVER_BEAN_NAME, ViewResolver.class);
this.viewResolvers = Collections.singletonList(vr);
}
catch (NoSuchBeanDefinitionException ex) {
@@ -698,11 +689,10 @@ public class DispatcherServlet extends FrameworkServlet {
* @param context the current WebApplicationContext
* @param strategyInterface the strategy interface
* @return the corresponding strategy object
* @throws BeansException if initialization failed
* @see #getDefaultStrategies
*/
protected Object getDefaultStrategy(ApplicationContext context, Class strategyInterface) throws BeansException {
List strategies = getDefaultStrategies(context, strategyInterface);
protected <T> T getDefaultStrategy(ApplicationContext context, Class<T> strategyInterface) {
List<T> strategies = getDefaultStrategies(context, strategyInterface);
if (strategies.size() != 1) {
throw new BeanInitializationException(
"DispatcherServlet needs exactly 1 strategy for interface [" + strategyInterface.getName() + "]");
@@ -718,42 +708,36 @@ public class DispatcherServlet extends FrameworkServlet {
* @param context the current WebApplicationContext
* @param strategyInterface the strategy interface
* @return the List of corresponding strategy objects
* @throws BeansException if initialization failed
*/
protected List getDefaultStrategies(ApplicationContext context, Class strategyInterface) throws BeansException {
@SuppressWarnings("unchecked")
protected <T> List<T> getDefaultStrategies(ApplicationContext context, Class<T> strategyInterface) {
String key = strategyInterface.getName();
List strategies = null;
String value = defaultStrategies.getProperty(key);
if (value != null) {
String[] classNames = StringUtils.commaDelimitedListToStringArray(value);
strategies = new ArrayList(classNames.length);
for (int i = 0; i < classNames.length; i++) {
String className = classNames[i];
if (JdkVersion.getMajorJavaVersion() < JdkVersion.JAVA_15 && className.indexOf("Annotation") != -1) {
// Skip Java 5 specific strategies when running on JDK 1.4...
continue;
}
List<T> strategies = new ArrayList<T>(classNames.length);
for (String className : classNames) {
try {
Class clazz = ClassUtils.forName(className, DispatcherServlet.class.getClassLoader());
Object strategy = createDefaultStrategy(context, clazz);
strategies.add(strategy);
strategies.add((T) strategy);
}
catch (ClassNotFoundException ex) {
throw new BeanInitializationException(
"Could not find DispatcherServlet's default strategy class [" + className +
"] for interface [" + key + "]", ex);
"] for interface [" + key + "]", ex);
}
catch (LinkageError err) {
throw new BeanInitializationException(
"Error loading DispatcherServlet's default strategy class [" + className +
"] for interface [" + key + "]: problem with class file or dependent class", err);
"] for interface [" + key + "]: problem with class file or dependent class", err);
}
}
return strategies;
}
else {
strategies = Collections.EMPTY_LIST;
return new LinkedList<T>();
}
return strategies;
}
/**
@@ -786,10 +770,10 @@ public class DispatcherServlet extends FrameworkServlet {
// Keep a snapshot of the request attributes in case of an include,
// to be able to restore the original attributes after the include.
Map attributesSnapshot = null;
Map<String, Object> attributesSnapshot = null;
if (WebUtils.isIncludeRequest(request)) {
logger.debug("Taking snapshot of request attributes before include");
attributesSnapshot = new HashMap();
attributesSnapshot = new HashMap<String, Object>();
Enumeration attrNames = request.getAttributeNames();
while (attrNames.hasMoreElements()) {
String attrName = (String) attrNames.nextElement();
@@ -1051,12 +1035,10 @@ public class DispatcherServlet extends FrameworkServlet {
return handler;
}
Iterator it = this.handlerMappings.iterator();
while (it.hasNext()) {
HandlerMapping hm = (HandlerMapping) it.next();
for (HandlerMapping hm : this.handlerMappings) {
if (logger.isTraceEnabled()) {
logger.trace("Testing handler map [" + hm + "] in DispatcherServlet with name '" +
getServletName() + "'");
logger.trace(
"Testing handler map [" + hm + "] in DispatcherServlet with name '" + getServletName() + "'");
}
handler = hm.getHandler(request);
if (handler != null) {
@@ -1091,9 +1073,7 @@ public class DispatcherServlet extends FrameworkServlet {
* This is a fatal error.
*/
protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException {
Iterator it = this.handlerAdapters.iterator();
while (it.hasNext()) {
HandlerAdapter ha = (HandlerAdapter) it.next();
for (HandlerAdapter ha : this.handlerAdapters) {
if (logger.isTraceEnabled()) {
logger.trace("Testing handler adapter [" + ha + "]");
}
@@ -1214,8 +1194,7 @@ public class DispatcherServlet extends FrameworkServlet {
protected View resolveViewName(String viewName, Map model, Locale locale, HttpServletRequest request)
throws Exception {
for (Iterator it = this.viewResolvers.iterator(); it.hasNext();) {
ViewResolver viewResolver = (ViewResolver) it.next();
for (ViewResolver viewResolver : this.viewResolvers) {
View view = viewResolver.resolveViewName(viewName, locale);
if (view != null) {
return view;
@@ -1266,7 +1245,7 @@ public class DispatcherServlet extends FrameworkServlet {
// Need to copy into separate Collection here, to avoid side effects
// on the Enumeration when removing attributes.
Set attrsToCheck = new HashSet();
Set<String> attrsToCheck = new HashSet<String>();
Enumeration attrNames = request.getAttributeNames();
while (attrNames.hasMoreElements()) {
String attrName = (String) attrNames.nextElement();
@@ -1277,8 +1256,7 @@ public class DispatcherServlet extends FrameworkServlet {
// Iterate over the attributes to check, restoring the original value
// or removing the attribute, respectively, if appropriate.
for (Iterator it = attrsToCheck.iterator(); it.hasNext();) {
String attrName = (String) it.next();
for (String attrName : attrsToCheck) {
Object attrValue = attributesSnapshot.get(attrName);
if (attrValue != null) {
if (logger.isDebugEnabled()) {

View File

@@ -11,7 +11,6 @@ org.springframework.web.servlet.HandlerMapping=org.springframework.web.servlet.h
org.springframework.web.servlet.HandlerAdapter=org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,\
org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,\
org.springframework.web.servlet.mvc.throwaway.ThrowawayControllerHandlerAdapter,\
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter
org.springframework.web.servlet.RequestToViewNameTranslator=org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* 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.
@@ -17,10 +17,9 @@
package org.springframework.web.servlet.mvc;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.http.HttpServletRequest;
import org.springframework.core.CollectionFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerMapping;
@@ -55,7 +54,7 @@ public class UrlFilenameViewController extends AbstractUrlViewController {
private String suffix = "";
/** Request URL path String --> view name String */
private final Map viewNameCache = CollectionFactory.createConcurrentMapIfPossible(16);
private final Map<String, String> viewNameCache = new ConcurrentHashMap<String, String>();
/**
@@ -125,7 +124,7 @@ public class UrlFilenameViewController extends AbstractUrlViewController {
* @see #postProcessViewName
*/
protected String getViewNameForUrlPath(String uri) {
String viewName = (String) this.viewNameCache.get(uri);
String viewName = this.viewNameCache.get(uri);
if (viewName == null) {
viewName = extractViewNameFromUrlPath(uri);
viewName = postProcessViewName(viewName);

View File

@@ -654,10 +654,9 @@ public class AnnotationMethodHandlerAdapter extends WebContentGenerator implemen
@Override
@SuppressWarnings({"unchecked"})
protected Object resolvePathVariable(String pathVarName,
MethodParameter methodParam,
NativeWebRequest webRequest,
Object handlerForInitBinderCall) throws Exception {
protected Object resolvePathVariable(String pathVarName, MethodParameter methodParam,
NativeWebRequest webRequest, Object handlerForInitBinderCall) throws Exception {
Class paramType = methodParam.getParameterType();
if (pathVarName.length() == 0) {
pathVarName = methodParam.getParameterName();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* 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.
@@ -17,8 +17,8 @@
package org.springframework.web.servlet.mvc.multiaction;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.core.CollectionFactory;
import org.springframework.web.util.WebUtils;
/**
@@ -43,7 +43,7 @@ public class InternalPathMethodNameResolver extends AbstractUrlMethodNameResolve
private String suffix = "";
/** Request URL path String --> method name String */
private final Map methodNameCache = CollectionFactory.createConcurrentMapIfPossible(16);
private final Map<String, String> methodNameCache = new ConcurrentHashMap<String, String>();
/**
@@ -86,7 +86,7 @@ public class InternalPathMethodNameResolver extends AbstractUrlMethodNameResolve
*/
@Override
protected String getHandlerMethodNameForUrlPath(String urlPath) {
String methodName = (String) this.methodNameCache.get(urlPath);
String methodName = this.methodNameCache.get(urlPath);
if (methodName == null) {
methodName = extractHandlerMethodNameFromUrlPath(urlPath);
methodName = postProcessHandlerMethodName(methodName);

View File

@@ -19,11 +19,8 @@ package org.springframework.web.servlet.mvc.support;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.springframework.core.JdkVersion;
import org.springframework.util.ClassUtils;
import org.springframework.web.servlet.handler.AbstractDetectingUrlHandlerMapping;
/**
@@ -37,32 +34,19 @@ import org.springframework.web.servlet.handler.AbstractDetectingUrlHandlerMappin
*/
public abstract class AbstractControllerUrlHandlerMapping extends AbstractDetectingUrlHandlerMapping {
private static final String ANNOTATION_PREDICATE_NAME =
"org.springframework.web.servlet.mvc.support.AnnotationControllerTypePredicate";
private ControllerTypePredicate predicate = new AnnotationControllerTypePredicate();
private ControllerTypePredicate predicate;
private Set<String> excludedPackages = Collections.singleton("org.springframework.web.servlet.mvc");
private Set excludedPackages = Collections.singleton("org.springframework.web.servlet.mvc");
private Set excludedClasses = Collections.EMPTY_SET;
/**
* Activates detection of annotated controllers when running on JDK 1.5 or higher.
*/
public AbstractControllerUrlHandlerMapping() {
this.predicate = (JdkVersion.isAtLeastJava15() ?
instantiateAnnotationPredicate() : new ControllerTypePredicate());
}
private Set<Class> excludedClasses = Collections.emptySet();
/**
* Set whether to activate or deactivate detection of annotated controllers.
* <p>Annotated controllers will by included by default when runnong on JDK 1.5 or higher.
*/
public void setIncludeAnnotatedControllers(boolean includeAnnotatedControllers) {
this.predicate = (includeAnnotatedControllers ?
instantiateAnnotationPredicate() : new ControllerTypePredicate());
new AnnotationControllerTypePredicate() : new ControllerTypePredicate());
}
/**
@@ -77,8 +61,8 @@ public abstract class AbstractControllerUrlHandlerMapping extends AbstractDetect
* alongside this ControllerClassNameHandlerMapping for application controllers.
*/
public void setExcludedPackages(String[] excludedPackages) {
this.excludedPackages =
(excludedPackages != null ? new HashSet(Arrays.asList(excludedPackages)) : Collections.EMPTY_SET);
this.excludedPackages = (excludedPackages != null) ?
new HashSet<String>(Arrays.asList(excludedPackages)) : new HashSet<String>();
}
/**
@@ -86,19 +70,8 @@ public abstract class AbstractControllerUrlHandlerMapping extends AbstractDetect
* Any such classes will simply be ignored by this HandlerMapping.
*/
public void setExcludedClasses(Class[] excludedClasses) {
this.excludedClasses =
(excludedClasses != null ? new HashSet(Arrays.asList(excludedClasses)) : Collections.EMPTY_SET);
}
private ControllerTypePredicate instantiateAnnotationPredicate() {
try {
return (ControllerTypePredicate) ClassUtils.forName(ANNOTATION_PREDICATE_NAME,
AbstractControllerUrlHandlerMapping.class.getClassLoader()).newInstance();
}
catch (Exception ex) {
throw new IllegalStateException("Cannot load AnnotationControllerTypePredicate", ex);
}
this.excludedClasses = (excludedClasses != null) ?
new HashSet<Class>(Arrays.asList(excludedClasses)) : new HashSet<Class>();
}
@@ -141,8 +114,7 @@ public abstract class AbstractControllerUrlHandlerMapping extends AbstractDetect
return false;
}
String beanClassName = beanClass.getName();
for (Iterator it = this.excludedPackages.iterator(); it.hasNext();) {
String packageName = (String) it.next();
for (String packageName : this.excludedPackages) {
if (beanClassName.startsWith(packageName)) {
if (logger.isDebugEnabled()) {
logger.debug("Excluding controller bean '" + beanName + "' from class name mapping " +

View File

@@ -18,7 +18,6 @@ package org.springframework.web.servlet.mvc.support;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import org.springframework.web.servlet.mvc.throwaway.ThrowawayController;
/**
* Internal helper class that identifies controller types.
@@ -29,12 +28,11 @@ import org.springframework.web.servlet.mvc.throwaway.ThrowawayController;
class ControllerTypePredicate {
public boolean isControllerType(Class beanClass) {
return (Controller.class.isAssignableFrom(beanClass) ||
ThrowawayController.class.isAssignableFrom(beanClass));
return Controller.class.isAssignableFrom(beanClass);
}
public boolean isMultiActionControllerType(Class beanClass) {
return (MultiActionController.class.isAssignableFrom(beanClass));
return MultiActionController.class.isAssignableFrom(beanClass);
}
}

View File

@@ -1,70 +0,0 @@
/*
* 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.mvc.throwaway;
import org.springframework.web.servlet.ModelAndView;
/**
* ThrowawayController is an alternative to Spring's default Controller interface,
* for executable per-request command instances that are not aware of the Servlet API.
* In contrast to Controller, implementing beans are not supposed to be defined as
* Servlet/Struts-style singletons that process a HttpServletRequest but rather as
* WebWork/Maverick-style prototypes that get populated with request parameters,
* executed to determine a view, and thrown away afterwards.
*
* <p>The main advantage of this controller programming model is that controllers
* are testable without HttpServletRequest/HttpServletResponse mocks, just like
* WebWork actions. They are still web UI workflow controllers: Spring does not
* aim for the arguably hard-to-achieve reusability of such controllers in non-web
* environments, as XWork (the generic command framework from WebWork2) does
* but just for ease of testing.
*
* <p>A ThrowawayController differs from the command notion of Base- or
* AbstractCommandController in that a ThrowawayController is an <i>executable</i>
* command that contains workflow logic to determine the next view to render,
* while BaseCommandController treats commands as plain parameter holders.
*
* <p>If binding request parameters to this controller fails, a fatal BindException
* will be thrown.
*
* <p>If you need access to the HttpServletRequest and/or HttpServletResponse,
* consider implementing Controller or deriving from AbstractCommandController.
* ThrowawayController is specifically intended for controllers that are not aware
* of the Servlet API at all. Accordingly, if you need to handle session form objects
* or even wizard forms, consider the corresponding Controller subclasses.
*
* @author Juergen Hoeller
* @since 08.12.2003
* @see org.springframework.web.servlet.mvc.Controller
* @see org.springframework.web.servlet.mvc.AbstractCommandController
* @deprecated as of Spring 2.5, in favor of annotation-based controllers.
* To be removed in Spring 3.0.
*/
@Deprecated
public interface ThrowawayController {
/**
* Execute this controller according to its bean properties.
* Gets invoked after a new instance of the controller has been populated with request
* parameters. Is supposed to return a ModelAndView in any case, as it is not able to
* generate a response itself.
* @return a ModelAndView to render
* @throws Exception in case of errors
*/
ModelAndView execute() throws Exception;
}

View File

@@ -1,135 +0,0 @@
/*
* 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.mvc.throwaway;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.ModelAndView;
/**
* Adapter to use the ThrowawayController workflow interface with the
* generic DispatcherServlet. Does not support last-modified checks.
*
* <p>This is an SPI class, not used directly by application code.
* It can be explicitly configured in a DispatcherServlet context, to use a
* customized version instead of the default ThrowawayControllerHandlerAdapter.
*
* @author Juergen Hoeller
* @since 08.12.2003
* @deprecated as of Spring 2.5, in favor of annotation-based controllers.
* To be removed in Spring 3.0.
*/
@Deprecated
public class ThrowawayControllerHandlerAdapter implements HandlerAdapter {
public static final String DEFAULT_COMMAND_NAME = "throwawayController";
private String commandName = DEFAULT_COMMAND_NAME;
/**
* Set the name of the command in the model.
* The command object will be included in the model under this name.
*/
public final void setCommandName(String commandName) {
this.commandName = commandName;
}
/**
* Return the name of the command in the model.
*/
public final String getCommandName() {
return this.commandName;
}
public boolean supports(Object handler) {
return (handler instanceof ThrowawayController);
}
/**
* This implementation binds request parameters to the ThrowawayController
* instance and then calls <code>execute</code> on it.
* @see #createBinder
* @see ThrowawayController#execute
*/
public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
ThrowawayController throwaway = (ThrowawayController) handler;
ServletRequestDataBinder binder = createBinder(request, throwaway);
binder.bind(request);
binder.closeNoCatch();
return throwaway.execute();
}
/**
* Create a new binder instance for the given command and request.
* <p>Called by <code>bindAndValidate</code>. Can be overridden to plug in
* custom ServletRequestDataBinder subclasses.
* <p>Default implementation creates a standard ServletRequestDataBinder,
* sets the specified MessageCodesResolver (if any), and invokes initBinder.
* Note that <code>initBinder</code> will not be invoked if you override this method!
* @param request current HTTP request
* @param command the command to bind onto
* @return the new binder instance
* @throws Exception in case of invalid state or arguments
* @see #initBinder
* @see #getCommandName
*/
protected ServletRequestDataBinder createBinder(HttpServletRequest request, ThrowawayController command)
throws Exception {
ServletRequestDataBinder binder = new ServletRequestDataBinder(command, getCommandName());
initBinder(request, binder);
return binder;
}
/**
* Initialize the given binder instance, for example with custom editors.
* Called by <code>createBinder</code>.
* <p>This method allows you to register custom editors for certain fields of your
* command class. For instance, you will be able to transform Date objects into a
* String pattern and back, in order to allow your JavaBeans to have Date properties
* and still be able to set and display them in an HTML interface.
* <p>Default implementation is empty.
* @param request current HTTP request
* @param binder new binder instance
* @throws Exception in case of invalid state or arguments
* @see #createBinder
* @see org.springframework.validation.DataBinder#registerCustomEditor
* @see org.springframework.beans.propertyeditors.CustomDateEditor
*/
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder)
throws Exception {
}
/**
* This implementation always returns -1, as last-modified checks are not supported.
*/
public long getLastModified(HttpServletRequest request, Object handler) {
return -1;
}
}

View File

@@ -1,8 +0,0 @@
<html>
<body>
Throwaway command controllers are a WebWork/Maverick-style alternative
to Spring's default Servlet/Struts-style Controller approach.
</body>
</html>

View File

@@ -19,10 +19,8 @@ package org.springframework.web.servlet.tags.form;
import java.beans.PropertyEditor;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.springframework.core.JdkVersion;
import org.springframework.core.enums.LabeledEnum;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
@@ -134,14 +132,13 @@ abstract class SelectedValueComparator {
private static boolean exhaustiveCollectionCompare(
Collection collection, Object candidateValue, BindStatus bindStatus) {
Map convertedValueCache = new HashMap(1);
Map<PropertyEditor, Object> convertedValueCache = new HashMap<PropertyEditor, Object>(1);
PropertyEditor editor = null;
boolean candidateIsString = (candidateValue instanceof String);
if (!candidateIsString) {
editor = bindStatus.findEditor(candidateValue.getClass());
}
for (Iterator it = collection.iterator(); it.hasNext();) {
Object element = it.next();
for (Object element : collection) {
if (editor == null && element != null && candidateIsString) {
editor = bindStatus.findEditor(element.getClass());
}
@@ -152,8 +149,8 @@ abstract class SelectedValueComparator {
return false;
}
private static boolean exhaustiveCompare(
Object boundValue, Object candidate, PropertyEditor editor, Map convertedValueCache) {
private static boolean exhaustiveCompare(Object boundValue, Object candidate,
PropertyEditor editor, Map<PropertyEditor, Object> convertedValueCache) {
String candidateDisplayString = ValueFormatter.getDisplayString(candidate, editor, false);
if (boundValue instanceof LabeledEnum) {
@@ -167,7 +164,7 @@ abstract class SelectedValueComparator {
return true;
}
}
else if (JdkVersion.isAtLeastJava15() && boundValue.getClass().isEnum()) {
else if (boundValue.getClass().isEnum()) {
Enum boundEnum = (Enum) boundValue;
String enumCodeAsString = ObjectUtils.getDisplayString(boundEnum.name());
if (enumCodeAsString.equals(candidateDisplayString)) {

View File

@@ -18,13 +18,11 @@ package org.springframework.web.servlet.view;
import java.util.Enumeration;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.util.ClassUtils;
import org.springframework.web.servlet.support.RequestContext;
/**
@@ -54,12 +52,6 @@ public abstract class AbstractTemplateView extends AbstractUrlBasedView {
public static final String SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE = "springMacroRequestContext";
// Determine whether the Servlet 2.4 HttpServletResponse.getContentType()
// method is available.
private static boolean responseGetContentTypeAvailable =
ClassUtils.hasMethod(HttpServletResponse.class, "getContentType", new Class[0]);
private boolean exposeRequestAttributes = false;
private boolean allowRequestOverride = false;
@@ -185,18 +177,7 @@ public abstract class AbstractTemplateView extends AbstractUrlBasedView {
* @see #setContentType
*/
protected void applyContentType(HttpServletResponse response) {
boolean apply = true;
if (responseGetContentTypeAvailable) {
try {
apply = (response.getContentType() == null);
}
catch (Throwable ex) {
// Probably Servlet 2.4 API present but not implemented.
// Behave like on Servlet 2.3...
apply = true;
}
}
if (apply) {
if (response.getContentType() == null) {
response.setContentType(getContentType());
}
}

View File

@@ -26,7 +26,6 @@ import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
@@ -797,9 +796,7 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView {
return provider.create(report);
}
catch (JRException ex) {
IllegalArgumentException iaex = new IllegalArgumentException("Supplied JRDataSourceProvider is invalid");
iaex.initCause(ex);
throw iaex;
throw new IllegalArgumentException("Supplied JRDataSourceProvider is invalid", ex);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* 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.
@@ -17,13 +17,13 @@
package org.springframework.web.servlet.view.tiles2;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.tiles.TilesException;
import org.apache.tiles.preparer.NoSuchPreparerException;
import org.apache.tiles.preparer.PreparerException;
import org.apache.tiles.preparer.ViewPreparer;
import org.springframework.core.CollectionFactory;
import org.springframework.web.context.WebApplicationContext;
/**
@@ -39,16 +39,16 @@ import org.springframework.web.context.WebApplicationContext;
public class SimpleSpringPreparerFactory extends AbstractSpringPreparerFactory {
/** Cache of shared ViewPreparer instances: bean name --> bean instance */
private final Map sharedPreparers = CollectionFactory.createConcurrentMapIfPossible(16);
private final Map<String, ViewPreparer> sharedPreparers = new ConcurrentHashMap<String, ViewPreparer>();
@Override
protected ViewPreparer getPreparer(String name, WebApplicationContext context) throws TilesException {
// Quick check on the concurrent map first, with minimal locking.
ViewPreparer preparer = (ViewPreparer) this.sharedPreparers.get(name);
ViewPreparer preparer = this.sharedPreparers.get(name);
if (preparer == null) {
synchronized (this.sharedPreparers) {
preparer = (ViewPreparer) this.sharedPreparers.get(name);
preparer = this.sharedPreparers.get(name);
if (preparer == null) {
try {
Class beanClass = context.getClassLoader().loadClass(name);