Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

java - How do I map different values for a parameter in the same @RequestMapping in Spring MVC?

Suppose I have:

@RequestMapping(params = "action=nuovoprodotto")    
    public ModelAndView nuovoProdotto(
            @RequestParam(value = "page", required = false, defaultValue = "-1") int page,
            @RequestParam(value = "action") String action,
            @ModelAttribute Prodotto prod, HttpSession session)
            throws Exception {

is it possible to map this request to like two or three values of "action" parameter?

I tried many ways like

@RequestMapping(params = "action=nuovoprodotto, action=salvaprodotto")  

or

@RequestMapping(params = "action=nuovoprodotto|salvaprodotto")  

but they don't work... If I can't what are the solutions, besided writing an handler for every single parameter value combination?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this:

@RequestMapping(params = {"action=nuovoprodotto","action=salvaprodotto"})

The params attribute is actually of type String[], but annotations let you write a String in place of a single-element String[], so these two are equivalent:

@RequestMapping(params = {"action=nuovoprodotto"})

and

@RequestMapping(params = "action=nuovoprodotto")

Reference:


Update: my bad, as you can read in the section Advanced @RequestMapping options, multiple params are combined using and, not or, so it can't work as specified above.

So I'd say what you have to do is create an alias method with almost the same signature:

@RequestMapping(params = "action=nuovoprodotto")    
public ModelAndView nuovoProdotto(
        @RequestParam(value = "page", required = false, defaultValue = "-1") int page,
        @RequestParam(value = "action") String action,
        @ModelAttribute Prodotto prod, HttpSession session)
        throws Exception {
        // some stuff here
}

@RequestMapping(params = "action=salvaprodotto")    
public ModelAndView salvaProdotto(
        @RequestParam(value = "page", required = false, defaultValue = "-1") int page,
        @RequestParam(value = "action") String action,
        @ModelAttribute Prodotto prod, HttpSession session)
        throws Exception {

        return nuovoProdotto(page, action, prod, session);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...