controller in spring for form handling - java

I am newbie in spring. using spring 3.0 mvc.
I am creating a spring application, I have a login form,Any one please suggest what controller i should use, as when I am using SimpleFormController its saying deprecated,
Any specific controller I can use.

First of all as everybody already told you use annotation-base controller
secondly for creating a form you can use spring form taglib
thirdly you can create method like this
public String updateHouse(House house, #RequestParam("file") MultipartFile file, Model model) {
this is from my sample application. House object is auto generated from form. In my form I have fields of my House object and it is send to the method as object. #RequestParam allows me to fetch the file witch is uploaded via form (POST), Model is my view model.
As you can see it is easy :)

Why don't you try annotation-based controllers? They are easy and fun to use.

You can try annotation based controller. Please refer below link:
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html

Related

Am I still using spring-mvc (MVC architecture) if my backend only returns a json response to the frontend

There are a lot of definitions on what MVC is, but most of them say that the user contacts the controller and then the controller changes the view and sends it to the user. If I am using React.js for my frontend and calling endpoints in my controller, am I still using MVC pattern or not?
Is the #Controller even the same thing as the controller in MVC because in the definitions it says that the controller handles the application logic which in my case it does not I have service classes for that. I am writing an essay and I don't even know what type of application I am creating. It is driving me nuts.
Yep, it's still MVC. In this case you have controller (Spring #Controller or #RestController and React) model (services) and view (html generated by React). There is no strict definition what is MVC.
In MVC controller should not contain logic themself, but communicate with model (your services), this is the correct layered backend architecture. Otherwise, the Single Responsibility Principle is violated.
Spring Controller i.e., #Controller is the responsible person to provide the view the user requested if you need only the view page, it can be anything .html,.JSP and many more. So, if the user requested for any page either by the react.js or anything like angular then it calls the dispatcher servlet of the spring front controller and calls the handler mapper to which controller the user have requested.
If you requested something from the client to provide or do some crud operation then Rest Controller comes into the picture where #RestController...#Service...#Repository is been used.
So indirectly, the spring provides the way where developers can define the user request in the model view and controller format in which it segerrate the things separately and provides more convenient way to organise the code it looks like and spring have assigned annotations where it marks the class the responsibility it should behave.

How do I configure validation check in Spring MVC with JSP?

I need a quick help regarding validation check in Spring MVC. I have a basic HTML form not the JSTL Tag form. How do I check or implement a straight forward data validation check in Spring MVC? One way in my mind coming right now is to use regex to verify the user name is alphanumeric [a-zA-Z0-9].
But I have seen people use Validator do this job. I want to use Validator as it seems more profession.
Second question,
I'm trying to get a Exception handling working properly but it is not working. I want the absolute basic response to happen, the response throws a HTTP.404 response. My simple method:
#RequestMapping(value="/request/view/{id}",method=RequestMethod.GET)
public String requestSubmit(Model model)
Now with my response String, how can I do it? After search on Stackoverflow. They said to create a generic class such as NotFoundException and extend it RunTimeException. But I still don't know how to I set the response intentionally to be 404 or any other response actually, even Http.BANDWIDTH_EXCEEEDED_RESPONSE
Fist thing you should know: it's better to use POST instead of GET in form submitting. Because when you use GET, all your model properties sent as url parameter and it's not a good practice.
For using validation, you can use #Valid as this:
public String requestSubmit(#Valid Model model)
Then you can use validation annotation like #NotNull, #Size, ... at every property of Model class you want to validate it.
When a user submits your form, if every form attribute has validation problem, spring throws MethodArgumentNotValidException automatically. For getting validation errors, you can use try-catch block in your controller or better way is to have central exception handler with #ControllerAdvice.

The Model parameter in #RequestMapping method

Currently I am learning Spring specifically the Spring MVC part and I stumbled on thing I don't quite understand how does it work.
#RequestMapping("/foo")
public String foo(Model model){
// code here
return "foo";
}
The method above annotated with #RequestMapping receive the parameter with class Model and sometimes ModelAndView.
What I don't understand is where the Model parameter comes from and how the flow is from the spring configuration class (Such as WebConfig.java) which use the ComponentScan and a Bean of InternalResourceViewResolver.
I've been looking for sources and I don't find anything helpful for me, even the documentation, which makes me to ask here for the first time.
A direct explanation will be really helpful, or if there are any sources can be put the link here.
If it is from the documentation please mention which part/section it is because I might miss one or two thing.
The method above annotated with #RequestMapping receive the parameter
with class Model and sometimes ModelAndView.
The below post explains in detail about ModelAndView and Model
When to use ModelAndView vs Model in Spring?
where the Model parameter comes from
A Controller is typically responsible for preparing a model Map with data and selecting a view name but it can also write directly to the response stream and complete the request. View name resolution is highly configurable through file extension or Accept header content type negotiation, through bean names, a properties file, or even a custom ViewResolver implementation. The model (the M in MVC) is a Map interface, which allows for the complete abstraction of the view technology. You can integrate directly with template based rendering technologies such as JSP, Velocity and Freemarker, or directly generate XML, JSON, Atom, and many other types of content. The model Map is simply transformed into an appropriate format, such as JSP request attributes, a Velocity template model.
Reference - http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-arguments

Spring #RequestBody annotation in Restful web service

Thanks to #RestController I don't need to add annotation #ResposneBody, cause spring knows that it is rest controller, and he will not generate view, but instead it will return json object.
Unfortunately there is one more annotation related to this topic. It is #RequestBody, when controller method accept json object as a parameter. And it will have to be pointed before that parameter.
My question is there a way to get rid of that annotation (#RequestBody).? If my controller is rest controller (#RestController instead of regular #Controller) it should be demanded from spring?
No, you'll have to specify #RequestBody. A Java method can have only a single return value, and so the #ResponseBody is unambiguous, but there are multiple possible ways that mapped controller parameters might be interpreted (in particular, using #ModelAttribute with form encoding is a very common alternative to #RequestBody with JSON), and you'll need to tell Spring how to map the incoming request.

Spring form validation for plain HTML form

I need to validate some simple forms in my application. In these forms I have one or two input text to validate so I'd like to not create a specific ModelAttribute class for every form. I'd like to use instead plain HTML form and use #RequestParam annotations to handle POST parameters.
Is there a way to use Spring form validation in this situation (without using model attribute) or should I implement a backing-form object and a validator for each form?
Currently it is not possible to use #Valid on individual #RequestParam, #PathVariable etc. to trigger validation. This is the relevant feature request on the Spring Issue Tracker. Let's cross our fingers for Spring 4.1!
In your case, you will either have to use #ModelAttribute, or perform custom validation inside the controller (or maybe a Spring interceptor if you want the same validation to apply to multiple endpoints)
I think you can do this with Annotation. You can specifie for your parameters annotation like :
#Size(min=3, max=5)
#NotNull
#NotEmpty
...
Without a model attribute, Spring form Validation is not possible. Because Spring Form Validation depends on Spring Form Binding, which is a linkage between form elements and Model Attribute. So how small the form may be, create a DTO(Model Attribute), bind it to form and Perform Validations.
Definitely not possible using Spring's validation API (Errors object):
java.lang.IllegalStateException: An Errors/BindingResult argument is expected to be declared immediately after the model attribute, the #RequestBody or the #RequestPart arguments to which they apply
You could instantiate a model object, fill it with the data from the plain form and validate that object programmatically.

Categories

Resources