Spring 3.0 URL pattern validation - spring

I'm wanting to to add an endpoint like /user/foo where foo is one of a set of values determined at runtime. I'm wondering what the best way is to do this in Spring, or indeed if it should even been done in Spring an not handled at the controller level.
I'm currently using Springs security filter chain, so I did think about putting a filter in front of /user/* to do this validation. Is this a reasonable solution or is there a more desirable solution I have missed?

You can use #PathVariable annotation on a method argument. #PathVariable also allows regex if you need to validate the structure of the varible.
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping
http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/bind/annotation/PathVariable.html
and for the regex
http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html

Related

Should we perform db operation using #PathVariable in Spring?

GET should be used for viewing something, without changing it, while POST should be used for changing something. For example, a search page should use GET, while a form that changes your password should use POST.
So in Spring we have #PathVariable annotation and we can access it in our controller.
My questions is:
1)Should we use path variable in our controller to perform any DB operation like delete or update as it seems clearly in the URL.If yes then it can be a hole in our application that anyone can make that request again.
I know that we can use #RequestParam with POST method in spring as well as with GET method but I just want to know that if it is okay to use PathVariable to change our database.
It is not a matter of #RequestParam, #RequestBody, or #PathVariable. You should check for correct user ROLES to do the database operation as long as these three methods can be automated using tools. Pure case of logic!
There is no matter if you use #PathVariable or #RequestParam.
I think the important part you have to think about is, that you can use hidden input fields. And they can be catched with the #RequestParam annotation.
So I would say it depends on what you want to show in your url and what you want to "hide".

Default handler mapping for annotation based spring project

I am new to spring framework. Even I dont have any deep concept about annotation.
I am developing a very small application using spring mvc 3 framework and also I used annotation.
I have a confusion. I have one spring-servlet.xml. Here I have not defined any handler mapping. But still it is working. So must be there some default handler mapping. Can you please let me what is this default handler mapping and how I can override it so that I do some customization.
It is all explained in: http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-config
Also see this question: How to use default-servlet-handler and Where to put default-servlet-handler in Spring MVC configuration
Spring 3.1 and later doesnt need DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter declaration in the [servelt-name]-servlet.xml
These links might help:
Spring Controller to handle all requests not matched by other Controllers
https://dzone.com/articles/using-the-spring-requestmapping-annotation
I had the same problem that I just resolved so I have confirmed the approach below works, although this is with annotations rather than an XML configuration.
You specify URL prefixes at the controller class level and include a request mapping annotation for ** to ensure you match on anything that falls through your other handlers for this class. There's really nothing special or default about this handler other than the fact that you're defining a handler that is guaranteed to match everything under the class level mappings.
Note: This is not magic. Your handlers are still subject to Spring's ordering algorithm regarding the "best match". It would be nice to have an annotation providing for a true default when nothing else matches handler, especially in cases with complex mappings where "**" is useful outside of this catch-all handler. The basic implementation is:
#RestController
#RequestMapping(value={"/path1/","/path2/"})
public class MyRestController {
#RequestMapping("/subpath")
String matchedRequestHandler () {
return "This matches /path1/subpath and /path2/subpath.";
}
#RequestMapping("**")
String unmatchedRequestsHandler () {
return "This matches everything else.";
}
}
In my actual use case, I needed to handle arbitrary paths to resources inside of the URL pattern and therefore needed to support a variable number of directories. Ideally, that would be handled using a pattern such as:
"/base/{optionaldir}/**/{entityName}/{describeVar:describe.json}"
which works fine by itself, but it isn't compatible with a default handler bound to "**" since the "**" mapping is calculated by Spring as a better match for these types of requests.
Instead, I had to add a bunch of separate entries to my request mapping to support the arbitrary paths within the URL pattern, e.g.
value={"/base/{optionaldir}/{entityName}/{describeVar:describe.json}",
"/base/{optionaldir}/*/{entityName}/{describeVar:describe.json}",
"/base/{optionaldir}/*/*/{entityName}/{describeVar:describe.json}",
"/base/{optionaldir}/*/*/*/{entityName}/{describeVar:describe.json}"
}
Alternatively, I could have handled everything with a "**" mapping and parsed the URL myself, but that kind of defeats the purpose of using request mappings with path variables. Hopefully Spring's capabilities will evolve in this area in the future.

Spring 3 Field Formatting

I am looking at using the Spring's Field formatting in particular the existing DateFormatter. I do understand that I need to specify a pattern on an annotation in my POJO.
Instead of hard coding the pattern I need to be able to provide it dynamically, I know this is not feasible with annotations. To properly support internationalization I would need to look up a pattern from a properties file before passing it to a Formatter.
Can anyone suggest an approach I can take?
Not sure however you may try implementing InitializingBean or init-method and set the values dynamically.
like suggested in spring forum for cron expression.

Best practice for validating a URL with Spring-MVC?

I am using Spring MVC for my web application.
I need to validate that the URL the user inputs is valid and was wondering if there is something in Spring that can do the basic checks for me (for example starts with http/https, has domain name etc).
ValidationUtils only contains very basic checks and I know I can write a regular expression in the validate() method however prefer to avoid it inm case someone has already done it :)
Thanks
In the past, I have always utilized Hibernate Validator. Simply annotate the appropriate field in your form bean with a #URL constraint.
If you've never used the ORM part of Hibernate before, don't let that scare you. The Validator portion is not dependent on the ORM stuff, and integrating it into Spring is very straightforward.
If for some reason you can't use Hibernate Validator... or you just want to stick with what you're comfortable with, a good place for regex's is RegExLib.com; several patterns that can match a URI are listed there.
Ended up using UrlValidator from apache commons.
I know this question is quite old, but I just need the same and I think I'll go with the PropertyEditors in SpringFramework.
More precisely there is URLEditor, which you can use to convert a String representation to an actual URL object.
Here is a link to the respective documentation:
http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-beans-conversion
http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/propertyeditors/URLEditor.html
In my case, I think about using the following code within a Spring Validator to check whether a String entered by a user is a valid URL or not:
try {
PropertyEditor urlEditor = new URLEditor();
urlEditor.setAsText(field.getValue());
} catch (IllegalArgumentException ex) {
errors.rejectValue("nameOfTheFieldToBeValidated", "url_is_invalid");
}
However, as for now, I'm unsure whether it is possible to configure which protocol is going to be accepted as valid (i.e. URLEditor seems to also accept URLs starting with "classpath:")
Use a spring interceptor:
http://java.dzone.com/articles/using-spring-interceptors-your

How can I bind fieldName_1, fieldName_2 to a list in spring mvc

I'm trying to convert a struts 1 application to Spring MVC 3.0. We have an form with quite a few parameters, most of which where automatically binded in struts. However there where a number of fields in the format fieldName_# where # is a number that we manually bound by looping through the request.
I'm looking for a tidier way to do this in Spring mvc, but don't know where to start.
Ideally we should have them as fieldName[#] and it would be easier, but we cannot change this and have to keep the fieldName_# format. Also the number of these fields that are sent in the request are unknown.
One way to achieve this is by wrapping the servletRequest and implementing the getParameter (and associated methods) such a way that parameters with name fieldName_# are returned as fieldName[#]. A servletFilter would be one option to wrap the request.

Resources