Struts 2 convert error - validation

I created an action in struts 2
class MyAction extends ActionSupport {
private List<User> users;
//getters and setters users
public String execute(){
users=//code to get users;
return SUCCESS;
}
}
I mapped this action class with url /MyAction and the success result is a jsp which displays the users when i open the url:
http: //localhost:8080/MyAction.action
When I open the page as:
http: //localhost:8080/MyAction.action?xyz=123
I do not get any error. But when I open the page as:
http: //localhost:8080/MyAction.action?users=123
Struts tries to call setUsers() method and fails to convert 123 to a list of Users. Hence I get an Conversion error.
Since the action is not expecting any parameter it should behave in same way to all extra parameters provided. It should not just ignore few and show error for others.
The solution that I was able to find for this problem is to make all the setter methods private except for the setters for expected parameters.
Does anyone has a better solution?

You can use ParameterNameAware.
The above link should make the usage clear.
Although as anu was suggesting, your action is generally a public interface. Struts2 exposes setters as a convenience, and a great convince it is. You should only have setters for input. The action then does all of its work at another layer (Business), which typically in turn uses another layer(or tier if you prefer), which accesses persistent data. You probably know this but by only putting what is appropriate in the action layer, life is made less complicated (your issue never comes up).

Anu's right. I think what you are trying to fix is not a problem, it is the framework's functionality itself.

Thanks for your replies. I understand that this is struts functionality, but what I'm pointing out is that if struts is ignoring other parameters (for which there is no setter) it should ignore all the parameters that the action does not require. But yes, there should be some way for specifying the list of acceptable parameters.
As Quaternion pointed out ParameterNameAware is a solution but this works when there is only one action method in the action class or all the action methods must accept the same list of parameters.
I have found another way of specifying the list of acceptable parameters for each action using the params interceptor.
<action name="xxx" class="yyy" method="action1">
<intercecptor-ref name="defaultStack">
<param name="params.excludeParams">regex</param>
</intercecptor-ref>
<!-- other code -->
</action>
in place of regex you specify the regular expression for the excluding the parameters except for the ones that are not excepted by your expression.

Related

How do I test form submission with Spring MVC test?

Most of my experience with creating controllers with Spring are for REST controllers that consume JSON formatted requests. I've been searching for documentation on how to do testing for form submission, and so far this is how I understand it should go using MockMvc:
MvcResult result = mockMvc.perform(post("/submit")
.param('title', 'test title')
.param('description', 'test description'))
.andReturn()
However, I'm not sure how to map the form parameters to a model object. I've seen the #ModelAttribute annotation pop up in my searches but I can't figure out how it should be used for mapping. In addition, this quick start guide from the official documentation does not elaborate on how things like th:object and th:field translate to HTML and subsequently to URL encoded form.
I have my controller code similar to the following:
#PostMapping('/submit')
def submit(#ModelAttribute WriteUp writeUp) {
//do something with writeUp object
'result'
}
I discovered through trial and error that my specific problem might have been Groovy specific. There test code and the controller code, it turns out, have no issues. To reiterate, for testing form submission, use the param method through perform method of MockMvcRequestBuilders. Another thing to note is that this doesn't seem to work if content type is not specified. Here's a sample test code that works for me:
MvcResult result = webApp.perform(post("/submit")
.contentType(APPLICATION_FORM_URLENCODED) //from MediaType
.param('title', 'test title')
.param('description', 'test description'))
.andReturn()
As you can see, it's not much different from what I posted originally. The controller code is pretty much just the same, with #ModelAttribute working just fine.
The problem with my setup though was that since I was using Groovy, I assumed that getters and setters were automatically generated in my WriteUp class. Here's how the WriteUp class looked originally:
class WriteUp {
private String title
private String description
}
I haven't written code in Groovy for a while, and the last time I did, classes like the one above can be assumed to have getters and setters implicitly. However, it turns out that is not the case. To solve my specific issue, I updated the access modifier in the fields to be default (package level):
class WriteUp {
String title
String description
}
I've seen the #ModelAttribute annotation pop up in my searches but I
can't figure out how it should be used for mapping.
When you mark your writeUp object with #ModelAttribute, then the Spring container populates the parameters (like title, description, etc..) from HttpServletRequest object & injects the object to the controller method, when the request comes to the server from the client (could be a Browser or MockMvc unit test client or anything else).
Also, few other basic points for your quick understanding:
(1) Controller methods are mapped to an URI and RequestMethod (like POST/GET/DELETE/PUT et..) like shown below:
#RequestMapping(value="/submit", method=RequestMethod.POST)
public String submit(#ModelAttribute WriteUp writeUp) {
//Call the service and Save the details
model.addAttribute("Writeup details added successfully");
return "writeUpResult"; //Returns to the View (JSP)
}
(2) #ModelAttribute will be mapped to an object (like your writeUp) for http POST/PUT requests where the html formd data is part of http body.
(3) #RequestParam or #PathParam will be used for http GET requests where the parameters are part of URL (i.e., not part of http body).
You can look here for understanding the DispatcherServlet request handling & Spring MVC basic web flow.

