Broadly remove deprecated core classes and methods

Issue: SPR-14430
This commit is contained in:
Juergen Hoeller
2016-07-05 15:52:48 +02:00
parent 0fc0ce78ae
commit b5db5d3aac
119 changed files with 145 additions and 6086 deletions

View File

@@ -66,14 +66,13 @@ public class ViewResolversBeanDefinitionParser implements BeanDefinitionParser {
public static final String VIEW_RESOLVER_BEAN_NAME = "mvcViewResolver";
@SuppressWarnings("deprecation")
public BeanDefinition parse(Element element, ParserContext context) {
Object source = context.extractSource(element);
context.pushContainingComponent(new CompositeComponentDefinition(element.getTagName(), source));
ManagedList<Object> resolvers = new ManagedList<Object>(4);
resolvers.setSource(context.extractSource(element));
String[] names = new String[] {"jsp", "tiles", "bean-name", "freemarker", "velocity", "groovy", "script-template", "bean", "ref"};
String[] names = new String[] {"jsp", "tiles", "bean-name", "freemarker", "groovy", "script-template", "bean", "ref"};
for (Element resolverElement : DomUtils.getChildElementsByTagName(element, names)) {
String name = resolverElement.getLocalName();
@@ -81,7 +80,7 @@ public class ViewResolversBeanDefinitionParser implements BeanDefinitionParser {
resolvers.add(context.getDelegate().parsePropertySubElement(resolverElement, null));
continue;
}
RootBeanDefinition resolverBeanDef = null;
RootBeanDefinition resolverBeanDef;
if ("jsp".equals(name)) {
resolverBeanDef = new RootBeanDefinition(InternalResourceViewResolver.class);
resolverBeanDef.getPropertyValues().add("prefix", "/WEB-INF/");

View File

@@ -381,17 +381,6 @@ public class MvcUriComponentsBuilder {
(controllerType != null ? controllerType : method.getDeclaringClass()), method, args);
}
/**
* @see #fromMethod(Class, Method, Object...)
* @see #fromMethod(UriComponentsBuilder, Class, Method, Object...)
* @deprecated as of 4.2, this is deprecated in favor of the overloaded
* method that also accepts a controllerType argument
*/
@Deprecated
public static UriComponentsBuilder fromMethod(Method method, Object... args) {
return fromMethodInternal(null, method.getDeclaringClass(), method, args);
}
private static UriComponentsBuilder fromMethodInternal(UriComponentsBuilder baseUrl,
Class<?> controllerType, Method method, Object... args) {
@@ -777,15 +766,6 @@ public class MvcUriComponentsBuilder {
}
}
/**
* @deprecated as of 4.2, this is deprecated in favor of alternative constructors
* that accept a controllerType argument
*/
@Deprecated
public MethodArgumentBuilder(Method method) {
this(method.getDeclaringClass(), method);
}
private static UriComponentsBuilder initBaseUrl() {
UriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentServletMapping();
return UriComponentsBuilder.fromPath(builder.build().getPath());

View File

@@ -98,9 +98,7 @@ public abstract class ResponseEntityExceptionHandler {
* @param ex the target exception
* @param request the current request
*/
@SuppressWarnings("deprecation")
@ExceptionHandler({
org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException.class,
HttpRequestMethodNotSupportedException.class,
HttpMediaTypeNotSupportedException.class,
HttpMediaTypeNotAcceptableException.class,
@@ -118,11 +116,7 @@ public abstract class ResponseEntityExceptionHandler {
})
public final ResponseEntity<Object> handleException(Exception ex, WebRequest request) {
HttpHeaders headers = new HttpHeaders();
if (ex instanceof org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException) {
HttpStatus status = HttpStatus.NOT_FOUND;
return handleNoSuchRequestHandlingMethod((org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException) ex, headers, status, request);
}
else if (ex instanceof HttpRequestMethodNotSupportedException) {
if (ex instanceof HttpRequestMethodNotSupportedException) {
HttpStatus status = HttpStatus.METHOD_NOT_ALLOWED;
return handleHttpRequestMethodNotSupported((HttpRequestMethodNotSupportedException) ex, headers, status, request);
}
@@ -205,25 +199,6 @@ public abstract class ResponseEntityExceptionHandler {
return new ResponseEntity<Object>(body, headers, status);
}
/**
* Customize the response for NoSuchRequestHandlingMethodException.
* <p>This method logs a warning and delegates to {@link #handleExceptionInternal}.
* @param ex the exception
* @param headers the headers to be written to the response
* @param status the selected response status
* @param request the current request
* @return a {@code ResponseEntity} instance
* @deprecated as of 4.3, along with {@link org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException}
*/
@Deprecated
protected ResponseEntity<Object> handleNoSuchRequestHandlingMethod(org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
pageNotFoundLogger.warn(ex.getMessage());
return handleExceptionInternal(ex, null, headers, status, request);
}
/**
* Customize the response for HttpRequestMethodNotSupportedException.
* <p>This method logs a warning, sets the "Allow" header, and delegates to

View File

@@ -1,118 +0,0 @@
/*
* Copyright 2002-2012 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.multiaction;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
import org.springframework.web.util.UrlPathHelper;
/**
* Abstract base class for URL-based {@link MethodNameResolver} implementations.
*
* <p>Provides infrastructure for mapping handlers to URLs and configurable
* URL lookup. For information on the latter, see the
* {@link #setAlwaysUseFullPath} "alwaysUseFullPath"}
* and {@link #setUrlDecode "urlDecode"} properties.
*
* @author Juergen Hoeller
* @since 14.01.2004
* @deprecated as of 4.3, in favor of annotation-driven handler methods
*/
@Deprecated
public abstract class AbstractUrlMethodNameResolver implements MethodNameResolver {
/** Logger available to subclasses */
protected final Log logger = LogFactory.getLog(getClass());
private UrlPathHelper urlPathHelper = new UrlPathHelper();
/**
* Set if URL lookup should always use full path within current servlet
* context. Else, the path within the current servlet mapping is used
* if applicable (i.e. in the case of a ".../*" servlet mapping in web.xml).
* Default is "false".
* @see org.springframework.web.util.UrlPathHelper#setAlwaysUseFullPath
*/
public void setAlwaysUseFullPath(boolean alwaysUseFullPath) {
this.urlPathHelper.setAlwaysUseFullPath(alwaysUseFullPath);
}
/**
* Set if context path and request URI should be URL-decoded.
* Both are returned <i>undecoded</i> by the Servlet API,
* in contrast to the servlet path.
* <p>Uses either the request encoding or the default encoding according
* to the Servlet spec (ISO-8859-1).
* @see org.springframework.web.util.UrlPathHelper#setUrlDecode
*/
public void setUrlDecode(boolean urlDecode) {
this.urlPathHelper.setUrlDecode(urlDecode);
}
/**
* Set the UrlPathHelper to use for resolution of lookup paths.
* <p>Use this to override the default UrlPathHelper with a custom subclass,
* or to share common UrlPathHelper settings across multiple MethodNameResolvers
* and HandlerMappings.
* @see org.springframework.web.servlet.handler.AbstractUrlHandlerMapping#setUrlPathHelper
*/
public void setUrlPathHelper(UrlPathHelper urlPathHelper) {
Assert.notNull(urlPathHelper, "UrlPathHelper must not be null");
this.urlPathHelper = urlPathHelper;
}
/**
* Retrieves the URL path to use for lookup and delegates to
* {@code getHandlerMethodNameForUrlPath}.
* Converts {@code null} values to NoSuchRequestHandlingMethodExceptions.
* @see #getHandlerMethodNameForUrlPath
*/
@Override
public final String getHandlerMethodName(HttpServletRequest request)
throws NoSuchRequestHandlingMethodException {
String urlPath = this.urlPathHelper.getLookupPathForRequest(request);
String name = getHandlerMethodNameForUrlPath(urlPath);
if (name == null) {
throw new NoSuchRequestHandlingMethodException(urlPath, request.getMethod(), request.getParameterMap());
}
if (logger.isDebugEnabled()) {
logger.debug("Returning handler method name '" + name + "' for lookup path: " + urlPath);
}
return name;
}
/**
* Return a method name that can handle this request, based on the
* given lookup path. Called by {@code getHandlerMethodName}.
* @param urlPath the URL path to use for lookup,
* according to the settings in this class
* @return a method name that can handle this request.
* Should return null if no matching method found.
* @see #getHandlerMethodName
* @see #setAlwaysUseFullPath
* @see #setUrlDecode
*/
protected abstract String getHandlerMethodNameForUrlPath(String urlPath);
}

View File

@@ -1,126 +0,0 @@
/*
* Copyright 2002-2012 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.multiaction;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.web.util.WebUtils;
/**
* Simple implementation of {@link MethodNameResolver} that maps URL to
* method name. Although this is the default implementation used by the
* {@link MultiActionController} class (because it requires no configuration),
* it's bit naive for most applications. In particular, we don't usually
* want to tie URL to implementation methods.
*
* <p>Maps the resource name after the last slash, ignoring an extension.
* E.g. "/foo/bar/baz.html" to "baz", assuming a "/foo/bar/baz.html"
* controller mapping to the corresponding MultiActionController handler.
* method. Doesn't support wildcards.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @deprecated as of 4.3, in favor of annotation-driven handler methods
*/
@Deprecated
public class InternalPathMethodNameResolver extends AbstractUrlMethodNameResolver {
private String prefix = "";
private String suffix = "";
/** Request URL path String --> method name String */
private final Map<String, String> methodNameCache = new ConcurrentHashMap<String, String>(16);
/**
* Specify a common prefix for handler method names.
* Will be prepended to the internal path found in the URL:
* e.g. internal path "baz", prefix "my" -> method name "mybaz".
*/
public void setPrefix(String prefix) {
this.prefix = (prefix != null ? prefix : "");
}
/**
* Return the common prefix for handler method names.
*/
protected String getPrefix() {
return this.prefix;
}
/**
* Specify a common suffix for handler method names.
* Will be appended to the internal path found in the URL:
* e.g. internal path "baz", suffix "Handler" -> method name "bazHandler".
*/
public void setSuffix(String suffix) {
this.suffix = (suffix != null ? suffix : "");
}
/**
* Return the common suffix for handler method names.
*/
protected String getSuffix() {
return this.suffix;
}
/**
* Extracts the method name indicated by the URL path.
* @see #extractHandlerMethodNameFromUrlPath
* @see #postProcessHandlerMethodName
*/
@Override
protected String getHandlerMethodNameForUrlPath(String urlPath) {
String methodName = this.methodNameCache.get(urlPath);
if (methodName == null) {
methodName = extractHandlerMethodNameFromUrlPath(urlPath);
methodName = postProcessHandlerMethodName(methodName);
this.methodNameCache.put(urlPath, methodName);
}
return methodName;
}
/**
* Extract the handler method name from the given request URI.
* Delegates to {@code WebUtils.extractFilenameFromUrlPath(String)}.
* @param uri the request URI (e.g. "/index.html")
* @return the extracted URI filename (e.g. "index")
* @see org.springframework.web.util.WebUtils#extractFilenameFromUrlPath
*/
protected String extractHandlerMethodNameFromUrlPath(String uri) {
return WebUtils.extractFilenameFromUrlPath(uri);
}
/**
* Build the full handler method name based on the given method name
* as indicated by the URL path.
* <p>The default implementation simply applies prefix and suffix.
* This can be overridden, for example, to manipulate upper case
* / lower case, etc.
* @param methodName the original method name, as indicated by the URL path
* @return the full method name to use
* @see #getPrefix()
* @see #getSuffix()
*/
protected String postProcessHandlerMethodName(String methodName) {
return getPrefix() + methodName + getSuffix();
}
}

View File

@@ -1,47 +0,0 @@
/*
* Copyright 2002-2012 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.multiaction;
import javax.servlet.http.HttpServletRequest;
/**
* Interface that parameterizes the MultiActionController class
* using the <b>Strategy</b> GoF Design pattern, allowing
* the mapping from incoming request to handler method name
* to be varied without affecting other application code.
*
* <p>Illustrates how delegation can be more flexible than subclassing.
*
* @author Rod Johnson
* @see MultiActionController#setMethodNameResolver
* @deprecated as of 4.3, in favor of annotation-driven handler methods
*/
@Deprecated
public interface MethodNameResolver {
/**
* Return a method name that can handle this request. Such
* mappings are typically, but not necessarily, based on URL.
* @param request current HTTP request
* @return a method name that can handle this request.
* Never returns {@code null}; throws exception if not resolvable.
* @throws NoSuchRequestHandlingMethodException if no handler method
* can be found for the given request
*/
String getHandlerMethodName(HttpServletRequest request) throws NoSuchRequestHandlingMethodException;
}

View File

@@ -1,657 +0,0 @@
/*
* Copyright 2002-2015 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.multiaction;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import org.springframework.web.HttpSessionRequiredException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.servlet.mvc.LastModified;
/**
* {@link org.springframework.web.servlet.mvc.Controller Controller}
* implementation that allows multiple request types to be handled by the same
* class. Subclasses of this class can handle several different types of
* request with methods of the form
*
* <pre class="code">public (ModelAndView | Map | String | void) actionName(HttpServletRequest request, HttpServletResponse response, [,HttpSession] [,AnyObject]);</pre>
*
* A Map return value indicates a model that is supposed to be passed to a default view
* (determined through a {@link org.springframework.web.servlet.RequestToViewNameTranslator}).
* A String return value indicates the name of a view to be rendered without a specific model.
*
* <p>May take a third parameter (of type {@link HttpSession}) in which an
* existing session will be required, or a third parameter of an arbitrary
* class that gets treated as the command (that is, an instance of the class
* gets created, and request parameters get bound to it)
*
* <p>These methods can throw any kind of exception, but should only let
* propagate those that they consider fatal, or which their class or superclass
* is prepared to catch by implementing an exception handler.
*
* <p>When returning just a {@link Map} instance view name translation will be
* used to generate the view name. The configured
* {@link org.springframework.web.servlet.RequestToViewNameTranslator} will be
* used to determine the view name.
*
* <p>When returning {@code void} a return value of {@code null} is
* assumed meaning that the handler method is responsible for writing the
* response directly to the supplied {@link HttpServletResponse}.
*
* <p>This model allows for rapid coding, but loses the advantage of
* compile-time checking. It is similar to a Struts {@code DispatchAction},
* but more sophisticated. Also supports delegation to another object.
*
* <p>An implementation of the {@link MethodNameResolver} interface defined in
* this package should return a method name for a given request, based on any
* aspect of the request, such as its URL or an "action" parameter. The actual
* strategy can be configured via the "methodNameResolver" bean property, for
* each {@code MultiActionController}.
*
* <p>The default {@code MethodNameResolver} is
* {@link InternalPathMethodNameResolver}; further included strategies are
* {@link PropertiesMethodNameResolver} and {@link ParameterMethodNameResolver}.
*
* <p>Subclasses can implement custom exception handler methods with names such
* as:
*
* <pre class="code">public ModelAndView anyMeaningfulName(HttpServletRequest request, HttpServletResponse response, ExceptionClass exception);</pre>
*
* The third parameter can be any subclass or {@link Exception} or
* {@link RuntimeException}.
*
* <p>There can also be an optional {@code xxxLastModified} method for
* handlers, of signature:
*
* <pre class="code">public long anyMeaningfulNameLastModified(HttpServletRequest request)</pre>
*
* If such a method is present, it will be invoked. Default return from
* {@code getLastModified} is -1, meaning that the content must always be
* regenerated.
*
* <p><b>Note that all handler methods need to be public and that
* method overloading is <i>not</i> allowed.</b>
*
* <p>See also the description of the workflow performed by
* {@link AbstractController the superclass} (in that section of the class
* level Javadoc entitled 'workflow').
*
* <p><b>Note:</b> For maximum data binding flexibility, consider direct usage of a
* {@link ServletRequestDataBinder} in your controller method, instead of relying
* on a declared command argument. This allows for full control over the entire
* binder setup and usage, including the invocation of {@link Validator Validators}
* and the subsequent evaluation of binding/validation errors.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Colin Sampaleanu
* @author Rob Harrop
* @author Sam Brannen
* @see MethodNameResolver
* @see InternalPathMethodNameResolver
* @see PropertiesMethodNameResolver
* @see ParameterMethodNameResolver
* @see org.springframework.web.servlet.mvc.LastModified#getLastModified
* @see org.springframework.web.bind.ServletRequestDataBinder
* @deprecated as of 4.3, in favor of annotation-driven handler methods
*/
@Deprecated
public class MultiActionController extends AbstractController implements LastModified {
/** Suffix for last-modified methods */
public static final String LAST_MODIFIED_METHOD_SUFFIX = "LastModified";
/** Default command name used for binding command objects: "command" */
public static final String DEFAULT_COMMAND_NAME = "command";
/**
* Log category to use when no mapped handler is found for a request.
* @see #pageNotFoundLogger
*/
public static final String PAGE_NOT_FOUND_LOG_CATEGORY = "org.springframework.web.servlet.PageNotFound";
/**
* Additional logger to use when no mapped handler is found for a request.
* @see #PAGE_NOT_FOUND_LOG_CATEGORY
*/
protected static final Log pageNotFoundLogger = LogFactory.getLog(PAGE_NOT_FOUND_LOG_CATEGORY);
/** Object we'll invoke methods on. Defaults to this. */
private Object delegate;
/** Delegate that knows how to determine method names from incoming requests */
private MethodNameResolver methodNameResolver = new InternalPathMethodNameResolver();
/** List of Validators to apply to commands */
private Validator[] validators;
/** Optional strategy for pre-initializing data binding */
private WebBindingInitializer webBindingInitializer;
/** Handler methods, keyed by name */
private final Map<String, Method> handlerMethodMap = new HashMap<String, Method>();
/** LastModified methods, keyed by handler method name (without LAST_MODIFIED_SUFFIX) */
private final Map<String, Method> lastModifiedMethodMap = new HashMap<String, Method>();
/** Methods, keyed by exception class */
private final Map<Class<?>, Method> exceptionHandlerMap = new HashMap<Class<?>, Method>();
/**
* Constructor for {@code MultiActionController} that looks for
* handler methods in the present subclass.
*/
public MultiActionController() {
this.delegate = this;
registerHandlerMethods(this.delegate);
// We'll accept no handler methods found here - a delegate might be set later on.
}
/**
* Constructor for {@code MultiActionController} that looks for
* handler methods in delegate, rather than a subclass of this class.
* @param delegate handler object. This does not need to implement any
* particular interface, as everything is done using reflection.
*/
public MultiActionController(Object delegate) {
setDelegate(delegate);
}
/**
* Set the delegate used by this class; the default is {@code this},
* assuming that handler methods have been added by a subclass.
* <p>This method does not get invoked once the class is configured.
* @param delegate an object containing handler methods
* @throws IllegalStateException if no handler methods are found
*/
public final void setDelegate(Object delegate) {
Assert.notNull(delegate, "Delegate must not be null");
this.delegate = delegate;
registerHandlerMethods(this.delegate);
// There must be SOME handler methods.
if (this.handlerMethodMap.isEmpty()) {
throw new IllegalStateException("No handler methods in class [" + this.delegate.getClass() + "]");
}
}
/**
* Set the method name resolver that this class should use.
* <p>Allows parameterization of handler method mappings.
*/
public final void setMethodNameResolver(MethodNameResolver methodNameResolver) {
this.methodNameResolver = methodNameResolver;
}
/**
* Return the MethodNameResolver used by this class.
*/
public final MethodNameResolver getMethodNameResolver() {
return this.methodNameResolver;
}
/**
* Set the {@link Validator Validators} for this controller.
* <p>The {@code Validators} must support the specified command class.
*/
public final void setValidators(Validator[] validators) {
this.validators = validators;
}
/**
* Return the Validators for this controller.
*/
public final Validator[] getValidators() {
return this.validators;
}
/**
* Specify a WebBindingInitializer which will apply pre-configured
* configuration to every DataBinder that this controller uses.
* <p>Allows for factoring out the entire binder configuration
* to separate objects, as an alternative to {@link #initBinder}.
*/
public final void setWebBindingInitializer(WebBindingInitializer webBindingInitializer) {
this.webBindingInitializer = webBindingInitializer;
}
/**
* Return the WebBindingInitializer (if any) which will apply pre-configured
* configuration to every DataBinder that this controller uses.
*/
public final WebBindingInitializer getWebBindingInitializer() {
return this.webBindingInitializer;
}
/**
* Registers all handlers methods on the delegate object.
*/
private void registerHandlerMethods(Object delegate) {
this.handlerMethodMap.clear();
this.lastModifiedMethodMap.clear();
this.exceptionHandlerMap.clear();
// Look at all methods in the subclass, trying to find
// methods that are validators according to our criteria
Method[] methods = delegate.getClass().getMethods();
for (Method method : methods) {
// We're looking for methods with given parameters.
if (isExceptionHandlerMethod(method)) {
registerExceptionHandlerMethod(method);
}
else if (isHandlerMethod(method)) {
registerHandlerMethod(method);
registerLastModifiedMethodIfExists(delegate, method);
}
}
}
/**
* Is the supplied method a valid handler method?
* <p>Does not consider {@code Controller.handleRequest} itself
* as handler method (to avoid potential stack overflow).
*/
private boolean isHandlerMethod(Method method) {
Class<?> returnType = method.getReturnType();
if (ModelAndView.class == returnType || Map.class == returnType || String.class == returnType ||
void.class == returnType) {
Class<?>[] parameterTypes = method.getParameterTypes();
return (parameterTypes.length >= 2 &&
HttpServletRequest.class == parameterTypes[0] &&
HttpServletResponse.class == parameterTypes[1] &&
!("handleRequest".equals(method.getName()) && parameterTypes.length == 2));
}
return false;
}
/**
* Is the supplied method a valid exception handler method?
*/
private boolean isExceptionHandlerMethod(Method method) {
return (isHandlerMethod(method) &&
method.getParameterTypes().length == 3 &&
Throwable.class.isAssignableFrom(method.getParameterTypes()[2]));
}
/**
* Registers the supplied method as a request handler.
*/
private void registerHandlerMethod(Method method) {
if (logger.isDebugEnabled()) {
logger.debug("Found action method [" + method + "]");
}
this.handlerMethodMap.put(method.getName(), method);
}
/**
* Registers a last-modified handler method for the supplied handler method
* if one exists.
*/
private void registerLastModifiedMethodIfExists(Object delegate, Method method) {
// Look for corresponding LastModified method.
try {
Method lastModifiedMethod = delegate.getClass().getMethod(
method.getName() + LAST_MODIFIED_METHOD_SUFFIX,
new Class<?>[] {HttpServletRequest.class});
Class<?> returnType = lastModifiedMethod.getReturnType();
if (!(long.class == returnType || Long.class == returnType)) {
throw new IllegalStateException("last-modified method [" + lastModifiedMethod +
"] declares an invalid return type - needs to be 'long' or 'Long'");
}
// Put in cache, keyed by handler method name.
this.lastModifiedMethodMap.put(method.getName(), lastModifiedMethod);
if (logger.isDebugEnabled()) {
logger.debug("Found last-modified method for handler method [" + method + "]");
}
}
catch (NoSuchMethodException ex) {
// No last modified method. That's ok.
}
}
/**
* Registers the supplied method as an exception handler.
*/
private void registerExceptionHandlerMethod(Method method) {
this.exceptionHandlerMap.put(method.getParameterTypes()[2], method);
if (logger.isDebugEnabled()) {
logger.debug("Found exception handler method [" + method + "]");
}
}
//---------------------------------------------------------------------
// Implementation of LastModified
//---------------------------------------------------------------------
/**
* Try to find an XXXXLastModified method, where XXXX is the name of a handler.
* Return -1 if there's no such handler, indicating that content must be updated.
* @see org.springframework.web.servlet.mvc.LastModified#getLastModified(HttpServletRequest)
*/
@Override
public long getLastModified(HttpServletRequest request) {
try {
String handlerMethodName = this.methodNameResolver.getHandlerMethodName(request);
Method lastModifiedMethod = this.lastModifiedMethodMap.get(handlerMethodName);
if (lastModifiedMethod != null) {
try {
// Invoke the last-modified method...
Long wrappedLong = (Long) lastModifiedMethod.invoke(this.delegate, request);
return (wrappedLong != null ? wrappedLong : -1);
}
catch (Exception ex) {
// We encountered an error invoking the last-modified method.
// We can't do anything useful except log this, as we can't throw an exception.
logger.error("Failed to invoke last-modified method", ex);
}
}
}
catch (NoSuchRequestHandlingMethodException ex) {
// No handler method for this request. This shouldn't happen, as this
// method shouldn't be called unless a previous invocation of this class
// has generated content. Do nothing, that's OK: We'll return default.
}
return -1L;
}
//---------------------------------------------------------------------
// Implementation of AbstractController
//---------------------------------------------------------------------
/**
* Determine a handler method and invoke it.
* @see MethodNameResolver#getHandlerMethodName
* @see #invokeNamedMethod
* @see #handleNoSuchRequestHandlingMethod
*/
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
throws Exception {
try {
String methodName = this.methodNameResolver.getHandlerMethodName(request);
return invokeNamedMethod(methodName, request, response);
}
catch (NoSuchRequestHandlingMethodException ex) {
return handleNoSuchRequestHandlingMethod(ex, request, response);
}
}
/**
* Handle the case where no request handler method was found.
* <p>The default implementation logs a warning and sends an HTTP 404 error.
* Alternatively, a fallback view could be chosen, or the
* NoSuchRequestHandlingMethodException could be rethrown as-is.
* @param ex the NoSuchRequestHandlingMethodException to be handled
* @param request current HTTP request
* @param response current HTTP response
* @return a ModelAndView to render, or {@code null} if handled directly
* @throws Exception an Exception that should be thrown as result of the servlet request
*/
protected ModelAndView handleNoSuchRequestHandlingMethod(
NoSuchRequestHandlingMethodException ex, HttpServletRequest request, HttpServletResponse response)
throws Exception {
pageNotFoundLogger.warn(ex.getMessage());
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return null;
}
/**
* Invokes the named method.
* <p>Uses a custom exception handler if possible; otherwise, throw an
* unchecked exception; wrap a checked exception or Throwable.
*/
protected final ModelAndView invokeNamedMethod(
String methodName, HttpServletRequest request, HttpServletResponse response) throws Exception {
Method method = this.handlerMethodMap.get(methodName);
if (method == null) {
throw new NoSuchRequestHandlingMethodException(methodName, getClass());
}
try {
Class<?>[] paramTypes = method.getParameterTypes();
List<Object> params = new ArrayList<Object>(4);
params.add(request);
params.add(response);
if (paramTypes.length >= 3 && HttpSession.class == paramTypes[2]) {
HttpSession session = request.getSession(false);
if (session == null) {
throw new HttpSessionRequiredException(
"Pre-existing session required for handler method '" + methodName + "'");
}
params.add(session);
}
// If last parameter isn't of HttpSession type, it's a command.
if (paramTypes.length >= 3 && HttpSession.class != paramTypes[paramTypes.length - 1]) {
Object command = newCommandObject(paramTypes[paramTypes.length - 1]);
params.add(command);
bind(request, command);
}
Object returnValue = method.invoke(this.delegate, params.toArray(new Object[params.size()]));
return massageReturnValueIfNecessary(returnValue);
}
catch (InvocationTargetException ex) {
// The handler method threw an exception.
return handleException(request, response, ex.getTargetException());
}
catch (Exception ex) {
// The binding process threw an exception.
return handleException(request, response, ex);
}
}
/**
* Processes the return value of a handler method to ensure that it either returns
* {@code null} or an instance of {@link ModelAndView}. When returning a {@link Map},
* the {@link Map} instance is wrapped in a new {@link ModelAndView} instance.
*/
@SuppressWarnings("unchecked")
private ModelAndView massageReturnValueIfNecessary(Object returnValue) {
if (returnValue instanceof ModelAndView) {
return (ModelAndView) returnValue;
}
else if (returnValue instanceof Map) {
return new ModelAndView().addAllObjects((Map<String, ?>) returnValue);
}
else if (returnValue instanceof String) {
return new ModelAndView((String) returnValue);
}
else {
// Either returned null or was 'void' return.
// We'll assume that the handle method already wrote the response.
return null;
}
}
/**
* Create a new command object of the given class.
* <p>This implementation uses {@code BeanUtils.instantiateClass},
* so commands need to have public no-arg constructors.
* Subclasses can override this implementation if desired.
* @throws Exception if the command object could not be instantiated
* @see org.springframework.beans.BeanUtils#instantiateClass(Class)
*/
protected Object newCommandObject(Class<?> clazz) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("Creating new command of class [" + clazz.getName() + "]");
}
return BeanUtils.instantiateClass(clazz);
}
/**
* Bind request parameters onto the given command bean
* @param request request from which parameters will be bound
* @param command command object, that must be a JavaBean
* @throws Exception in case of invalid state or arguments
*/
protected void bind(HttpServletRequest request, Object command) throws Exception {
logger.debug("Binding request parameters onto MultiActionController command");
ServletRequestDataBinder binder = createBinder(request, command);
binder.bind(request);
if (this.validators != null) {
for (Validator validator : this.validators) {
if (validator.supports(command.getClass())) {
ValidationUtils.invokeValidator(validator, command, binder.getBindingResult());
}
}
}
binder.closeNoCatch();
}
/**
* Create a new binder instance for the given command and request.
* <p>Called by {@code bind}. Can be overridden to plug in custom
* ServletRequestDataBinder subclasses.
* <p>The default implementation creates a standard ServletRequestDataBinder,
* and invokes {@code initBinder}. Note that {@code initBinder}
* 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 #bind
* @see #initBinder
*/
protected ServletRequestDataBinder createBinder(HttpServletRequest request, Object command) throws Exception {
ServletRequestDataBinder binder = new ServletRequestDataBinder(command, getCommandName(command));
initBinder(request, binder);
return binder;
}
/**
* Return the command name to use for the given command object.
* <p>Default is "command".
* @param command the command object
* @return the command name to use
* @see #DEFAULT_COMMAND_NAME
*/
protected String getCommandName(Object command) {
return DEFAULT_COMMAND_NAME;
}
/**
* Initialize the given binder instance, for example with custom editors.
* Called by {@code createBinder}.
* <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>The default implementation is empty.
* <p>Note: the command object is not directly passed to this method, but it's available
* via {@link org.springframework.validation.DataBinder#getTarget()}
* @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 {
if (this.webBindingInitializer != null) {
this.webBindingInitializer.initBinder(binder, new ServletWebRequest(request));
}
}
/**
* Determine the exception handler method for the given exception.
* <p>Can return {@code null} if not found.
* @return a handler for the given exception type, or {@code null}
* @param exception the exception to handle
*/
protected Method getExceptionHandler(Throwable exception) {
Class<?> exceptionClass = exception.getClass();
if (logger.isDebugEnabled()) {
logger.debug("Trying to find handler for exception class [" + exceptionClass.getName() + "]");
}
Method handler = this.exceptionHandlerMap.get(exceptionClass);
while (handler == null && exceptionClass != Throwable.class) {
if (logger.isDebugEnabled()) {
logger.debug("Trying to find handler for exception superclass [" + exceptionClass.getName() + "]");
}
exceptionClass = exceptionClass.getSuperclass();
handler = this.exceptionHandlerMap.get(exceptionClass);
}
return handler;
}
/**
* We've encountered an exception thrown from a handler method.
* Invoke an appropriate exception handler method, if any.
* @param request current HTTP request
* @param response current HTTP response
* @param ex the exception that got thrown
* @return a ModelAndView to render the response
*/
private ModelAndView handleException(HttpServletRequest request, HttpServletResponse response, Throwable ex)
throws Exception {
Method handler = getExceptionHandler(ex);
if (handler != null) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking exception handler [" + handler + "] for exception: " + ex);
}
try {
Object returnValue = handler.invoke(this.delegate, request, response, ex);
return massageReturnValueIfNecessary(returnValue);
}
catch (InvocationTargetException ex2) {
logger.error("Original exception overridden by exception handling failure", ex);
ReflectionUtils.rethrowException(ex2.getTargetException());
}
catch (Exception ex2) {
logger.error("Failed to invoke exception handler method", ex2);
}
}
else {
// If we get here, there was no custom handler or we couldn't invoke it.
ReflectionUtils.rethrowException(ex);
}
throw new IllegalStateException("Should never get here");
}
}

View File

@@ -1,80 +0,0 @@
/*
* Copyright 2002-2012 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.multiaction;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.core.style.StylerUtils;
import org.springframework.web.util.UrlPathHelper;
/**
* Exception thrown when there is no handler method ("action" method)
* for a specific HTTP request.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @see MethodNameResolver#getHandlerMethodName(javax.servlet.http.HttpServletRequest)
* @deprecated as of 4.3, in favor of annotation-driven handler methods
*/
@Deprecated
@SuppressWarnings("serial")
public class NoSuchRequestHandlingMethodException extends ServletException {
private String methodName;
/**
* Create a new NoSuchRequestHandlingMethodException for the given request.
* @param request the offending HTTP request
*/
public NoSuchRequestHandlingMethodException(HttpServletRequest request) {
this(new UrlPathHelper().getRequestUri(request), request.getMethod(), request.getParameterMap());
}
/**
* Create a new NoSuchRequestHandlingMethodException.
* @param urlPath the request URI that has been used for handler lookup
* @param method the HTTP request method of the request
* @param parameterMap the request's parameters as map
*/
public NoSuchRequestHandlingMethodException(String urlPath, String method, Map<String, String[]> parameterMap) {
super("No matching handler method found for servlet request: path '" + urlPath +
"', method '" + method + "', parameters " + StylerUtils.style(parameterMap));
}
/**
* Create a new NoSuchRequestHandlingMethodException for the given request.
* @param methodName the name of the handler method that wasn't found
* @param controllerClass the class the handler method was expected to be in
*/
public NoSuchRequestHandlingMethodException(String methodName, Class<?> controllerClass) {
super("No request handling method with name '" + methodName +
"' in class [" + controllerClass.getName() + "]");
this.methodName = methodName;
}
/**
* Return the name of the offending method, if known.
*/
public String getMethodName() {
return this.methodName;
}
}

View File

@@ -1,224 +0,0 @@
/*
* Copyright 2002-2014 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.multiaction;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.util.WebUtils;
/**
* Implementation of {@link MethodNameResolver} which supports several strategies
* for mapping parameter values to the names of methods to invoke.
*
* <p>The simplest strategy looks for a specific named parameter, whose value is
* considered the name of the method to invoke. The name of the parameter may be
* specified as a JavaBean property, if the default {@code action} is not
* acceptable.
*
* <p>The alternative strategy uses the very existence of a request parameter (
* i.e. a request parameter with a certain name is found) as an indication that a
* method with the same name should be dispatched to. In this case, the actual
* request parameter value is ignored. The list of parameter/method names may
* be set via the {@code methodParamNames} JavaBean property.
*
* <p>The second resolution strategy is primarily expected to be used with web
* pages containing multiple submit buttons. The 'name' attribute of each
* button should be set to the mapped method name, while the 'value' attribute
* is normally displayed as the button label by the browser, and will be
* ignored by the resolver.
*
* <p>Note that the second strategy also supports the use of submit buttons of
* type 'image'. That is, an image submit button named 'reset' will normally be
* submitted by the browser as two request parameters called 'reset.x', and
* 'reset.y'. When checking for the existence of a parameter from the
* {@code methodParamNames} list, to indicate that a specific method should
* be called, the code will look for a request parameter in the "reset" form
* (exactly as specified in the list), and in the "reset.x" form ('.x' appended
* to the name in the list). In this way it can handle both normal and image
* submit buttons. The actual method name resolved, if there is a match, will
* always be the bare form without the ".x".
*
* <p><b>Note:</b> If both strategies are configured, i.e. both "paramName"
* and "methodParamNames" are specified, then both will be checked for any given
* request. A match for an explicit request parameter in the "methodParamNames"
* list always wins over a value specified for a "paramName" action parameter.
*
* <p>For use with either strategy, the name of a default handler method to use
* when there is no match, can be specified as a JavaBean property.
*
* <p>For both resolution strategies, the method name is of course coming from
* some sort of view code, (such as a JSP page). While this may be acceptable,
* it is sometimes desirable to treat this only as a 'logical' method name,
* with a further mapping to a 'real' method name. As such, an optional
* 'logical' mapping may be specified for this purpose.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Colin Sampaleanu
* @see #setParamName
* @see #setMethodParamNames
* @see #setLogicalMappings
* @see #setDefaultMethodName
* @deprecated as of 4.3, in favor of annotation-driven handler methods
*/
@Deprecated
public class ParameterMethodNameResolver implements MethodNameResolver {
/**
* Default name for the parameter whose value identifies the method to invoke:
* "action".
*/
public static final String DEFAULT_PARAM_NAME = "action";
protected final Log logger = LogFactory.getLog(getClass());
private String paramName = DEFAULT_PARAM_NAME;
private String[] methodParamNames;
private Properties logicalMappings;
private String defaultMethodName;
/**
* Set the name of the parameter whose <i>value</i> identifies the name of
* the method to invoke. Default is "action".
* <p>Alternatively, specify parameter names where the very existence of each
* parameter means that a method of the same name should be invoked, via
* the "methodParamNames" property.
* @see #setMethodParamNames
*/
public void setParamName(String paramName) {
if (paramName != null) {
Assert.hasText(paramName, "'paramName' must not be empty");
}
this.paramName = paramName;
}
/**
* Set a String array of parameter names, where the <i>very existence of a
* parameter</i> in the list (with value ignored) means that a method of the
* same name should be invoked. This target method name may then be optionally
* further mapped via the {@link #logicalMappings} property, in which case it
* can be considered a logical name only.
* @see #setParamName
*/
public void setMethodParamNames(String... methodParamNames) {
this.methodParamNames = methodParamNames;
}
/**
* Specifies a set of optional logical method name mappings. For both resolution
* strategies, the method name initially comes in from the view layer. If that needs
* to be treated as a 'logical' method name, and mapped to a 'real' method name, then
* a name/value pair for that purpose should be added to this Properties instance.
* Any method name not found in this mapping will be considered to already be the
* real method name.
* <p>Note that in the case of no match, where the {@link #defaultMethodName} property
* is used if available, that method name is considered to already be the real method
* name, and is not run through the logical mapping.
* @param logicalMappings a Properties object mapping logical method names to real
* method names
*/
public void setLogicalMappings(Properties logicalMappings) {
this.logicalMappings = logicalMappings;
}
/**
* Set the name of the default handler method that should be
* used when no parameter was found in the request
*/
public void setDefaultMethodName(String defaultMethodName) {
if (defaultMethodName != null) {
Assert.hasText(defaultMethodName, "'defaultMethodName' must not be empty");
}
this.defaultMethodName = defaultMethodName;
}
@Override
public String getHandlerMethodName(HttpServletRequest request) throws NoSuchRequestHandlingMethodException {
String methodName = null;
// Check parameter names where the very existence of each parameter
// means that a method of the same name should be invoked, if any.
if (this.methodParamNames != null) {
for (String candidate : this.methodParamNames) {
if (WebUtils.hasSubmitParameter(request, candidate)) {
methodName = candidate;
if (logger.isDebugEnabled()) {
logger.debug("Determined handler method '" + methodName +
"' based on existence of explicit request parameter of same name");
}
break;
}
}
}
// Check parameter whose value identifies the method to invoke, if any.
if (methodName == null && this.paramName != null) {
methodName = request.getParameter(this.paramName);
if (methodName != null) {
if (logger.isDebugEnabled()) {
logger.debug("Determined handler method '" + methodName +
"' based on value of request parameter '" + this.paramName + "'");
}
}
}
if (methodName != null && this.logicalMappings != null) {
// Resolve logical name into real method name, if appropriate.
String originalName = methodName;
methodName = this.logicalMappings.getProperty(methodName, methodName);
if (logger.isDebugEnabled()) {
logger.debug("Resolved method name '" + originalName + "' to handler method '" + methodName + "'");
}
}
if (methodName != null && !StringUtils.hasText(methodName)) {
if (logger.isDebugEnabled()) {
logger.debug("Method name '" + methodName + "' is empty: treating it as no method name found");
}
methodName = null;
}
if (methodName == null) {
if (this.defaultMethodName != null) {
// No specific method resolved: use default method.
methodName = this.defaultMethodName;
if (logger.isDebugEnabled()) {
logger.debug("Falling back to default handler method '" + this.defaultMethodName + "'");
}
}
else {
// If resolution failed completely, throw an exception.
throw new NoSuchRequestHandlingMethodException(request);
}
}
return methodName;
}
}

View File

@@ -1,101 +0,0 @@
/*
* Copyright 2002-2012 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.multiaction;
import java.util.Enumeration;
import java.util.Properties;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.Assert;
import org.springframework.util.PathMatcher;
/**
* The most flexible out-of-the-box implementation of the {@link MethodNameResolver}
* interface. Uses {@code java.util.Properties} to define the mapping
* between the URL of incoming requests and the corresponding method name.
* Such properties can be held in an XML document.
*
* <p>Properties format is
* {@code
* /welcome.html=displayGenresPage
* }
* Note that method overloading isn't allowed, so there's no need to
* specify arguments.
*
* <p>Supports direct matches, e.g. a registered "/test" matches "/test",
* and a various Ant-style pattern matches, e.g. a registered "/t*" matches
* both "/test" and "/team". For details, see the AntPathMatcher javadoc.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @see java.util.Properties
* @see org.springframework.util.AntPathMatcher
* @deprecated as of 4.3, in favor of annotation-driven handler methods
*/
@Deprecated
public class PropertiesMethodNameResolver extends AbstractUrlMethodNameResolver
implements InitializingBean {
private Properties mappings;
private PathMatcher pathMatcher = new AntPathMatcher();
/**
* Set explicit URL to method name mappings through a Properties object.
* @param mappings Properties with URL as key and method name as value
*/
public void setMappings(Properties mappings) {
this.mappings = mappings;
}
/**
* Set the PathMatcher implementation to use for matching URL paths
* against registered URL patterns. Default is AntPathMatcher.
* @see org.springframework.util.AntPathMatcher
*/
public void setPathMatcher(PathMatcher pathMatcher) {
Assert.notNull(pathMatcher, "PathMatcher must not be null");
this.pathMatcher = pathMatcher;
}
@Override
public void afterPropertiesSet() {
if (this.mappings == null || this.mappings.isEmpty()) {
throw new IllegalArgumentException("'mappings' property is required");
}
}
@Override
protected String getHandlerMethodNameForUrlPath(String urlPath) {
String methodName = this.mappings.getProperty(urlPath);
if (methodName != null) {
return methodName;
}
Enumeration<?> propNames = this.mappings.propertyNames();
while (propNames.hasMoreElements()) {
String registeredPath = (String) propNames.nextElement();
if (this.pathMatcher.match(registeredPath, urlPath)) {
return (String) this.mappings.get(registeredPath);
}
}
return null;
}
}

View File

@@ -1,13 +0,0 @@
/**
* Package allowing MVC Controller implementations to handle requests
* at <i>method</i> rather than <i>class</i> level. This is useful when
* we want to avoid having many trivial controller classes, as can
* easily happen when using an MVC framework.
*
* <p>Typically a controller that handles multiple request types will
* extend MultiActionController, and implement multiple request handling
* methods that will be invoked by reflection if they follow this class'
* naming convention. Classes are analyzed at startup and methods cached,
* so the performance overhead of reflection in this approach is negligible.
*/
package org.springframework.web.servlet.mvc.multiaction;

View File

@@ -1,158 +0,0 @@
/*
* Copyright 2002-2014 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.support;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.springframework.web.servlet.handler.AbstractDetectingUrlHandlerMapping;
/**
* Base class for {@link org.springframework.web.servlet.HandlerMapping} implementations
* that derive URL paths according to conventions for specific controller types.
*
* @author Juergen Hoeller
* @since 2.5.3
* @see ControllerClassNameHandlerMapping
* @see ControllerBeanNameHandlerMapping
* @deprecated as of 4.3, in favor of annotation-driven handler methods
*/
@Deprecated
public abstract class AbstractControllerUrlHandlerMapping extends AbstractDetectingUrlHandlerMapping {
private ControllerTypePredicate predicate = new AnnotationControllerTypePredicate();
private Set<String> excludedPackages = Collections.singleton("org.springframework.web.servlet.mvc");
private Set<Class<?>> excludedClasses = Collections.emptySet();
/**
* Set whether to activate or deactivate detection of annotated controllers.
*/
public void setIncludeAnnotatedControllers(boolean includeAnnotatedControllers) {
this.predicate = (includeAnnotatedControllers ?
new AnnotationControllerTypePredicate() : new ControllerTypePredicate());
}
/**
* Specify Java packages that should be excluded from this mapping.
* Any classes in such a package (or any of its subpackages) will be
* ignored by this HandlerMapping.
* <p>Default is to exclude the entire "org.springframework.web.servlet.mvc"
* package, including its subpackages, since none of Spring's out-of-the-box
* Controller implementations is a reasonable candidate for this mapping strategy.
* Such controllers are typically handled by a separate HandlerMapping,
* e.g. a {@link org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping},
* alongside this ControllerClassNameHandlerMapping for application controllers.
*/
public void setExcludedPackages(String... excludedPackages) {
this.excludedPackages = (excludedPackages != null) ?
new HashSet<String>(Arrays.asList(excludedPackages)) : new HashSet<String>();
}
/**
* Specify controller classes that should be excluded from this mapping.
* Any such classes will simply be ignored by this HandlerMapping.
*/
public void setExcludedClasses(Class<?>... excludedClasses) {
this.excludedClasses = (excludedClasses != null) ?
new HashSet<Class<?>>(Arrays.asList(excludedClasses)) : new HashSet<Class<?>>();
}
/**
* This implementation delegates to {@link #buildUrlsForHandler},
* provided that {@link #isEligibleForMapping} returns {@code true}.
*/
@Override
protected String[] determineUrlsForHandler(String beanName) {
Class<?> beanClass = getApplicationContext().getType(beanName);
if (isEligibleForMapping(beanName, beanClass)) {
return buildUrlsForHandler(beanName, beanClass);
}
else {
return null;
}
}
/**
* Determine whether the specified controller is excluded from this mapping.
* @param beanName the name of the controller bean
* @param beanClass the concrete class of the controller bean
* @return whether the specified class is excluded
* @see #setExcludedPackages
* @see #setExcludedClasses
*/
protected boolean isEligibleForMapping(String beanName, Class<?> beanClass) {
if (beanClass == null) {
if (logger.isDebugEnabled()) {
logger.debug("Excluding controller bean '" + beanName + "' from class name mapping " +
"because its bean type could not be determined");
}
return false;
}
if (this.excludedClasses.contains(beanClass)) {
if (logger.isDebugEnabled()) {
logger.debug("Excluding controller bean '" + beanName + "' from class name mapping " +
"because its bean class is explicitly excluded: " + beanClass.getName());
}
return false;
}
String beanClassName = beanClass.getName();
for (String packageName : this.excludedPackages) {
if (beanClassName.startsWith(packageName)) {
if (logger.isDebugEnabled()) {
logger.debug("Excluding controller bean '" + beanName + "' from class name mapping " +
"because its bean class is defined in an excluded package: " + beanClass.getName());
}
return false;
}
}
return isControllerType(beanClass);
}
/**
* Determine whether the given bean class indicates a controller type
* that is supported by this mapping strategy.
* @param beanClass the class to introspect
*/
protected boolean isControllerType(Class<?> beanClass) {
return this.predicate.isControllerType(beanClass);
}
/**
* Determine whether the given bean class indicates a controller type
* that dispatches to multiple action methods.
* @param beanClass the class to introspect
*/
protected boolean isMultiActionControllerType(Class<?> beanClass) {
return this.predicate.isMultiActionControllerType(beanClass);
}
/**
* Abstract template method to be implemented by subclasses.
* @param beanName the name of the bean
* @param beanClass the type of the bean
* @return the URLs determined for the bean
*/
protected abstract String[] buildUrlsForHandler(String beanName, Class<?> beanClass);
}

View File

@@ -1,45 +0,0 @@
/*
* Copyright 2002-2012 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.support;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Controller;
/**
* Extension of {@link ControllerTypePredicate} that detects
* annotated {@code @Controller} beans as well.
*
* @author Juergen Hoeller
* @since 2.5.3
* @deprecated as of 4.3, in favor of annotation-driven handler methods
*/
@Deprecated
class AnnotationControllerTypePredicate extends ControllerTypePredicate {
@Override
public boolean isControllerType(Class<?> beanClass) {
return (super.isControllerType(beanClass) ||
AnnotationUtils.findAnnotation(beanClass, Controller.class) != null);
}
@Override
public boolean isMultiActionControllerType(Class<?> beanClass) {
return (super.isMultiActionControllerType(beanClass) ||
AnnotationUtils.findAnnotation(beanClass, Controller.class) != null);
}
}

View File

@@ -1,96 +0,0 @@
/*
* Copyright 2002-2012 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.support;
import java.util.ArrayList;
import java.util.List;
import org.springframework.util.StringUtils;
/**
* Implementation of {@link org.springframework.web.servlet.HandlerMapping} that
* follows a simple convention for generating URL path mappings from the <i>bean names</i>
* of registered {@link org.springframework.web.servlet.mvc.Controller} beans
* as well as {@code @Controller} annotated beans.
*
* <p>This is similar to {@link org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping}
* but doesn't expect bean names to follow the URL convention: It turns plain bean names
* into URLs by prepending a slash and optionally applying a specified prefix and/or suffix.
* However, it only does so for well-known {@link #isControllerType controller types},
* as listed above (analogous to {@link ControllerClassNameHandlerMapping}).
*
* @author Juergen Hoeller
* @since 2.5.3
* @see ControllerClassNameHandlerMapping
* @see org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping
* @deprecated as of 4.3, in favor of annotation-driven handler methods
*/
@Deprecated
public class ControllerBeanNameHandlerMapping extends AbstractControllerUrlHandlerMapping {
private String urlPrefix = "";
private String urlSuffix = "";
/**
* Set an optional prefix to prepend to generated URL mappings.
* <p>By default this is an empty String. If you want a prefix like
* "/myapp/", you can set it for all beans mapped by this mapping.
*/
public void setUrlPrefix(String urlPrefix) {
this.urlPrefix = (urlPrefix != null ? urlPrefix : "");
}
/**
* Set an optional suffix to append to generated URL mappings.
* <p>By default this is an empty String. If you want a suffix like
* ".do", you can set it for all beans mapped by this mapping.
*/
public void setUrlSuffix(String urlSuffix) {
this.urlSuffix = (urlSuffix != null ? urlSuffix : "");
}
@Override
protected String[] buildUrlsForHandler(String beanName, Class<?> beanClass) {
List<String> urls = new ArrayList<String>();
urls.add(generatePathMapping(beanName));
String[] aliases = getApplicationContext().getAliases(beanName);
for (String alias : aliases) {
urls.add(generatePathMapping(alias));
}
return StringUtils.toStringArray(urls);
}
/**
* Prepends a '/' if required and appends the URL suffix to the name.
*/
protected String generatePathMapping(String beanName) {
String name = (beanName.startsWith("/") ? beanName : "/" + beanName);
StringBuilder path = new StringBuilder();
if (!name.startsWith(this.urlPrefix)) {
path.append(this.urlPrefix);
}
path.append(name);
if (!name.endsWith(this.urlSuffix)) {
path.append(this.urlSuffix);
}
return path.toString();
}
}

View File

@@ -1,183 +0,0 @@
/*
* Copyright 2002-2012 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.support;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
/**
* Implementation of {@link org.springframework.web.servlet.HandlerMapping} that
* follows a simple convention for generating URL path mappings from the <i>class names</i>
* of registered {@link org.springframework.web.servlet.mvc.Controller} beans
* as well as {@code @Controller} annotated beans.
*
* <p>For simple {@link org.springframework.web.servlet.mvc.Controller} implementations
* (those that handle a single request type), the convention is to take the
* {@link ClassUtils#getShortName short name} of the {@code Class},
* remove the 'Controller' suffix if it exists and return the remaining text, lower-cased,
* as the mapping, with a leading {@code /}. For example:
* <ul>
* <li>{@code WelcomeController} -> {@code /welcome*}</li>
* <li>{@code HomeController} -> {@code /home*}</li>
* </ul>
*
* <p>For {@code MultiActionController MultiActionControllers} and {@code @Controller}
* beans, a similar mapping is registered, except that all sub-paths are registered
* using the trailing wildcard pattern {@code /*}. For example:
* <ul>
* <li>{@code WelcomeController} -> {@code /welcome}, {@code /welcome/*}</li>
* <li>{@code CatalogController} -> {@code /catalog}, {@code /catalog/*}</li>
* </ul>
*
* <p>For {@code MultiActionController} it is often useful to use
* this mapping strategy in conjunction with the
* {@link org.springframework.web.servlet.mvc.multiaction.InternalPathMethodNameResolver}.
*
* <p>Thanks to Warren Oliver for suggesting the "caseSensitive", "pathPrefix"
* and "basePackage" properties which have been added in Spring 2.5.
*
* @author Rob Harrop
* @author Juergen Hoeller
* @since 2.0
* @see org.springframework.web.servlet.mvc.Controller
* @see org.springframework.web.servlet.mvc.multiaction.MultiActionController
* @deprecated as of 4.3, in favor of annotation-driven handler methods
*/
@Deprecated
public class ControllerClassNameHandlerMapping extends AbstractControllerUrlHandlerMapping {
/**
* Common suffix at the end of controller implementation classes.
* Removed when generating the URL path.
*/
private static final String CONTROLLER_SUFFIX = "Controller";
private boolean caseSensitive = false;
private String pathPrefix;
private String basePackage;
/**
* Set whether to apply case sensitivity to the generated paths,
* e.g. turning the class name "BuyForm" into "buyForm".
* <p>Default is "false", using pure lower case paths,
* e.g. turning the class name "BuyForm" into "buyform".
*/
public void setCaseSensitive(boolean caseSensitive) {
this.caseSensitive = caseSensitive;
}
/**
* Specify a prefix to prepend to the path generated from the controller name.
* <p>Default is a plain slash ("/"). A path like "/mymodule" can be specified
* in order to have controller path mappings prefixed with that path, e.g.
* "/mymodule/buyform" instead of "/buyform" for the class name "BuyForm".
*/
public void setPathPrefix(String prefixPath) {
this.pathPrefix = prefixPath;
if (StringUtils.hasLength(this.pathPrefix)) {
if (!this.pathPrefix.startsWith("/")) {
this.pathPrefix = "/" + this.pathPrefix;
}
if (this.pathPrefix.endsWith("/")) {
this.pathPrefix = this.pathPrefix.substring(0, this.pathPrefix.length() - 1);
}
}
}
/**
* Set the base package to be used for generating path mappings,
* including all subpackages underneath this packages as path elements.
* <p>Default is {@code null}, using the short class name for the
* generated path, with the controller's package not represented in the path.
* Specify a base package like "com.mycompany.myapp" to include subpackages
* within that base package as path elements, e.g. generating the path
* "/mymodule/buyform" for the class name "com.mycompany.myapp.mymodule.BuyForm".
* Subpackage hierarchies are represented as individual path elements,
* e.g. "/mymodule/mysubmodule/buyform" for the class name
* "com.mycompany.myapp.mymodule.mysubmodule.BuyForm".
*/
public void setBasePackage(String basePackage) {
this.basePackage = basePackage;
if (StringUtils.hasLength(this.basePackage) && !this.basePackage.endsWith(".")) {
this.basePackage = this.basePackage + ".";
}
}
@Override
protected String[] buildUrlsForHandler(String beanName, Class<?> beanClass) {
return generatePathMappings(beanClass);
}
/**
* Generate the actual URL paths for the given controller class.
* <p>Subclasses may choose to customize the paths that are generated
* by overriding this method.
* @param beanClass the controller bean class to generate a mapping for
* @return the URL path mappings for the given controller
*/
protected String[] generatePathMappings(Class<?> beanClass) {
StringBuilder pathMapping = buildPathPrefix(beanClass);
String className = ClassUtils.getShortName(beanClass);
String path = (className.endsWith(CONTROLLER_SUFFIX) ?
className.substring(0, className.lastIndexOf(CONTROLLER_SUFFIX)) : className);
if (path.length() > 0) {
if (this.caseSensitive) {
pathMapping.append(path.substring(0, 1).toLowerCase()).append(path.substring(1));
}
else {
pathMapping.append(path.toLowerCase());
}
}
if (isMultiActionControllerType(beanClass)) {
return new String[] {pathMapping.toString(), pathMapping.toString() + "/*"};
}
else {
return new String[] {pathMapping.toString() + "*"};
}
}
/**
* Build a path prefix for the given controller bean class.
* @param beanClass the controller bean class to generate a mapping for
* @return the path prefix, potentially including subpackage names as path elements
*/
private StringBuilder buildPathPrefix(Class<?> beanClass) {
StringBuilder pathMapping = new StringBuilder();
if (this.pathPrefix != null) {
pathMapping.append(this.pathPrefix);
pathMapping.append("/");
}
else {
pathMapping.append("/");
}
if (this.basePackage != null) {
String packageName = ClassUtils.getPackageName(beanClass);
if (packageName.startsWith(this.basePackage)) {
String subPackage = packageName.substring(this.basePackage.length()).replace('.', '/');
pathMapping.append(this.caseSensitive ? subPackage : subPackage.toLowerCase());
pathMapping.append("/");
}
}
return pathMapping;
}
}

View File

@@ -1,40 +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.support;
import org.springframework.web.servlet.mvc.Controller;
/**
* Internal helper class that identifies controller types.
*
* @author Juergen Hoeller
* @since 2.5.3
* @deprecated as of 4.3, in favor of annotation-driven handler methods
*/
@Deprecated
class ControllerTypePredicate {
public boolean isControllerType(Class<?> beanClass) {
return Controller.class.isAssignableFrom(beanClass);
}
@SuppressWarnings("deprecation")
public boolean isMultiActionControllerType(Class<?> beanClass) {
return org.springframework.web.servlet.mvc.multiaction.MultiActionController.class.isAssignableFrom(beanClass);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2016 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.
@@ -63,7 +63,6 @@ import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;
* @author Juergen Hoeller
* @since 3.0
* @see org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler
* @see #handleNoSuchRequestHandlingMethod
* @see #handleHttpRequestMethodNotSupported
* @see #handleHttpMediaTypeNotSupported
* @see #handleMissingServletRequestParameter
@@ -100,16 +99,11 @@ public class DefaultHandlerExceptionResolver extends AbstractHandlerExceptionRes
@Override
@SuppressWarnings("deprecation")
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) {
try {
if (ex instanceof org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException) {
return handleNoSuchRequestHandlingMethod((org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException) ex,
request, response, handler);
}
else if (ex instanceof HttpRequestMethodNotSupportedException) {
if (ex instanceof HttpRequestMethodNotSupportedException) {
return handleHttpRequestMethodNotSupported((HttpRequestMethodNotSupportedException) ex, request,
response, handler);
}
@@ -168,29 +162,6 @@ public class DefaultHandlerExceptionResolver extends AbstractHandlerExceptionRes
return null;
}
/**
* Handle the case where no request handler method was found.
* <p>The default implementation logs a warning, sends an HTTP 404 error, and returns
* an empty {@code ModelAndView}. Alternatively, a fallback view could be chosen,
* or the NoSuchRequestHandlingMethodException could be rethrown as-is.
* @param ex the NoSuchRequestHandlingMethodException to be handled
* @param request current HTTP request
* @param response current HTTP response
* @param handler the executed handler, or {@code null} if none chosen
* at the time of the exception (for example, if multipart resolution failed)
* @return an empty ModelAndView indicating the exception was handled
* @throws IOException potentially thrown from response.sendError()
* @deprecated as of 4.3, along with {@link org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException}
*/
@Deprecated
protected ModelAndView handleNoSuchRequestHandlingMethod(org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException ex,
HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
pageNotFoundLogger.warn(ex.getMessage());
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return new ModelAndView();
}
/**
* Handle the case where no request handler method was found for the particular HTTP request method.
* <p>The default implementation logs a warning, sends an HTTP 405 error, sets the "Allow" header,

View File

@@ -510,13 +510,8 @@ public class ResourceHttpRequestHandler extends WebContentGenerator
* @param resource the resource to check
* @return the corresponding media type, or {@code null} if none found
*/
@SuppressWarnings("deprecation")
protected MediaType getMediaType(HttpServletRequest request, Resource resource) {
// For backwards compatibility
MediaType mediaType = getMediaType(resource);
if (mediaType != null) {
return mediaType;
}
MediaType mediaType = null;
Class<PathExtensionContentNegotiationStrategy> clazz = PathExtensionContentNegotiationStrategy.class;
PathExtensionContentNegotiationStrategy strategy = this.contentNegotiationManager.getStrategy(clazz);
@@ -540,18 +535,6 @@ public class ResourceHttpRequestHandler extends WebContentGenerator
return mediaType;
}
/**
* Determine an appropriate media type for the given resource.
* @param resource the resource to check
* @return the corresponding media type, or {@code null} if none found
* @deprecated as of 4.3 this method is deprecated; please override
* {@link #getMediaType(HttpServletRequest, Resource)} instead.
*/
@Deprecated
protected MediaType getMediaType(Resource resource) {
return null;
}
/**
* Set headers on the given servlet response.
* Called for GET requests as well as HEAD requests.

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2016 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.
@@ -60,53 +60,6 @@ public abstract class RequestContextUtils {
public static final String REQUEST_DATA_VALUE_PROCESSOR_BEAN_NAME = "requestDataValueProcessor";
/**
* Look for the WebApplicationContext associated with the DispatcherServlet
* that has initiated request processing.
* @param request current HTTP request
* @return the request-specific web application context
* @throws IllegalStateException if no servlet-specific context has been found
* @see #getWebApplicationContext(ServletRequest, ServletContext)
* @deprecated as of Spring 4.2.1, in favor of
* {@link #findWebApplicationContext(HttpServletRequest)}
*/
@Deprecated
public static WebApplicationContext getWebApplicationContext(ServletRequest request) throws IllegalStateException {
return getWebApplicationContext(request, null);
}
/**
* Look for the WebApplicationContext associated with the DispatcherServlet
* that has initiated request processing, and for the global context if none
* was found associated with the current request. This method is useful to
* allow components outside the framework, such as JSP tag handlers,
* to access the most specific application context available.
* @param request current HTTP request
* @param servletContext current servlet context
* @return the request-specific WebApplicationContext, or the global one
* if no request-specific context has been found
* @throws IllegalStateException if neither a servlet-specific nor a
* global context has been found
* @see DispatcherServlet#WEB_APPLICATION_CONTEXT_ATTRIBUTE
* @see WebApplicationContextUtils#getRequiredWebApplicationContext(ServletContext)
* @deprecated as of Spring 4.2.1, in favor of
* {@link #findWebApplicationContext(HttpServletRequest, ServletContext)}
*/
@Deprecated
public static WebApplicationContext getWebApplicationContext(
ServletRequest request, ServletContext servletContext) throws IllegalStateException {
WebApplicationContext webApplicationContext = (WebApplicationContext) request.getAttribute(
DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE);
if (webApplicationContext == null) {
if (servletContext == null) {
throw new IllegalStateException("No WebApplicationContext found: not in a DispatcherServlet request?");
}
webApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
}
return webApplicationContext;
}
/**
* Look for the WebApplicationContext associated with the DispatcherServlet
* that has initiated request processing, and for the global context if none

View File

@@ -143,27 +143,6 @@ public class FormTag extends AbstractHtmlElementTag {
return this.modelAttribute;
}
/**
* Set the name of the form attribute in the model.
* <p>May be a runtime expression.
* @see #setModelAttribute
* @deprecated as of Spring 4.3, in favor of {@link #setModelAttribute}
*/
@Deprecated
public void setCommandName(String commandName) {
this.modelAttribute = commandName;
}
/**
* Get the name of the form attribute in the model.
* @see #getModelAttribute
* @deprecated as of Spring 4.3, in favor of {@link #getModelAttribute}
*/
@Deprecated
protected String getCommandName() {
return this.modelAttribute;
}
/**
* Set the value of the '{@code name}' attribute.
* <p>May be a runtime expression.
@@ -331,18 +310,7 @@ public class FormTag extends AbstractHtmlElementTag {
* Get the name of the request param for non-browser supported HTTP methods.
* @since 4.2.3
*/
@SuppressWarnings("deprecation")
protected String getMethodParam() {
return getMethodParameter();
}
/**
* Get the name of the request param for non-browser supported HTTP methods.
* @deprecated as of 4.2.3, in favor of {@link #getMethodParam()} which is
* a proper pairing for {@link #setMethodParam(String)}
*/
@Deprecated
protected String getMethodParameter() {
return this.methodParam;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2016 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.
@@ -397,9 +397,8 @@ public class ComplexWebApplicationContext extends StaticWebApplicationContext {
public static class ComplexLocaleChecker implements MyHandler {
@Override
@SuppressWarnings("deprecation")
public void doSomething(HttpServletRequest request) throws ServletException, IllegalAccessException {
WebApplicationContext wac = RequestContextUtils.getWebApplicationContext(request);
WebApplicationContext wac = RequestContextUtils.findWebApplicationContext(request);
if (!(wac instanceof ComplexWebApplicationContext)) {
throw new ServletException("Incorrect WebApplicationContext");
}

View File

@@ -699,38 +699,6 @@ public class DispatcherServletTests {
assertNull(myServlet.getServletConfig());
}
@Test
@SuppressWarnings("deprecation")
public void webApplicationContextLookup() {
MockServletContext servletContext = new MockServletContext();
MockHttpServletRequest request = new MockHttpServletRequest(servletContext, "GET", "/invalid.do");
try {
RequestContextUtils.getWebApplicationContext(request);
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
try {
RequestContextUtils.getWebApplicationContext(request, servletContext);
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
new StaticWebApplicationContext());
try {
RequestContextUtils.getWebApplicationContext(request, servletContext);
}
catch (IllegalStateException ex) {
fail("Should not have thrown IllegalStateException: " + ex.getMessage());
}
}
@Test
public void withNoView() throws Exception {
MockServletContext servletContext = new MockServletContext();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2016 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.
@@ -74,10 +74,9 @@ public class SimpleWebApplicationContext extends StaticWebApplicationContext {
public static class LocaleChecker implements Controller, LastModified {
@Override
@SuppressWarnings("deprecation")
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (!(RequestContextUtils.getWebApplicationContext(request) instanceof SimpleWebApplicationContext)) {
if (!(RequestContextUtils.findWebApplicationContext(request) instanceof SimpleWebApplicationContext)) {
throw new ServletException("Incorrect WebApplicationContext");
}
if (!(RequestContextUtils.getLocaleResolver(request) instanceof AcceptHeaderLocaleResolver)) {

View File

@@ -1,27 +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.annotation;
import org.springframework.stereotype.Controller;
/**
* @author Juergen Hoeller
*/
@Controller
public class AdminController {
}

View File

@@ -1,52 +0,0 @@
/*
* Copyright 2002-2009 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.annotation;
import java.io.IOException;
import java.io.Writer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
/**
* Used for testing the combination of ControllerClassNameHandlerMapping/SimpleUrlHandlerMapping with @RequestParam in
* {@link ServletAnnotationControllerTests}. Implemented as a top-level class (rather than an inner class) to make the
* ControllerClassNameHandlerMapping work.
*
* @author Arjen Poutsma
*/
@Controller
public class BookController {
@RequestMapping("list")
public void list(Writer writer) throws IOException {
writer.write("list");
}
@RequestMapping("show")
public void show(@RequestParam(required = true) Long id, Writer writer) throws IOException {
writer.write("show-id=" + id);
}
@RequestMapping(method = RequestMethod.POST)
public void create(Writer writer) throws IOException {
writer.write("create");
}
}

View File

@@ -1,27 +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.annotation;
import org.springframework.stereotype.Controller;
/**
* @author Juergen Hoeller
*/
@Controller
public class BuyForm {
}

View File

@@ -25,7 +25,6 @@ import org.junit.Test;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.aop.interceptor.SimpleTraceInterceptor;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse;
@@ -42,10 +41,11 @@ import static org.junit.Assert.*;
* @author Arjen Poutsma
* @since 3.0
*/
public class CgLibProxyServletAnnotationTests {
public class CglibProxyControllerTests {
private DispatcherServlet servlet;
@Test
public void typeLevel() throws Exception {
initServlet(TypeLevelImpl.class);
@@ -78,13 +78,12 @@ public class CgLibProxyServletAnnotationTests {
@SuppressWarnings("serial")
private void initServlet(final Class<?> controllerclass) throws ServletException {
private void initServlet(final Class<?> controllerClass) throws ServletException {
servlet = new DispatcherServlet() {
@Override
protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent)
throws BeansException {
protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) {
GenericWebApplicationContext wac = new GenericWebApplicationContext();
wac.registerBeanDefinition("controller", new RootBeanDefinition(controllerclass));
wac.registerBeanDefinition("controller", new RootBeanDefinition(controllerClass));
DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator();
autoProxyCreator.setProxyTargetClass(true);
autoProxyCreator.setBeanFactory(wac.getBeanFactory());
@@ -97,9 +96,6 @@ public class CgLibProxyServletAnnotationTests {
servlet.init(new MockServletConfig());
}
/*
* Controllers
*/
@Controller
@RequestMapping("/test")
@@ -111,6 +107,7 @@ public class CgLibProxyServletAnnotationTests {
}
}
@Controller
public static class MethodLevelImpl {
@@ -120,6 +117,7 @@ public class CgLibProxyServletAnnotationTests {
}
}
@Controller
@RequestMapping("/hotels")
public static class TypeAndMethodLevelImpl {

View File

@@ -1,40 +0,0 @@
/*
* Copyright 2002-2010 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.annotation;
import java.io.IOException;
import java.io.Writer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/** @author Arjen Poutsma */
@Controller
public class ControllerClassNameController {
@RequestMapping(value = {"{id}", "{id}.*"}, method = RequestMethod.GET)
public void plain(Writer writer, @PathVariable("id") String id) throws IOException {
writer.write("plain-" + id);
}
@RequestMapping(value = "{id}.pdf", method = RequestMethod.GET)
public void pdf(Writer writer, @PathVariable("id") String id) throws IOException {
writer.write("pdf-" + id);
}
}

View File

@@ -1,128 +0,0 @@
/*
* Copyright 2002-2015 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.annotation;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockServletContext;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerMapping;
import static org.junit.Assert.*;
/**
* @author Juergen Hoeller
*/
public class ControllerClassNameHandlerMappingTests {
private static final String LOCATION = "/org/springframework/web/servlet/mvc/annotation/class-mapping.xml";
private final XmlWebApplicationContext wac = new XmlWebApplicationContext();
private HandlerMapping hm, hm2, hm3, hm4;
@Before
public void setUp() throws Exception {
this.wac.setServletContext(new MockServletContext(""));
this.wac.setConfigLocations(LOCATION);
this.wac.refresh();
this.hm = (HandlerMapping) this.wac.getBean("mapping");
this.hm2 = (HandlerMapping) this.wac.getBean("mapping2");
this.hm3 = (HandlerMapping) this.wac.getBean("mapping3");
this.hm4 = (HandlerMapping) this.wac.getBean("mapping4");
}
@After
public void closeWac() {
this.wac.close();
}
@Test
public void indexUri() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/index");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("index"), chain.getHandler());
request = new MockHttpServletRequest("GET", "/index/product");
chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("index"), chain.getHandler());
}
@Test
public void mapSimpleUri() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/welcome");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
request = new MockHttpServletRequest("GET", "/welcome/product");
chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
@Test
public void withContextPath() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/welcome");
request.setContextPath("/myapp");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
@Test
public void withoutControllerSuffix() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/buyform");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("buy"), chain.getHandler());
request = new MockHttpServletRequest("GET", "/buyform/product");
chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("buy"), chain.getHandler());
}
@Test
public void withBasePackage() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/mvc/annotation/welcome");
HandlerExecutionChain chain = this.hm2.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
@Test
public void withBasePackageAndCaseSensitive() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/mvc/annotation/buyForm");
HandlerExecutionChain chain = this.hm2.getHandler(request);
assertEquals(this.wac.getBean("buy"), chain.getHandler());
}
@Test
public void withFullBasePackage() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/welcome");
HandlerExecutionChain chain = this.hm3.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
@Test
public void withRootAsBasePackage() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/org/springframework/web/servlet/mvc/annotation/welcome");
HandlerExecutionChain chain = this.hm4.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
}

View File

@@ -1,37 +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.annotation;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* @author Juergen Hoeller
*/
@Controller
public class IndexController {
@RequestMapping
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
return new ModelAndView("indexView");
}
}

View File

@@ -25,7 +25,6 @@ import org.junit.Test;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.aop.interceptor.SimpleTraceInterceptor;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse;
@@ -42,10 +41,11 @@ import static org.junit.Assert.*;
* @author Arjen Poutsma
* @since 3.0
*/
public class JdkProxyServletAnnotationTests {
public class JdkProxyControllerTests {
private DispatcherServlet servlet;
@Test
public void typeLevel() throws Exception {
initServlet(TypeLevelImpl.class);
@@ -81,8 +81,7 @@ public class JdkProxyServletAnnotationTests {
private void initServlet(final Class<?> controllerclass) throws ServletException {
servlet = new DispatcherServlet() {
@Override
protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent)
throws BeansException {
protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) {
GenericWebApplicationContext wac = new GenericWebApplicationContext();
wac.registerBeanDefinition("controller", new RootBeanDefinition(controllerclass));
DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator();
@@ -96,9 +95,6 @@ public class JdkProxyServletAnnotationTests {
servlet.init(new MockServletConfig());
}
/*
* Controllers
*/
@Controller
@RequestMapping("/test")
@@ -106,9 +102,9 @@ public class JdkProxyServletAnnotationTests {
@RequestMapping
void doIt(Writer writer) throws IOException;
}
public static class TypeLevelImpl implements TypeLevel {
@Override
@@ -123,9 +119,9 @@ public class JdkProxyServletAnnotationTests {
@RequestMapping("/test")
void doIt(Writer writer) throws IOException;
}
public static class MethodLevelImpl implements MethodLevel {
@Override
@@ -134,15 +130,16 @@ public class JdkProxyServletAnnotationTests {
}
}
@Controller
@RequestMapping("/hotels")
public interface TypeAndMethodLevel {
@RequestMapping("/bookings")
void doIt(Writer writer) throws IOException;
}
public static class TypeAndMethodLevelImpl implements TypeAndMethodLevel {
@Override

View File

@@ -1,53 +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.annotation;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* @author Juergen Hoeller
*/
@Controller
@RequestMapping("/*.do")
public class MethodNameDispatchingController {
@RequestMapping
public void myHandle(HttpServletResponse response) throws IOException {
response.getWriter().write("myView");
}
@RequestMapping
public void myOtherHandle(HttpServletResponse response) throws IOException {
response.getWriter().write("myOtherView");
}
@RequestMapping(method = RequestMethod.POST)
public void myLangHandle(HttpServletResponse response) throws IOException {
response.getWriter().write("myLangView");
}
@RequestMapping(method = RequestMethod.POST)
public void mySurpriseHandle(HttpServletResponse response) throws IOException {
response.getWriter().write("mySurpriseView");
}
}

View File

@@ -1,37 +0,0 @@
/*
* 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.mvc.annotation;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* @author Juergen Hoeller
*/
@Controller
public class WelcomeController {
@RequestMapping
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
return new ModelAndView("welcomeView");
}
}

View File

@@ -1,26 +0,0 @@
/*
* 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.mvc.mapping;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
/**
* @author Rob Harrop
*/
public class AdminController extends MultiActionController {
}

View File

@@ -1,32 +0,0 @@
/*
* Copyright 2002-2013 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.mapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
public class BuyForm implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
return null;
}
}

View File

@@ -1,34 +0,0 @@
/*
* Copyright 2002-2012 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.mapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
/**
* @author Juergen Hoeller
*/
public class Controller implements org.springframework.web.servlet.mvc.Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
return new ModelAndView("indexView");
}
}

View File

@@ -1,92 +0,0 @@
/*
* Copyright 2002-2015 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.mapping;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockServletContext;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerMapping;
import static org.junit.Assert.*;
/**
* @author Juergen Hoeller
*/
public class ControllerBeanNameHandlerMappingTests {
private static final String LOCATION = "/org/springframework/web/servlet/mvc/mapping/name-mapping.xml";
private final XmlWebApplicationContext wac = new XmlWebApplicationContext();
private HandlerMapping hm;
@Before
public void setUp() throws Exception {
this.wac.setServletContext(new MockServletContext(""));
this.wac.setConfigLocations(LOCATION);
this.wac.refresh();
this.hm = this.wac.getBean(HandlerMapping.class);
}
@After
public void closeWac() {
this.wac.close();
}
@Test
public void indexUri() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/index");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("index"), chain.getHandler());
}
@Test
public void mapSimpleUri() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/welcome");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
@Test
public void withContextPath() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/welcome");
request.setContextPath("/myapp");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
@Test
public void withMultiActionControllerMapping() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/admin");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("admin"), chain.getHandler());
}
@Test
public void withoutControllerSuffix() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/buy");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("buy"), chain.getHandler());
}
}

View File

@@ -1,130 +0,0 @@
/*
* Copyright 2002-2015 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.mapping;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockServletContext;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerMapping;
import static org.junit.Assert.*;
/**
* @author Rob Harrop
* @author Juergen Hoeller
*/
public class ControllerClassNameHandlerMappingTests {
public static final String LOCATION = "/org/springframework/web/servlet/mvc/mapping/class-mapping.xml";
private XmlWebApplicationContext wac;
private HandlerMapping hm;
private HandlerMapping hm2;
private HandlerMapping hm3;
private HandlerMapping hm4;
@Before
public void setUp() throws Exception {
MockServletContext sc = new MockServletContext("");
this.wac = new XmlWebApplicationContext();
this.wac.setServletContext(sc);
this.wac.setConfigLocations(new String[] {LOCATION});
this.wac.refresh();
this.hm = (HandlerMapping) this.wac.getBean("mapping");
this.hm2 = (HandlerMapping) this.wac.getBean("mapping2");
this.hm3 = (HandlerMapping) this.wac.getBean("mapping3");
this.hm4 = (HandlerMapping) this.wac.getBean("mapping4");
}
@Test
public void indexUri() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("index"), chain.getHandler());
}
@Test
public void mapSimpleUri() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/welcome");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
@Test
public void withContextPath() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/welcome");
request.setContextPath("/myapp");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
@Test
public void withMultiActionControllerMapping() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/admin/user");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("admin"), chain.getHandler());
request = new MockHttpServletRequest("GET", "/admin/product");
chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("admin"), chain.getHandler());
}
@Test
public void withoutControllerSuffix() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/buyform");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("buy"), chain.getHandler());
}
@Test
public void withBasePackage() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/mvc/mapping/welcome");
HandlerExecutionChain chain = this.hm2.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
@Test
public void withBasePackageAndCaseSensitive() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/mvc/mapping/buyForm");
HandlerExecutionChain chain = this.hm2.getHandler(request);
assertEquals(this.wac.getBean("buy"), chain.getHandler());
}
@Test
public void withFullBasePackage() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/welcome");
HandlerExecutionChain chain = this.hm3.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
@Test
public void withRootAsBasePackage() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/org/springframework/web/servlet/mvc/mapping/welcome");
HandlerExecutionChain chain = this.hm4.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
}

View File

@@ -1,35 +0,0 @@
/*
* Copyright 2002-2012 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.mapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
/**
* @author Rob Harrop
*/
public class WelcomeController implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
return new ModelAndView("welcomeView");
}
}

View File

@@ -53,7 +53,6 @@ import org.springframework.web.context.request.WebRequest;
import org.springframework.web.context.support.StaticWebApplicationContext;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;
import static org.junit.Assert.*;
@@ -103,12 +102,6 @@ public class ResponseEntityExceptionHandlerTests {
}
}
@Test
public void noSuchRequestHandlingMethod() {
Exception ex = new NoSuchRequestHandlingMethodException("GET", TestController.class);
testException(ex);
}
@Test
public void httpRequestMethodNotSupported() {
List<String> supported = Arrays.asList("POST", "DELETE");
@@ -116,7 +109,6 @@ public class ResponseEntityExceptionHandlerTests {
ResponseEntity<Object> responseEntity = testException(ex);
assertEquals(EnumSet.of(HttpMethod.POST, HttpMethod.DELETE), responseEntity.getHeaders().getAllow());
}
@Test

View File

@@ -128,7 +128,6 @@ import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.context.support.GenericWebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.multipart.support.StringMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;
@@ -1786,10 +1785,6 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl
}
/*
* Controllers
*/
@Controller
static class ControllerWithEmptyValueMapping {
@@ -2501,7 +2496,6 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl
@Retention(RetentionPolicy.RUNTIME)
@Controller
public @interface MyControllerAnnotation {
}
@MyControllerAnnotation
@@ -2935,7 +2929,6 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl
}
public static class MyEntity {
}
@Controller
@@ -2964,8 +2957,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl
}
@RequestMapping("/multiValueMap")
public void multiValueMap(@RequestParam MultiValueMap<String, String> params, Writer writer)
throws IOException {
public void multiValueMap(@RequestParam MultiValueMap<String, String> params, Writer writer) throws IOException {
for (Iterator<Map.Entry<String, List<String>>> it1 = params.entrySet().iterator(); it1.hasNext();) {
Map.Entry<String, List<String>> entry = it1.next();
writer.write(entry.getKey() + "=[");
@@ -3135,7 +3127,6 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl
setValue(null);
}
}
}
@Controller
@@ -3174,6 +3165,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl
@Controller
@RequestMapping("/t1")
protected static class NoPathGetAndM2PostController {
@RequestMapping(method = RequestMethod.GET)
public void handle1(Writer writer) throws IOException {
writer.write("handle1");
@@ -3309,37 +3301,4 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl
}
}
// Test cases deleted from the original ServletAnnotationControllerTests:
// @Ignore("Controller interface => no method-level @RequestMapping annotation")
// public void standardHandleMethod() throws Exception {
// @Ignore("ControllerClassNameHandlerMapping")
// public void emptyRequestMapping() throws Exception {
// @Ignore("Controller interface => no method-level @RequestMapping annotation")
// public void proxiedStandardHandleMethod() throws Exception {
// @Ignore("ServletException no longer thrown for unmatched parameter constraints")
// public void constrainedParameterDispatchingController() throws Exception {
// @Ignore("Method name dispatching")
// public void methodNameDispatchingController() throws Exception {
// @Ignore("Method name dispatching")
// public void methodNameDispatchingControllerWithSuffix() throws Exception {
// @Ignore("ControllerClassNameHandlerMapping")
// public void controllerClassNamePlusMethodNameDispatchingController() throws Exception {
// @Ignore("Method name dispatching")
// public void postMethodNameDispatchingController() throws Exception {
// @Ignore("ControllerClassNameHandlerMapping")
// public void controllerClassNameNoTypeLevelAnn() throws Exception {
// @Ignore("SimpleUrlHandlerMapping")
// public void simpleUrlHandlerMapping() throws Exception {
}

View File

@@ -1,746 +0,0 @@
/*
* Copyright 2002-2013 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.multiaction;
import org.junit.Test;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import static org.junit.Assert.*;
import org.springframework.beans.FatalBeanException;
import org.springframework.context.ApplicationContextException;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse;
import org.springframework.mock.web.test.MockHttpSession;
import org.springframework.tests.sample.beans.TestBean;
import org.springframework.web.HttpSessionRequiredException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.servlet.ModelAndView;
/**
* @author Rod Johnson
* @author Juergen Hoeller
* @author Colin Sampaleanu
* @author Rob Harrop
* @author Sam Brannen
*/
public class MultiActionControllerTests {
@Test
public void defaultInternalPathMethodNameResolver() throws Exception {
doDefaultTestInternalPathMethodNameResolver("/foo.html", "foo");
doDefaultTestInternalPathMethodNameResolver("/foo/bar.html", "bar");
doDefaultTestInternalPathMethodNameResolver("/bugal.xyz", "bugal");
doDefaultTestInternalPathMethodNameResolver("/x/y/z/q/foo.html", "foo");
doDefaultTestInternalPathMethodNameResolver("qqq.q", "qqq");
}
private void doDefaultTestInternalPathMethodNameResolver(String in, String expected) throws Exception {
MultiActionController rc = new MultiActionController();
HttpServletRequest request = new MockHttpServletRequest("GET", in);
String actual = rc.getMethodNameResolver().getHandlerMethodName(request);
assertEquals("Wrong method name resolved", expected, actual);
}
@Test
public void customizedInternalPathMethodNameResolver() throws Exception {
doTestCustomizedInternalPathMethodNameResolver("/foo.html", "my", null, "myfoo");
doTestCustomizedInternalPathMethodNameResolver("/foo/bar.html", null, "Handler", "barHandler");
doTestCustomizedInternalPathMethodNameResolver("/Bugal.xyz", "your", "Method", "yourBugalMethod");
}
private void doTestCustomizedInternalPathMethodNameResolver(String in, String prefix, String suffix, String expected)
throws Exception {
MultiActionController rc = new MultiActionController();
InternalPathMethodNameResolver resolver = new InternalPathMethodNameResolver();
if (prefix != null) {
resolver.setPrefix(prefix);
}
if (suffix != null) {
resolver.setSuffix(suffix);
}
rc.setMethodNameResolver(resolver);
HttpServletRequest request = new MockHttpServletRequest("GET", in);
String actual = rc.getMethodNameResolver().getHandlerMethodName(request);
assertEquals("Wrong method name resolved", expected, actual);
}
@Test
public void parameterMethodNameResolver() throws NoSuchRequestHandlingMethodException {
ParameterMethodNameResolver mnr = new ParameterMethodNameResolver();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo.html");
request.addParameter("action", "bar");
assertEquals("bar", mnr.getHandlerMethodName(request));
request = new MockHttpServletRequest("GET", "/foo.html");
try {
mnr.getHandlerMethodName(request);
fail("Should have thrown NoSuchRequestHandlingMethodException");
}
catch (NoSuchRequestHandlingMethodException expected) {
}
request = new MockHttpServletRequest("GET", "/foo.html");
request.addParameter("action", "");
try {
mnr.getHandlerMethodName(request);
fail("Should have thrown NoSuchRequestHandlingMethodException");
}
catch (NoSuchRequestHandlingMethodException expected) {
}
request = new MockHttpServletRequest("GET", "/foo.html");
request.addParameter("action", " ");
try {
mnr.getHandlerMethodName(request);
fail("Should have thrown NoSuchRequestHandlingMethodException");
}
catch (NoSuchRequestHandlingMethodException expected) {
}
}
@Test
public void parameterMethodNameResolverWithCustomParamName() throws NoSuchRequestHandlingMethodException {
ParameterMethodNameResolver mnr = new ParameterMethodNameResolver();
mnr.setParamName("myparam");
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo.html");
request.addParameter("myparam", "bar");
assertEquals("bar", mnr.getHandlerMethodName(request));
}
@Test
public void parameterMethodNameResolverWithParamNames() throws NoSuchRequestHandlingMethodException {
ParameterMethodNameResolver resolver = new ParameterMethodNameResolver();
resolver.setDefaultMethodName("default");
resolver.setMethodParamNames(new String[] { "hello", "spring", "colin" });
Properties logicalMappings = new Properties();
logicalMappings.setProperty("hello", "goodbye");
logicalMappings.setProperty("nina", "colin");
resolver.setLogicalMappings(logicalMappings);
// verify default handler
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("this will not match anything", "whatever");
assertEquals("default", resolver.getHandlerMethodName(request));
// verify first resolution strategy (action=method)
request = new MockHttpServletRequest();
request.addParameter("action", "reset");
assertEquals("reset", resolver.getHandlerMethodName(request));
// this one also tests logical mapping
request = new MockHttpServletRequest();
request.addParameter("action", "nina");
assertEquals("colin", resolver.getHandlerMethodName(request));
// now validate second resolution strategy (parameter existence)
// this also tests logical mapping
request = new MockHttpServletRequest();
request.addParameter("hello", "whatever");
assertEquals("goodbye", resolver.getHandlerMethodName(request));
request = new MockHttpServletRequest();
request.addParameter("spring", "whatever");
assertEquals("spring", resolver.getHandlerMethodName(request));
request = new MockHttpServletRequest();
request.addParameter("hello", "whatever");
request.addParameter("spring", "whatever");
assertEquals("goodbye", resolver.getHandlerMethodName(request));
request = new MockHttpServletRequest();
request.addParameter("colin", "whatever");
request.addParameter("spring", "whatever");
assertEquals("spring", resolver.getHandlerMethodName(request));
// validate image button handling
request = new MockHttpServletRequest();
request.addParameter("spring.x", "whatever");
assertEquals("spring", resolver.getHandlerMethodName(request));
request = new MockHttpServletRequest();
request.addParameter("hello.x", "whatever");
request.addParameter("spring", "whatever");
assertEquals("goodbye", resolver.getHandlerMethodName(request));
}
@Test
public void parameterMethodNameResolverWithDefaultMethodName() throws NoSuchRequestHandlingMethodException {
ParameterMethodNameResolver mnr = new ParameterMethodNameResolver();
mnr.setDefaultMethodName("foo");
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo.html");
request.addParameter("action", "bar");
assertEquals("bar", mnr.getHandlerMethodName(request));
request = new MockHttpServletRequest("GET", "/foo.html");
assertEquals("foo", mnr.getHandlerMethodName(request));
}
@Test
public void invokesCorrectMethod() throws Exception {
TestMaController mc = new TestMaController();
HttpServletRequest request = new MockHttpServletRequest("GET", "/welcome.html");
HttpServletResponse response = new MockHttpServletResponse();
Properties p = new Properties();
p.put("/welcome.html", "welcome");
PropertiesMethodNameResolver mnr = new PropertiesMethodNameResolver();
mnr.setMappings(p);
mc.setMethodNameResolver(mnr);
ModelAndView mv = mc.handleRequest(request, response);
assertTrue("Invoked welcome method", mc.wasInvoked("welcome"));
assertTrue("view name is welcome", mv.getViewName().equals("welcome"));
assertTrue("Only one method invoked", mc.getInvokedMethods() == 1);
mc = new TestMaController();
request = new MockHttpServletRequest("GET", "/subdir/test.html");
response = new MockHttpServletResponse();
mv = mc.handleRequest(request, response);
assertTrue("Invoked test method", mc.wasInvoked("test"));
assertTrue("view name is subdir_test", mv.getViewName().equals("test"));
assertTrue("Only one method invoked", mc.getInvokedMethods() == 1);
}
@Test
public void pathMatching() throws Exception {
TestMaController mc = new TestMaController();
HttpServletRequest request = new MockHttpServletRequest("GET", "/welcome.html");
HttpServletResponse response = new MockHttpServletResponse();
Properties p = new Properties();
p.put("/welc*.html", "welcome");
PropertiesMethodNameResolver mn = new PropertiesMethodNameResolver();
mn.setMappings(p);
mc.setMethodNameResolver(mn);
ModelAndView mv = mc.handleRequest(request, response);
assertTrue("Invoked welcome method", mc.wasInvoked("welcome"));
assertTrue("view name is welcome", mv.getViewName().equals("welcome"));
assertTrue("Only one method invoked", mc.getInvokedMethods() == 1);
mc = new TestMaController();
mc.setMethodNameResolver(mn);
request = new MockHttpServletRequest("GET", "/nomatch");
response = new MockHttpServletResponse();
try {
mv = mc.handleRequest(request, response);
}
catch (Exception expected) {
}
assertFalse("Not invoking welcome method", mc.wasInvoked("welcome"));
assertTrue("No method invoked", mc.getInvokedMethods() == 0);
}
@Test
public void invokesCorrectMethodOnDelegate() throws Exception {
MultiActionController mac = new MultiActionController();
TestDelegate d = new TestDelegate();
mac.setDelegate(d);
HttpServletRequest request = new MockHttpServletRequest("GET", "/test.html");
HttpServletResponse response = new MockHttpServletResponse();
ModelAndView mv = mac.handleRequest(request, response);
assertTrue("view name is test", mv.getViewName().equals("test"));
assertTrue("Delegate was invoked", d.invoked);
}
@Test
public void invokesCorrectMethodWithSession() throws Exception {
TestMaController mc = new TestMaController();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/inSession.html");
request.setSession(new MockHttpSession(null));
HttpServletResponse response = new MockHttpServletResponse();
ModelAndView mv = mc.handleRequest(request, response);
assertTrue("Invoked inSession method", mc.wasInvoked("inSession"));
assertTrue("view name is welcome", mv.getViewName().equals("inSession"));
assertTrue("Only one method invoked", mc.getInvokedMethods() == 1);
request = new MockHttpServletRequest("GET", "/inSession.html");
response = new MockHttpServletResponse();
try {
mc.handleRequest(request, response);
fail("Must have rejected request without session");
}
catch (ServletException expected) {
}
}
@Test
public void invokesCommandMethodNoSession() throws Exception {
TestMaController mc = new TestMaController();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/commandNoSession.html");
request.addParameter("name", "rod");
request.addParameter("age", "32");
HttpServletResponse response = new MockHttpServletResponse();
ModelAndView mv = mc.handleRequest(request, response);
assertTrue("Invoked commandNoSession method", mc.wasInvoked("commandNoSession"));
assertTrue("view name is commandNoSession", mv.getViewName().equals("commandNoSession"));
assertTrue("Only one method invoked", mc.getInvokedMethods() == 1);
}
@Test
public void invokesCommandMethodWithSession() throws Exception {
TestMaController mc = new TestMaController();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/commandInSession.html");
request.addParameter("name", "rod");
request.addParameter("age", "32");
request.setSession(new MockHttpSession(null));
HttpServletResponse response = new MockHttpServletResponse();
ModelAndView mv = mc.handleRequest(request, response);
assertTrue("Invoked commandInSession method", mc.wasInvoked("commandInSession"));
assertTrue("view name is commandInSession", mv.getViewName().equals("commandInSession"));
assertTrue("Only one method invoked", mc.getInvokedMethods() == 1);
request = new MockHttpServletRequest("GET", "/commandInSession.html");
response = new MockHttpServletResponse();
try {
mc.handleRequest(request, response);
fail("Must have rejected request without session");
}
catch (ServletException expected) {
}
}
@Test
public void sessionRequiredCatchable() throws Exception {
HttpServletRequest request = new MockHttpServletRequest("GET", "/testSession.html");
HttpServletResponse response = new MockHttpServletResponse();
TestMaController contr = new TestSessionRequiredController();
try {
contr.handleRequest(request, response);
fail("Should have thrown exception");
}
catch (HttpSessionRequiredException ex) {
// assertTrue("session required", ex.equals(t));
}
request = new MockHttpServletRequest("GET", "/testSession.html");
response = new MockHttpServletResponse();
contr = new TestSessionRequiredExceptionHandler();
ModelAndView mv = contr.handleRequest(request, response);
assertTrue("Name is ok", mv.getViewName().equals("handle(SRE)"));
}
private void testExceptionNoHandler(TestMaController mc, Throwable t) throws Exception {
HttpServletRequest request = new MockHttpServletRequest("GET", "/testException.html");
request.setAttribute(TestMaController.THROWABLE_ATT, t);
HttpServletResponse response = new MockHttpServletResponse();
try {
mc.handleRequest(request, response);
fail("Should have thrown exception");
}
catch (Throwable ex) {
assertTrue(ex.equals(t));
}
}
private void testExceptionNoHandler(Throwable t) throws Exception {
testExceptionNoHandler(new TestMaController(), t);
}
@Test
public void exceptionNoHandler() throws Exception {
testExceptionNoHandler(new Exception());
// must go straight through
testExceptionNoHandler(new ServletException());
// subclass of servlet exception
testExceptionNoHandler(new ServletRequestBindingException("foo"));
testExceptionNoHandler(new RuntimeException());
testExceptionNoHandler(new Error());
}
@Test
public void lastModifiedDefault() throws Exception {
TestMaController mc = new TestMaController();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/welcome.html");
long lastMod = mc.getLastModified(request);
assertTrue("default last modified is -1", lastMod == -1L);
}
@Test
public void lastModifiedWithMethod() throws Exception {
LastModController mc = new LastModController();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/welcome.html");
long lastMod = mc.getLastModified(request);
assertTrue("last modified with method is > -1", lastMod == mc.getLastModified(request));
}
private ModelAndView testHandlerCaughtException(TestMaController mc, Throwable t) throws Exception {
HttpServletRequest request = new MockHttpServletRequest("GET", "/testException.html");
request.setAttribute(TestMaController.THROWABLE_ATT, t);
HttpServletResponse response = new MockHttpServletResponse();
return mc.handleRequest(request, response);
}
@Test
public void handlerCaughtException() throws Exception {
TestMaController mc = new TestExceptionHandler();
ModelAndView mv = testHandlerCaughtException(mc, new Exception());
assertNotNull("ModelAndView must not be null", mv);
assertTrue("mv name is handle(Exception)", "handle(Exception)".equals(mv.getViewName()));
assertTrue("Invoked correct method", mc.wasInvoked("handle(Exception)"));
// WILL GET RUNTIME EXCEPTIONS TOO
testExceptionNoHandler(mc, new Error());
mc = new TestServletExceptionHandler();
mv = testHandlerCaughtException(mc, new ServletException());
assertTrue(mv.getViewName().equals("handle(ServletException)"));
assertTrue("Invoke correct method", mc.wasInvoked("handle(ServletException)"));
mv = testHandlerCaughtException(mc, new ServletRequestBindingException("foo"));
assertTrue(mv.getViewName().equals("handle(ServletException)"));
assertTrue("Invoke correct method", mc.wasInvoked("handle(ServletException)"));
// Check it doesn't affect unknown exceptions
testExceptionNoHandler(mc, new RuntimeException());
testExceptionNoHandler(mc, new Error());
testExceptionNoHandler(mc, new SQLException());
testExceptionNoHandler(mc, new Exception());
mc = new TestRuntimeExceptionHandler();
mv = testHandlerCaughtException(mc, new RuntimeException());
assertTrue(mv.getViewName().equals("handle(RTE)"));
assertTrue("Invoke correct method", mc.wasInvoked("handle(RTE)"));
mv = testHandlerCaughtException(mc, new FatalBeanException(null, null));
assertTrue(mv.getViewName().equals("handle(RTE)"));
assertTrue("Invoke correct method", mc.wasInvoked("handle(RTE)"));
testExceptionNoHandler(mc, new SQLException());
testExceptionNoHandler(mc, new Exception());
}
@Test
public void handlerReturnsMap() throws Exception {
Map model = new HashMap();
model.put("message", "Hello World!");
MultiActionController mac = new ModelOnlyMultiActionController(model);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/welcome.html");
MockHttpServletResponse response = new MockHttpServletResponse();
ModelAndView mav = mac.handleRequest(request, response);
assertNotNull("ModelAndView cannot be null", mav);
assertFalse("ModelAndView should not have a view", mav.hasView());
assertEquals(model, mav.getModel());
}
@Test
public void exceptionHandlerReturnsMap() throws Exception {
Map model = new HashMap();
MultiActionController mac = new ModelOnlyMultiActionController(model);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/index.html");
MockHttpServletResponse response = new MockHttpServletResponse();
ModelAndView mav = mac.handleRequest(request, response);
assertNotNull("ModelAndView cannot be null", mav);
assertFalse("ModelAndView should not have a view", mav.hasView());
assertTrue(model.containsKey("exception"));
}
@Test
public void cannotCallExceptionHandlerDirectly() throws Exception {
Map model = new HashMap();
MultiActionController mac = new ModelOnlyMultiActionController(model);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/handleIllegalStateException.html");
MockHttpServletResponse response = new MockHttpServletResponse();
mac.handleRequest(request, response);
assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatus());
}
@Test
public void handlerReturnsVoid() throws Exception {
MultiActionController mac = new VoidMultiActionController();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/welcome.html");
MockHttpServletResponse response = new MockHttpServletResponse();
ModelAndView mav = mac.handleRequest(request, response);
assertNull("ModelAndView must be null", mav);
}
@Test
public void exceptionHandlerReturnsVoid() throws Exception {
MultiActionController mac = new VoidMultiActionController();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/index.html");
MockHttpServletResponse response = new MockHttpServletResponse();
ModelAndView mav = mac.handleRequest(request, response);
assertNull("ModelAndView must be null", mav);
assertEquals("exception", response.getContentAsString());
}
@Test
public void handlerReturnsString() throws Exception {
MultiActionController mac = new StringMultiActionController();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/welcome.html");
MockHttpServletResponse response = new MockHttpServletResponse();
ModelAndView mav = mac.handleRequest(request, response);
assertNotNull("ModelAndView cannot be null", mav);
assertTrue("ModelAndView must have a view", mav.hasView());
assertEquals("Verifying view name", "welcomeString", mav.getViewName());
}
@Test
public void exceptionHandlerReturnsString() throws Exception {
MultiActionController mac = new StringMultiActionController();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/index.html");
MockHttpServletResponse response = new MockHttpServletResponse();
ModelAndView mav = mac.handleRequest(request, response);
assertNotNull("ModelAndView cannot be null", mav);
assertTrue("ModelAndView must have a view", mav.hasView());
assertEquals("Verifying view name", "handleIllegalStateExceptionString", mav.getViewName());
}
/** No error handlers */
public static class TestMaController extends MultiActionController {
public static final String THROWABLE_ATT = "throwable";
/** Method name -> object */
protected Map invoked = new HashMap();
public void clear() {
this.invoked.clear();
}
public ModelAndView welcome(HttpServletRequest request, HttpServletResponse response) {
this.invoked.put("welcome", Boolean.TRUE);
return new ModelAndView("welcome");
}
public ModelAndView commandNoSession(HttpServletRequest request, HttpServletResponse response, TestBean command) {
this.invoked.put("commandNoSession", Boolean.TRUE);
String pname = request.getParameter("name");
// ALLOW FOR NULL
if (pname == null) {
assertTrue("name null", command.getName() == null);
}
else {
assertTrue("name param set", pname.equals(command.getName()));
}
//String page = request.getParameter("age");
// if (page == null)
// assertTrue("age default", command.getAge() == 0);
// else
// assertTrue("age set", command.getName().equals(pname));
// assertTrue("a",
// command.getAge().equals(request.getParameter("name")));
return new ModelAndView("commandNoSession");
}
public ModelAndView inSession(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
this.invoked.put("inSession", Boolean.TRUE);
assertTrue("session non null", session != null);
return new ModelAndView("inSession");
}
public ModelAndView commandInSession(HttpServletRequest request, HttpServletResponse response,
HttpSession session, TestBean command) {
this.invoked.put("commandInSession", Boolean.TRUE);
assertTrue("session non null", session != null);
return new ModelAndView("commandInSession");
}
public ModelAndView test(HttpServletRequest request, HttpServletResponse response) {
this.invoked.put("test", Boolean.TRUE);
return new ModelAndView("test");
}
public ModelAndView testException(HttpServletRequest request, HttpServletResponse response) throws Throwable {
this.invoked.put("testException", Boolean.TRUE);
Throwable t = (Throwable) request.getAttribute(THROWABLE_ATT);
if (t != null) {
throw t;
}
else {
return new ModelAndView("no throwable");
}
}
public boolean wasInvoked(String method) {
return this.invoked.get(method) != null;
}
public int getInvokedMethods() {
return this.invoked.size();
}
}
public static class TestDelegate {
boolean invoked;
public ModelAndView test(HttpServletRequest request, HttpServletResponse response) {
this.invoked = true;
return new ModelAndView("test");
}
}
public static class TestExceptionHandler extends TestMaController {
public ModelAndView handleAnyException(HttpServletRequest request, HttpServletResponse response, Exception ex) {
this.invoked.put("handle(Exception)", Boolean.TRUE);
return new ModelAndView("handle(Exception)");
}
}
public static class TestRuntimeExceptionHandler extends TestMaController {
public ModelAndView handleRuntimeProblem(HttpServletRequest request, HttpServletResponse response,
RuntimeException ex) {
this.invoked.put("handle(RTE)", Boolean.TRUE);
return new ModelAndView("handle(RTE)");
}
}
public static class TestSessionRequiredController extends TestMaController {
public ModelAndView testSession(HttpServletRequest request, HttpServletResponse response, HttpSession sess) {
return null;
}
}
/** Extends previous to handle exception */
public static class TestSessionRequiredExceptionHandler extends TestSessionRequiredController {
public ModelAndView handleServletException(HttpServletRequest request, HttpServletResponse response,
HttpSessionRequiredException ex) {
this.invoked.put("handle(SRE)", Boolean.TRUE);
return new ModelAndView("handle(SRE)");
}
}
public static class TestServletExceptionHandler extends TestMaController {
public ModelAndView handleServletException(HttpServletRequest request, HttpServletResponse response,
ServletException ex) {
this.invoked.put("handle(ServletException)", Boolean.TRUE);
return new ModelAndView("handle(ServletException)");
}
}
public static class LastModController extends MultiActionController {
public static final String THROWABLE_ATT = "throwable";
/** Method name -> object */
protected HashMap invoked = new HashMap();
public void clear() {
this.invoked.clear();
}
public ModelAndView welcome(HttpServletRequest request, HttpServletResponse response) {
this.invoked.put("welcome", Boolean.TRUE);
return new ModelAndView("welcome");
}
/** Always says content is up to date */
public long welcomeLastModified(HttpServletRequest request) {
return 1111L;
}
}
public static class ModelOnlyMultiActionController extends MultiActionController {
private final Map model;
public ModelOnlyMultiActionController(Map model) throws ApplicationContextException {
this.model = model;
}
public Map welcome(HttpServletRequest request, HttpServletResponse response) {
return this.model;
}
public Map index(HttpServletRequest request, HttpServletResponse response) {
throw new IllegalStateException();
}
public Map handleIllegalStateException(HttpServletRequest request, HttpServletResponse response,
IllegalStateException ex) {
this.model.put("exception", ex);
return this.model;
}
}
public static class VoidMultiActionController extends MultiActionController {
public void welcome(HttpServletRequest request, HttpServletResponse response) {
}
public void index(HttpServletRequest request, HttpServletResponse response) {
throw new IllegalStateException();
}
public void handleIllegalStateException(HttpServletRequest request, HttpServletResponse response,
IllegalStateException ex) throws IOException {
response.getWriter().write("exception");
}
}
public static class StringMultiActionController extends MultiActionController {
public String welcome(HttpServletRequest request, HttpServletResponse response) {
return "welcomeString";
}
public String index(HttpServletRequest request, HttpServletResponse response) {
throw new IllegalStateException();
}
public String handleIllegalStateException(HttpServletRequest request, HttpServletResponse response,
IllegalStateException ex) throws IOException {
return "handleIllegalStateExceptionString";
}
}
}

View File

@@ -43,7 +43,6 @@ import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;
import static org.junit.Assert.*;
@@ -67,15 +66,6 @@ public class DefaultHandlerExceptionResolverTests {
request.setMethod("GET");
}
@Test
public void handleNoSuchRequestHandlingMethod() {
NoSuchRequestHandlingMethodException ex = new NoSuchRequestHandlingMethodException(request);
ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
assertNotNull("No ModelAndView returned", mav);
assertTrue("No Empty ModelAndView returned", mav.isEmpty());
assertEquals("Invalid status code", 404, response.getStatus());
}
@Test
public void handleHttpRequestMethodNotSupported() {
HttpRequestMethodNotSupportedException ex =

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2016 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.
@@ -1039,7 +1039,7 @@ public class BindTagTests extends AbstractTagTests {
formTag.setCssClass(cssClass);
formTag.setCssStyle(cssStyle);
formTag.setAction(action);
formTag.setCommandName(commandName);
formTag.setModelAttribute(commandName);
formTag.setEnctype(enctype);
formTag.setMethod(method);
formTag.setOnsubmit(onsubmit);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2016 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.
@@ -386,7 +386,7 @@ public class MessageTagTests extends AbstractTagTests {
public void nullMessageSource() throws JspException {
PageContext pc = createPageContext();
ConfigurableWebApplicationContext ctx = (ConfigurableWebApplicationContext)
RequestContextUtils.getWebApplicationContext(pc.getRequest(), pc.getServletContext());
RequestContextUtils.findWebApplicationContext((HttpServletRequest) pc.getRequest(), pc.getServletContext());
ctx.close();
MessageTag tag = new MessageTag();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2016 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.
@@ -40,7 +40,7 @@ public abstract class AbstractFormTagTests extends AbstractHtmlElementTagTests {
@Override
protected void extendPageContext(MockPageContext pageContext) throws JspException {
this.formTag.setCommandName(COMMAND_NAME);
this.formTag.setModelAttribute(COMMAND_NAME);
this.formTag.setAction("myAction");
this.formTag.setPageContext(pageContext);
this.formTag.doStartTag();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2016 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.
@@ -20,7 +20,6 @@ import java.io.StringWriter;
import java.io.Writer;
import java.util.Collections;
import java.util.Map;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
@@ -106,8 +105,8 @@ public abstract class AbstractHtmlElementTagTests extends AbstractTagTests {
@SuppressWarnings("deprecation")
protected RequestDataValueProcessor getMockRequestDataValueProcessor() {
RequestDataValueProcessor mockProcessor = mock(RequestDataValueProcessor.class);
ServletRequest request = getPageContext().getRequest();
StaticWebApplicationContext wac = (StaticWebApplicationContext) RequestContextUtils.getWebApplicationContext(request);
HttpServletRequest request = (HttpServletRequest) getPageContext().getRequest();
StaticWebApplicationContext wac = (StaticWebApplicationContext) RequestContextUtils.findWebApplicationContext(request);
wac.getBean(RequestDataValueProcessorWrapper.class).setRequestDataValueProcessor(mockProcessor);
return mockProcessor;
}
@@ -128,18 +127,18 @@ public abstract class AbstractHtmlElementTagTests extends AbstractTagTests {
assertTrue("Expected to find attribute '" + attributeName +
"' with value '" + attributeValue +
"' in output + '" + output + "'",
output.indexOf(attributeString) > -1);
output.contains(attributeString));
}
protected final void assertAttributeNotPresent(String output, String attributeName) {
assertTrue("Unexpected attribute '" + attributeName + "' in output '" + output + "'.",
output.indexOf(attributeName + "=\"") < 0);
!output.contains(attributeName + "=\""));
}
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);
contents.contains(desiredContents));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2016 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.
@@ -86,7 +86,7 @@ public class FormTagTests extends AbstractHtmlElementTagTests {
this.tag.setName(name);
this.tag.setCssClass(cssClass);
this.tag.setCssStyle(cssStyle);
this.tag.setCommandName(commandName);
this.tag.setModelAttribute(commandName);
this.tag.setAction(action);
this.tag.setMethod(method);
this.tag.setTarget(target);
@@ -138,7 +138,7 @@ public class FormTagTests extends AbstractHtmlElementTagTests {
String onsubmit = "onsubmit";
String onreset = "onreset";
this.tag.setCommandName(commandName);
this.tag.setModelAttribute(commandName);
this.tag.setMethod(method);
this.tag.setEnctype(enctype);
this.tag.setOnsubmit(onsubmit);
@@ -182,7 +182,7 @@ public class FormTagTests extends AbstractHtmlElementTagTests {
String onsubmit = "onsubmit";
String onreset = "onreset";
this.tag.setCommandName(commandName);
this.tag.setModelAttribute(commandName);
this.tag.setServletRelativeAction(action);
this.tag.setMethod(method);
this.tag.setEnctype(enctype);
@@ -216,7 +216,7 @@ public class FormTagTests extends AbstractHtmlElementTagTests {
@Test
public void withNullResolvedCommand() throws Exception {
try {
tag.setCommandName(null);
tag.setModelAttribute(null);
tag.doStartTag();
fail("Must not be able to have a command name that resolves to null");
}

View File

@@ -1,59 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="index" class="org.springframework.web.servlet.mvc.annotation.IndexController"/>
<bean id="welcome" class="org.springframework.web.servlet.mvc.annotation.WelcomeController"/>
<bean id="admin" class="org.springframework.web.servlet.mvc.annotation.AdminController"/>
<bean id="buy" class="org.springframework.web.servlet.mvc.annotation.BuyForm"/>
<bean name="/myFile" class="org.springframework.web.servlet.mvc.UrlFilenameViewController"/>
<bean name="/myFile2" class="org.springframework.web.servlet.mvc.UrlFilenameViewController"/>
<bean id="mapping" class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
<!--
We have to revert the default exclude for "org.springframework.web.servlet.mvc",
since our test controllers sit in this package.
-->
<property name="excludedPackages"><list></list></property>
<property name="excludedClasses" value="org.springframework.web.servlet.mvc.UrlFilenameViewController"/>
</bean>
<bean id="mapping2" class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
<!--
We have to revert the default exclude for "org.springframework.web.servlet.mvc",
since our test controllers sit in this package.
-->
<property name="excludedPackages"><list></list></property>
<property name="excludedClasses" value="org.springframework.web.servlet.mvc.UrlFilenameViewController"/>
<property name="caseSensitive" value="true"/>
<property name="pathPrefix" value="/myapp"/>
<property name="basePackage" value="org.springframework.web.servlet"/>
</bean>
<bean id="mapping3" class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
<!--
We have to revert the default exclude for "org.springframework.web.servlet.mvc",
since our test controllers sit in this package.
-->
<property name="excludedPackages"><list></list></property>
<property name="excludedClasses" value="org.springframework.web.servlet.mvc.UrlFilenameViewController"/>
<property name="caseSensitive" value="true"/>
<property name="pathPrefix" value="/myapp"/>
<property name="basePackage" value="org.springframework.web.servlet.mvc.annotation"/>
</bean>
<bean id="mapping4" class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
<!--
We have to revert the default exclude for "org.springframework.web.servlet.mvc",
since our test controllers sit in this package.
-->
<property name="excludedPackages"><list></list></property>
<property name="excludedClasses" value="org.springframework.web.servlet.mvc.UrlFilenameViewController"/>
<property name="pathPrefix" value="myapp/"/>
<property name="basePackage" value=""/>
</bean>
</beans>

View File

@@ -1,59 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="index" class="org.springframework.web.servlet.mvc.mapping.Controller"/>
<bean id="welcome" class="org.springframework.web.servlet.mvc.mapping.WelcomeController"/>
<bean id="admin" class="org.springframework.web.servlet.mvc.mapping.AdminController"/>
<bean id="buy" class="org.springframework.web.servlet.mvc.mapping.BuyForm"/>
<bean name="/myFile" class="org.springframework.web.servlet.mvc.UrlFilenameViewController"/>
<bean name="/myFile2" class="org.springframework.web.servlet.mvc.UrlFilenameViewController"/>
<bean id="mapping" class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
<!--
We have to revert the default exclude for "org.springframework.web.servlet.mvc",
since our test controllers sit in this package.
-->
<property name="excludedPackages"><list></list></property>
<property name="excludedClasses" value="org.springframework.web.servlet.mvc.UrlFilenameViewController"/>
</bean>
<bean id="mapping2" class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
<!--
We have to revert the default exclude for "org.springframework.web.servlet.mvc",
since our test controllers sit in this package.
-->
<property name="excludedPackages"><list></list></property>
<property name="excludedClasses" value="org.springframework.web.servlet.mvc.UrlFilenameViewController"/>
<property name="caseSensitive" value="true"/>
<property name="pathPrefix" value="/myapp"/>
<property name="basePackage" value="org.springframework.web.servlet"/>
</bean>
<bean id="mapping3" class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
<!--
We have to revert the default exclude for "org.springframework.web.servlet.mvc",
since our test controllers sit in this package.
-->
<property name="excludedPackages"><list></list></property>
<property name="excludedClasses" value="org.springframework.web.servlet.mvc.UrlFilenameViewController"/>
<property name="caseSensitive" value="true"/>
<property name="pathPrefix" value="/myapp"/>
<property name="basePackage" value="org.springframework.web.servlet.mvc.mapping"/>
</bean>
<bean id="mapping4" class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
<!--
We have to revert the default exclude for "org.springframework.web.servlet.mvc",
since our test controllers sit in this package.
-->
<property name="excludedPackages"><list></list></property>
<property name="excludedClasses" value="org.springframework.web.servlet.mvc.UrlFilenameViewController"/>
<property name="pathPrefix" value="myapp/"/>
<property name="basePackage" value=""/>
</bean>
</beans>

View File

@@ -1,24 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="index" class="org.springframework.web.servlet.mvc.mapping.Controller"/>
<bean id="welcome" class="org.springframework.web.servlet.mvc.mapping.WelcomeController"/>
<bean id="admin" class="org.springframework.web.servlet.mvc.mapping.AdminController"/>
<bean id="buy" class="org.springframework.web.servlet.mvc.mapping.BuyForm"/>
<bean name="/myFile" class="org.springframework.web.servlet.mvc.UrlFilenameViewController"/>
<bean name="/myFile2" class="org.springframework.web.servlet.mvc.UrlFilenameViewController"/>
<bean id="mapping" class="org.springframework.web.servlet.mvc.support.ControllerBeanNameHandlerMapping">
<!--
We have to revert the default exclude for "org.springframework.web.servlet.mvc",
since our test controllers sit in this package.
-->
<property name="excludedPackages"><list></list></property>
<property name="excludedClasses" value="org.springframework.web.servlet.mvc.UrlFilenameViewController"/>
</bean>
</beans>