Pregunta

I am writing a web application using JSP, with a mysql database that keeps track of all the users. In a web page I use a form to allow users to register.

In my database, for example the username of an user has a maximum of 20 characters, so I would avoid to allow an user to register with an username longer than 20. In my application I am strictly separating all levels, so there's a strong separation between services, business logics, business flows and the presentation level done with JSP pages.

My concern is about where I should check that any given field is correct. In business logics I implement a class that abstracts the concept of an user, allowing to create a new user and inserting it in my database. In business flows (that is beans) I can elaborate all the HTTP parameters received, so I know all the fields values. I could do it in my JSP page, even with javascript analyzing every inserted field and conditionally submitting the form, in beans or in my "user" class. Which one would be the most correct?

¿Fue útil?

Solución

Assuming you're using a pattern close to MVC

The input validation is relevant to the controller part. It's up to your controller to process data, then display user friendly error message by passing these errors message to your view. Any processing have to be done in the controller and validating data is processing.

Anyway, an extra security on model isn't a bad thing, but in this case it's totally useless because you database engine will truncate (or throw an error) if you're inserting more than 20 characters, so security is allready in place.

Models are only meant to acces and store data, not validate it! (Except some rare case when data storage need validation and when database structure don't check integrity by itself).

But again, these are just concepts, you're free to adopt concepts in the way you like. As long as you're consistent across your application (don't do some validations in models, some in controllers, and why not some in view if we are at that!)

Otros consejos

I would do it in the model class.

What you must not do is doong the validation with javascript in the client, because the user can disable JS

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top