Java Spring #ModelAttribute method model name

I have been reading this forum for quite awhile and find it VERY useful, thank you to the contributors. I have a question that has plagded me for several weeks. And here it goes.
#RequestMapping(value="updateNote.htm",method=RequestMethod.POST)
public String updateNote(#ModelAttribute("note")NoteBean nb, BindingResult res,Model model){
daoobj.updateNote(nb.getName(),nb.getPath(), nb.getNote());
model.addAttribute("note",daoobj.getByName(nb.getName()));
return("success");
}
#RequestMapping(value="updateNote.htm",method=RequestMethod.GET)
public String updateNote(#ModelAttribute("note")NoteBean nb,Model model){
populateNoteBean();
model.addAttribute("note",daoobj.getByName(nb.getName()));
return("editNote");
}
#ModelAttribute("WHAT")
public NoteBean populateNoteBean() {
NoteBean nnb = new NoteBean();
return nnb;
}
With the method populateNoteBean() the model attribute is "WHAT". But, the name that I use is "note". So when I run the code, the NoteBean is correctly saved to the data base. My question is HOW?? It seems that the name "WHAT" should be "note" or that the model attribute is saving it as no name.
Thank for your time.
With your current code you will have two instances of your notebean in the model!
First spring invokes all modelattribute annotated methods in your controller and places the results in the model. Second it evaluates the ones from your requestmapping method.
The point of a modelattribute annotated method is that you can choose how to create your bean. Load it for example from a database.
We use this approach like that:
modelattr method (name="note")
Loads beans from db
requestmapping method with modelattr param (name="note")
Merges the note bean created by the first method with the request paramters from a submit for example and you habe directly access to the modifed one.
One nice effect:
We do not want to put hidden input fields for all attributes in a form just to be able to merge the entity with the entitymanager. This way you can have a form with only one attribute (plus one for the id to be able to fetch the entity)
Or another one:
If your note bean is an abstract class spring has no possibility to instanciate the bean because it does not know what to instanciate. You can for example add a requestparam parameter in the modelattr annotated method and decide what to do yourself.
This is very well described in the documentation. Either the reference or in the api of either controller, reqestmapping or modelattribute i believe.

Accessing Spring Controller Name from View

