Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I've read this guide: http://spring.io/guides/gs/validating-form-input/
I see that the spring's approach of validating a form is to annotate the
properties of a object (which can be a POJO), with validation constraints
like #Min, #Max, #Size, etc..
This is not the best approach to mess-up POJO objects with this
annotations.
How do you write your code for validation a form in spring framework?
Spring offers a design for validation (and data binding) that does not exclude either one of them. Spring features a Validator interface that you can use to validate objects.
The Validator interface works using an Errors object so that while validating, validators can report validation failures to the Errors object.
Person POJO:
public class Person {
private String name;
private int age;
// the usual getters and setters...
}
Implementing a Validator:
public class PersonValidator implements Validator {
/**
* This Validator validates just Person instances
*/
public boolean supports(Class clazz) {
return Person.class.equals(clazz);
}
public void validate(Object obj, Errors e) {
ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
Person p = (Person) obj;
if (p.getAge() 110) {
e.rejectValue("age", "too.darn.old");
}
}
}
Documentaction about Validation, Data Binding in Spring Framework 3.x
There is definitely some debate about whether or not you should use annotations on the POJO or not.
My personal opinion is that if you are not going to be sharing the POJO between modules, annotation configuration is perfectly acceptable.
If you want the validation constrains to be configured without annotations, you should look at Hibernate Validator's (Hibernate Validator is the reference implementation of this JSR 349) XML configuration. The reference for that configuration is here.
Also check out this (somewhat older) post for a tutorial.
Related
I'm taking my first swing at creating a RESTful API with OAS 3.0, Swagger Codegen, Spring MVC, and Spring HATEOAS. I want to use the OAS definition for documentation generation and server/client stub generation and use HATEOAS to create hyperlinks related resources.
I currently have my resources extending ResourceSupport and can add my links such that the responses have the _embedded and _links fields that I would expect. My issue is how to properly map the HATEOAS Resource to the model generated by Swagger codegen. My OAS definition matches the hal+json response, so the fields are identical in the swagger model and my HATEOAS Response.
Is there a way to easily map these? I'm also willing to accept that I am interpreting this incorrectly and that these frameworks don't really mesh together.
OAS example:
responses:
200:
description: ...
content:
application/hal+json:
schema:
$ref: '#/components/schemas/OasPersonResponse'
components:
schemas:
OasPersonResponse:
type: object
properties:
firstName:
type: string
lastName:
type: string
_links:
type: object
properties:
self:
type: object
properties:
href:
type: string
Resource example:
public class PersonResource extends ResourceSupport {
private final Person person;
public PersonResource(Person person) {
this.person = person;
}
public String getFirstName() {
return person.getFirstName();
}
public String getLastName() {
return person.getLastName();
}
}
Controller Example:
#Controller
public class PersonController implements PersonApi {
#Override
public ResponseEntity<OasPersonResponse> getPersonById(Integer personId) {
Person person = someDb.getPerson(personId);
PersonResource personResource = new PersonResource(person);
personResource
.add(linkTo(methodOn(PersonController.class)
.getPersonById(personId))
.withSelfRel();
Resource<PersonResource> returnResource =
new Resource(personResource);
return new ResponseEntity<>(returnResponse, HttpStatus.OK);
}
My issue is with the stub generated by swagger codegen expecting a return type of ResponseEntity<OasPersonResponse> but have a reference to a Resource<PersonResource>. Both OasPersonResponse and PersonResource represent the same data but the OasPersonResponse explicitly defines the _links object whereas the response with the PersonResource gets serialized to have the _links object.
Is there an easy way for me to convert the HATEOAS Resource to the model that was created by swagger codegen?
Thanks in advance for the help and guidance.
I'm currently working on a very similar project!
Firstly, if you can, I'd recommend using the 1.0.0.RC1 version of spring-hateoas as it has some pretty major quality of life improvements over the 0.25.x release branch. Of major relevance is that using the EntityModel wrapper class is now the recommended practice, which means you can just leave the relations out of your base entity specification. (The downside is this reduces the immediate utility of the OpenAPI spec; I haven't quite figured out how to reconcile that yet.)
Secondly, I'm afraid there doesn't seem to be much existing work on the swagger-codegen side as far as supporting Spring HATEOAS is concerned; in fact, I keep running into annoying bugs with the plain Spring "language" generator.
So either we can write our own swagger-codegen generator for spring-hateoas, or just heavily customize some templates to get "close enough" (there's less of this needed when using the EntityModel wrapper rather than extending ResourceSupport). I've gone with the latter approach so far, for what that's worth.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a generic abstract template class. I thought if I create type-specific Producers, I could inject some DAO service directly in the generic class. But I can't.
Why? And how could I work around this?
abstract class MyView<T> {
#Inject
MyDao<T> dao;
//some more template methods that make use of the dao
void someMethod() {
dao.use();
}
}
class CustomerView extends MyView<Customer> {
//javax.enterprise.inject.AmbiguousResolutionException: Ambigious resolution
}
class DaoManager {
#Produces
MyDao<Customer> getDaoCustomer() {
return DaoFactory.make(Customer.class);
}
#Produces
MyDao<Product> getDaoProduct() {
return DaoFactory.make(Product.class);
}
}
When I inject eg a #Inject MyDao<Customer> dao; it works perfectly. But not with generics...
When you request
#Inject MyDao<Customer> dao;
the container knows that you want a bean specifically of type MyDao<Customer>. If such a bean exists and its type information is known, then the container can satisfy the injection. For example, the type information is preserved in your #Produces annotated method
#Produces
MyDao<Product> getDaoProduct() {
The container uses reflection to retrieve that parameterized type and can match it to the requested #Inject field.
With
abstract class MyView<T> {
#Inject
MyDao<T> dao;
however, all the container knows is that you want a MyDao. T is a type variable, not a concrete parameterization. The container cannot assume a specific type for it. In your case, both of the #Produces beans would match and there would be ambiguity.
In your example, we know from the context that it really wants a MyDao<Customer>. That doesn't seem to be something your container is capable of doing, ie. trying to resolve the type parameter to a concrete type argument for a parameterized subclass.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I'm looking for argument validation framework which:
1) Allows specifying argument constraints via annontations (like OVal, JaValid)
2) Validation code automatically injected (during compilation or runtime) into methods (i.e. no explicit call to Validator object is required)
Example of what i'm looking for:
public class Person {
private String name;
....
//Method which arguments should be validated
public void setName(#NotBlank String name){
//<---validating code should be injected here
this.name = name;
}
}
//Example of call to the validated method
...
Person person = new Person();
person.setName("John");
...
Example of code i'm trying to avoid
...
Validator validator = new Validator(...);//glue code
Person person = new Person();
person.setName("John");
validator.validate(person);//glue code
...
Thanks for answers!
I think you meant "automatically injected during compilation or runtime", right?
I had the same problem. My solution was Spring Validation and self-written AOP layer (about three classes).
My validation code looks like this:
#Validational( validators =
{"com.mycompany.MyValidator"} )
public void myMethod( String paramToValidate )
I am learning myself Spring MVC 2.5 mostly from the docs. Can someone explain the following:
Advantages/differences of using command objects versus using #ModelAttribute to pass in the object.
Is there an easier way to do validation other then writing a Validator object?
Also, in this code how does the line ValidationUtils.rejectIfEmpty(e, "name", "name.empty"); work? How can it check if the name is empty on the person object when the person object is not passed in?
public void validate(Object obj, Errors e) {
ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
Person p = (Person) obj;
if (p.getAge() < 0) {
e.rejectValue("age", "negativevalue");
} else if (p.getAge() > 110) {
e.rejectValue("age", "too.darn.old");
}
}
(this code is from section 5.2 from the docs)
Thanks
The question about command object is not very clear. If you mean the following syntax
#RequestMapping(...) public ModelAndView foo(Command c) { ... }
then it is the same as the following
#RequestMapping(...) public ModelAndView foo(#ModelAttribute Command c) { ... }
because #ModelAttribute can be omitted. The only case when it's actually needed is then you need to specify attribute name explicitly (otherwise it would be inferred as a class name with the first letter decapitalized, i.e. command)
In Spring 2.5 - no. In Spring 3.0 you can use declarative validation with JSR-303 Bean Validation API.
The Errors object has a reference to the object being validated.
Here is the answer of your first question.
http://chompingatbits.com/2009/08/25/spring-formtag-commandname-vs-modelattribute/
according to my experience there isn't easier way to fullfill validation, because it's easy enough. You can get it easier integrating libraries such as commons-validator into your project and use pre-defined validation rules in your forms.
http://numberformat.wordpress.com/tag/spring-mvc-validation/
and also with 3rd version of Spring you can use Bean validation using annotations.
I don't want use XmlJavaTypeAdapter annotations with XmlAdapter's class in my code directly.
So, I wrote some wrapper:
class BinderWrapper<MODEL, BEAN> extends XmlAdapter<BEAN, MODEL>{
private final Binder<MODEL, BEAN> target;
private BinderWrapper(Binder<MODEL, BEAN> target){
this.target = target;
}
static <MODEL, BEAN> BinderWrapper<MODEL, BEAN> createInstance(Binder<MODEL, BEAN> binder){
return new BinderWrapper<MODEL, BEAN>(binder);
}
#Override
public MODEL unmarshal(BEAN v) throws Exception {
return target.unBean(v);
}
#Override
public BEAN marshal(MODEL v) throws Exception {
return target.toBean(v);
}
}
that's wrappes my binders like XmlAdapter s. All my binders will implements Binder interface
public interface Binder<MODEL, BEAN> {
MODEL unBean(BEAN bean);
BEAN toBean(MODEL model);
}
But there is a problem. #XmlJavaTypeAdapter require XmlAdapter class without any wrapper. How I can solve this problem? - use other annotation / write some config / write some magic annotation /..
Thanks.
upd
I have model classes that aren't JavaBeans. So I want do some two step mapping : in beans and than into xml. I want do first step with annotations too. Probably I well need this beans not only for JAXB. The real question is : can I do first step with some non JAXB annotations?
I have model classes that aren't
JavaBeans. So I want do some two step
mapping : in beans and than into xml.
I want do first step with annotations
too. Probably I well need this beans
not only for JAXB. The real question
is : can I do first step with some non
JAXB annotations?
The XmlAdapter provides the two step mapping you are looking for. If you look at the example linked below Map is the object that is not a Java Bean. What the XmlAdapter does is convert it to a Java Bean that can be mapped.
You may find it easier to use the #XmlJavaTypeAdapter annotation at the type level rather than the property level. When used at the type level you are saying everyone that references that class should use the adapter instead of per property. See my post on JAXB and Immutable Objects for a type level example.
For more information see:
http://bdoughan.blogspot.com/2010/07/xmladapter-jaxbs-secret-weapon.html
http://bdoughan.blogspot.com/2010/12/jaxb-and-immutable-objects.html