0

I have two Spring MVC actions that in this example takes one parameter from a form when submitted:

public ModelAndView login(HttpServletResponse response, HttpServletRequest request,  
@RequestParam String requestedURL ) 

I would like to know if the attribute requestedURL can refer to a declared variable that actually hold the name of the incoming attribute input name="requestURL" ...

class Core {
     static String requestedURL = "requestedURL"; 
}

pseudo code:

public ModelAndView login(..., @RequestParam String @ReadFrom(Core.RequestedURL) ) 

Notice the @ReadFrom

This is to avoid redundancy. Right now it is called requestedURL but in the future someone might want to change the input parameter name, this shouldn't be a hardcoded string in the applicaton in my opinion.

and

<input name="<%= Core.requestedURL %>" value="<%= requestedURL %>" />

and is read in the method when submitted. But does the attribute name have to be hardcoded in the incoming parameter of the action method?

Thanks!

1 Answer 1

1

Yes, it has to be hardcoded as part of the @RequestParam annotation - either hardcoded or refer to a static final variable.

The alternative is to take in a Model/Map as an additional parameter in the method and getting the attribute from that:

public ModelAndView login(HttpServletResponse response, HttpServletRequest request,  
Model model ){
    String requestedURL = model.asMap().get(Core.requestedURL);
} 

Update You can refer to a static final variable this way: assuming:

public abstract class Core {
     public static final String requestedURL = "requestedURL"; 
}

public ModelAndView login(..., @RequestParam(Core.requestedURL) String requestedURL) 
Sign up to request clarification or add additional context in comments.

5 Comments

final works fine, actually mine is final. How would that look like if final ? otherwise your suggestion might be a nice workaround. Thanks!
I just looked into the RequestParam class. There is an attribute value="" ... what is this for? Says nothing about final..
I have added in an update - basically that is the attribute name to expect from the browser. The method parameter itself (requestedURL) gets changed after compilation(unless debug symbols are on), so the value attribute of @RequestParam is a way to show the name of the attribute
Ok! If the attribute is required=false, how would @RequestParam(..) look like? @RequestParam(value=Core.requestedURL, required=false) ??
Yes, that is correct, value() indicates the default that the annotation accepts, if only one parameter is provided that goes into the value attribute, if there are more than one, then you will have to specify the name like you have done.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.