Best practice for validating a URL with Spring-MVC? - spring

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

Related

Spring boot/CRNK Custom Query Spec URL Mapping For Single Endpoint

I'm currently trying to change the functionality of the QuerySpecUrlMapper for only one specific endpoint. In particular, we want to disable the behavior that splits a string parameter by commas. I've figured out I can do this by getting the default URL mapper and calling setAllowCommaSeparatedValue, but I'm not sure how to do this for the specific endpoint I want. We're using Spring, and I tried Autowiring CrnkBoot into my Repository object so I could get the UrlMapper that way, but this breaks the whole thing in strange ways I don't yet understand. Some exception about "Cipher not initialized"
Anyone have ideas about how to handle this?

How to add a custom ContentHander for JAXB2 support in Spring 3 (MVC)?

Scenario: I have a web application that uses Spring 3 MVC. Using the powerful new annotations in Spring 3 (#Controller, #ResponseBody etc), I have written some domain objects with #XML annotations for marhalling ajax calls to web clients. Everything works great. I declared my Controller class to have a return type #ResponseBody with root XML object - the payload gets marshalled correctly and sent to Client.
The problem is that some data in the content is breaking the XML compliance. I need to wrap this with CDATA when necessary. I saw a POST here How to generate CDATA block using JAXB? that recommends using a custom Content Handler. Ok, fantastic!
public class CDataContentHandler extends (SAXHandler|XMLSerializer|Other...) {
// see http://www.w3.org/TR/xml/#syntax
private static final Pattern XML_CHARS = Pattern.compile("[<>&]");
public void characters(char[] ch, int start, int length) throws SAXException {
boolean useCData = XML_CHARS.matcher(new String(c,start,length)).find();
if (useCData) super.startCDATA();
super.characters(ch, start, length);
if (useCData) super.endCDATA();
}
}
Using Spring MVC 3, how do I achieve this? Everything was "auto-magically" done for me with regards to the JAXB aspects of setup, Spring read the return type of the method, saw the annotations of the return type and picked up JAXB2 off the classpath to do the marshalling (Object to XML conversion). So where on earth is the "hook" that permits a user to register a custom Content Handler to the config?
Using EclipseLink JAXB implementation it is as easy as adding #XmlCDATA to the Object attribute concerned. Is there some smart way Spring can help out here / abstract this problem away into a minor configuration detail?
I know Spring isn't tied to any particular implementation but for the sake of this question, please can we assume I am using whatever the default implementation is. I tried the Docs here http://static.springsource.org/spring-ws/site/reference/html/oxm.html but it barely helped at all with this question from what I could understand.
Thanks all for any replies, be really appreciated.
Update:
Thanks for the suggested answer below Akshay. It was sufficient to put me on right tracks. Investigating further, I see there is a bit of history with this one between Spring version 3.05 and 3.2. In Spring 3.05 it used to be quite difficult to register a custom MessageConverter (this is really the goal here).
This conversation pretty much explains the thinking behind the development changes requested:
https://jira.springsource.org/browse/SPR-7504
Here is a link to the typically required class override to build a cusom solution:
http://static.springsource.org/spring/docs/3.1.0.M1/javadoc-api/org/springframework/http/converter/AbstractHttpMessageConverter.html
And the following Question on stack overflow is very similar to what I was asking for (except the #ResponseBody discussion relates to JSON and jackson) - the goal is basically the same.
Spring 3.2 and Jackson 2: add custom object mapper
So it looks like usage of , and overriding MarshallingHttpMessageConverter is needed, registering to AnnotationMethodHandlerAdapter. There is a recommended solution in link above to also get clever with this stuff and wrap the whole thing behind a custom defined Annotation.
I haven't yet developed a working solution but since I asked the questions, wanted to at least post something that may help others with the same sort of question, to get started. With all due respect, although this has all improved in Spring 3.2, it's still bit of a dogs dinner to get a little customization working... I really was expecting a one liner config change etc.
Rather than twist and bend Spring, perhaps the easiest answer for my particular issue is just to change JAXB2 implementation and use something like Eclipse Link JAXB that can do this out of the box.
Basically you need to create a custom HttpMessageConverter. Instead of relying on the Jaxb2RootElementHttpMessageConverter that spring uses by default.
Unfortunately, customizing one converter means you are telling spring that you will take care of loading all the converters you need! Which is fairly involved and can get complicated, based on whether you use annotations, component scanning, Spring 3.1 or earlier, etc.. The issue of how to add a custom converter is addressed here: Custom HttpMessageConverter with #ResponseBody to do Json things
In your custom message converter you are free to use any custom JAXB2 content handlers.
Another, simpler approach to solve your original problem would be to use a custom XmlJavaTypeAdapter. Create a custom implementation of javax.xml.bind.annotation.adapters.XmlAdapter to handle CDATA, in the marshal method wrap the return value with the cdata braces. Then in your mapped pojo, use the XmlAdapter annotation, pass it the class of your custom adapter and you should be done.
I have not myself implemented the adapter approach, so couldn't provide sample code. But it should work, and won't be a lot of work.
Hope this helps.

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.

Spring 3.0 URL pattern validation

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

struts2 validation invoking xml

i have a login-validation.xml which define some basic field validation rules.
however that's not enough for me.
i need to do some more database lookup and i consider this as part of my validation logic.
how can i do both xml validation and my database lookup in one go?
i suppose i will write something like
public void validate() {
1) struts2-validation.xml validation();
2) myDatabaseLookup() and addFieldError() or addActionError();
}
my problem is, what is the api i can use for (1)?
or, how can i look at the code of this xml validation filter class? in fact i would also make the definitions in validation.xml available to javascript usage... i guess i would need to do some translation from xml to javascript logic, but first of all, how can i access the validation.xml api in java code?
Your best choice is to create a validator... Take a look here for some information -
Custom Validator
There are a few things to keep in mind... I don't know if the ObjectFactory will instantiate and inject your validator, so you might not have all the features of dependency injection. If your custom validator isn't injected, file a bug, I'll take a look at it.
After you create your validator and register it in your app, you can add it to the validation.xml file.
(side note, I know that I am pointing to the XWork docs, but Struts2 uses XWork internally for most of it's validation capabilities)

Resources