With Spring, how can i retrieve the following Controller attributes in the view?
Controller name
Controller's #RequestMapping URI
Action method name
Action method's #RequestMapping URI
One approach which i have tried is by creating a subclass of HandlerInterceptorAdapter and overriding postHandle. I register my subclass as an mvc:interceptor for a list of given paths - which is clunky to maintain but was the only way to avoid my interceptor being called for ResourceHandler requests (which i don't want). In my postHandle i can easily add the 2 name attributes, but not the URIs...
Parsing from the HttpRequest object requires constraints on all Controller RequestMappings. I.e. i must always map /Controller/Action or equiv scheme. Quite limiting.
Creating an ApplicationContext and querying that with the requestURI is too long-winded.
I am thinking about dropping the HandlerInterceptorAdapter and instead defining a BaseController for all my controllers to extend.
I wanted to ask before i do this, is there a better approach?
You haven't stated why you need to do this (it sometimes helps to include your motivation, as others can suggest alternative approaches).
But I'm guessing that the Spring 3.1 features loosely termed "end point documentation" may do what you are asking... See RequestMappingHandlerMapping in the Spring documentation which doesn't provide a lot of detail, so this example project is the best place to see it in action:
Spring MVC 3.1 Demo App
example controller
example JSP page

Best practice for using #SessionAttributes

I am trying to share data between two controllers in a Spring mvc application.
In Controller A I have annotated the class with #SessionAttributes({"mymodel1"}) and in the method which receives the first GET request I add it to the ModelMap:
model.addAttribute("mymodel1", MyModel1);
I now want to read myModel1 from Controller B.
In this Controller I have the following method which intercepts the POST requests and already has a different model in its parameters:
public String processSubmit(#ModelAttribute("mymodel2") MyModel2 mymodel2, BindingResult result, SessionStatus status, HttpServletRequest httpRequest)
Up to this point everything works fine and I am able to read mymodel2 from processSubmit however if I now want to add another #ModelAttribute("mymodel1") MyModel1 mymodel1 to this method signature I would have expected to be able to read the value I was setting in Controller A however I'm getting exceptions that the first model is no longer recognised.
So my question is: how can I read mymodel2 from Controller B?
You can't do that with #SessionAttributes :
Session attributes as indicated using this annotation correspond to a specific handlers model attributes, getting transparently stored in a conversational session. Those attributes will be removed once the handler indicates completion of its conversational session. Therefore, use this facility for such conversational attributes which are supposed to be stored in the session temporarily during the course of a specific handlers conversation.
For example I use this annotation when I want to validate elements with Hibernate validation, and after I submit the page and SOME elements are invalid I want the rest to be still on the page, but this is not your case. I think that the only way to do it would be with:
HttpSession.getAttribute()
The javadoc excerpt above is the most typical way #SessionAttributes is used. However, what Joly is describing should also work. Session attributes are stored via DefaultSessionAttributeStore, which by default does not prefix attribute names when it stores them in the session. That means if ControllerA and ControllerB both list an attribute called "mymodel1", they're actually referring to the same session attribute. You'll need to provide a little more information on the error you're getting and the actual controller code.

parameter validation with net.sf.oval (in play framework)

I would love to use the #NotNull annotation (or #Required or anything) for my own methods. While this works quite well in Controller and Model classes I cant get it to work in my own. This probably is more of a net.sf.oval question then play framework. But it might be connected, I don't know.
I have a class like:
#net.sf.oval.guard.Guarded
public class SimulatorWrapper {
public SimulatorWrapper setRedCode(#play.data.validation.Required #net.sf.oval.constraint.NotNull final String redCode) {
// just gessing here:
if(Validation.hasErrors()) throw new RuntimeException("invalid argument");
if(redCode == null) throw new RuntimeException("null");
// do stuff
return this;
}
}
When I call this method with a null parameter the if throws my exception, but #NotNull and #Required seem to do nothing at all. What am I doing wrong?
The play framework project came with oval 1.5, I downloaded 1.8 and added it to the classpath in eclipse just in case the old one had problems.
I'm starting the server with "play test my-server" and then I navigate to my website (not a test yet, just simple site) with my browser.
Thanks, Alex
P.S. I know the "null is evil" discussion, but I dont have access to the rest of the code so I cant change that.
The validation class is invoked to check the validation annotations by the Play framework only when a controller action is called.
Since you're not in a controller, the Validation on annotation won't be executed and the Required annotion won't be in Validation.hasErrors()
Instead of using annotation, you could use methods like:
Validation.required(redCode); //It'll check for null
And after that, call Validation.hasErrors() and it should work.
However, I don't think you should do this because the errors from Validation.hasError() should come from Validation on the controller action invocation and it can cause you side effects.
If you want to do something like your example, you should not rely on the play Validation class.
Are you sure you're using validation at the right places ?
In case anyone still needs this.
You can do validation with Play annotations in all classes exactly the same way as in controllers.
Just use validate plugin.

Resources