Spring 5.0 Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

To create a multi-action controller in the Spring 5.0 platform, follow these steps:

  1. Let us start this recipe with a multi-action controller named MultiActionController with all its handler methods mapped to their respective URLs, similar to a hub of independent services:
@Controller 
public class MultiActionController { 
 
  @RequestMapping(value={"/send/*", "/list/*"}, 
    method=RequestMethod.GET) 
  public String defaultMethod(){ 
    return "default_msg"; 
  } 
  
  @RequestMapping(value="/send/message_get.html", 
    method=RequestMethod.GET) 
  public String sendGetMessage(Model model){ 
    String message = "Multi-action GET URL Mapping"; 
    model.addAttribute("message", message);    
    return "get_msg"; 
  } 
  
  @RequestMapping(value="/send/message_post.html", 
    method=RequestMethod.POST) 
  public String sendPostMessage(Model model){ 
    String message = "Multi-action Post URL Mapping"; 
    model.addAttribute("message", message); 
      return "post_msg";  
  } 
  
  @RequestMapping(value="/list/multilist.html", 
    method=RequestMethod.GET) 
  public String viewTransactions(){ 
      return "multi_list";  
  } 
} 
  1. The preceding three handler methods are typical request transactions mapped to their respective URL and HTTP methods. The handler defaultMethod() is quite unique because its action will be triggered whenever a request URL that starts with a context path /send or /list has been executed but happens to be non-existent. This method serves as the callback feature of the multi-action controller whenever the URL invoked does not exist.
  2. Next, create the simple views default_msg, get_msg and post_msg, all having their own set of message bundle labels and JSTL tags for rendering.
  3. Moreover, create a multi_list page that will serve as a facade for GET and POST transactions:
<%@ taglib prefix="spring" 
uri="http://www.springframework.org/tags" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; 
 charset=ISO-8859-1"> 
<title><spring:message code="multi_facade" /></title> 
</head> 
<body> 
     <a href="/ch03/send/message_get.html">GET Transaction</a> 
     <br/> 
     <form action="/ch03/send/message_post.html" method="post" > 
       <input type="submit" value="POST Transaction" /> 
     </form> 
</body> 
</html> 
  1. Update both views.properties and messages_en_US.properties for the changes in the view configuration and resource bundle messages, respectively.
  2. Then clean, build, and deploy the project. Call each request handler independently.