Create a dynamic URL with 2 action parameters in Struts 2 using OGNL

If I have url: www.myurl.com/books and you want to create a new <s:url> filter for author and year: www.myurl.com/books/Sartre/1942 , passing Sartre and 1942 as parameters of the action class which will display on the book page with the corresponding results. How to do it in Struts2?

I have built-in logic, so it would be great if:

  • I could reuse the same jsp and action class that permalink www.myurl.com/books uses.
  • Show the dynamically displayed URL www.myurl.com/books/Sartre/1942 in the address bar even after the request request loaded the page (not www.myurl.com/books , that is).
+1
source share
1 answer

You need Advanced Wildcard Mappings .

From the documentation: Struts2 Advanced wildcard mappings :

Extended Wildcards

From 2.1.9 +, regular expressions defined in the action name can be defined. To use this wild card form, the following constants must be set:

 <constant name="struts.enable.SlashesInActionNames" value="true"/> <constant name="struts.mapper.alwaysSelectFullNamespace" value="false"/> <constant name="struts.patternMatcher" value="regex" /> 

Regular expressions can be in two forms, the simplest is {FIELD_NAME} , in which case the field with FIELD_NAME in action will be filled with the agreed text, for example:

 <package name="books" extends="struts-default" namespace="/"> <action name="/{type}/content/{title}" class="example.BookAction"> <result>/books/content.jsp</result> </action> </package> 

In this example, if the URL /fiction/content/Frankenstein is equal to the requested BookAction " type " field will be set to " fiction " and the " title " field will be set to " Frankenstein ".

If you are using Struts2-Convention-Plugin, your example:

 @Action(value="/books/{author}/{year}") public class Books extends ActionSupport { private String author; private Integer year; /* ...GETTERS AND SETTERS HERE... */ public String execute(){ /* ...LOAD DATA HERE... */ if (noDataFound) return NONE; return SUCCESS } } 

If you need to work with these parameters in the prepare() method, read this question .

+4
source

All Articles