Given a Spring-MVC controller method:
@RequestMapping(value = "/method")
public void method(ParamModel params) { /*...*/ }
with model class:
public class ParamModel { public int param1; }
The following two results are as expected/desired:
param1=1
: method
completes successfully.param1=blah
: JBWEB000120: The request sent by the client was syntactically incorrect.
However...
nonexistentparam=1
), there is no error.Is there a way to ensure the request is validated and rejected if it includes any parameters that aren't part of this API?
You can use filter to check for invalid parameters as
web.xml
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>com.mypackage.filter.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
MyFilter Class
import javax.servlet.Filter;
public class MyFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
String requestUrl = request.getParameter("param1");
//here I am considering 'param1=1' as valid request rest of all are invalid
if(!requestUrl.equals("1")) {
logger.info("Invalid Request");
//for invalid request redirect to error or login page
response.sendRedirect("/error"");
} else {
logger.info("Valid Request");
}
}
public void init(FilterConfig filterConfig) throws ServletException {
}
}
hope this will solve your problem
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With