I have an <s:form>
that is present on all pages of my web application.
<s:form action="search" method="post">
<s:textfield name="query" placeholder="Enter movie title..." cssClass="searchbox" />
<s:submit type="image" src="images/btn_search.gif" />
</s:form>
Currently, it is redirecting to index.jsp
when the validate()
method of SearchAction
class results to input
.
<action name="search" class="com.mypackage.action.SearchAction">
<result>/search-result.jsp</result>
<result name="input">/index.jsp</result>
</action>
SearchAction:
public class SearchAction extends ActionSupport implements RequestAware, Message {
private static final long serialVersionUID = 1L;
private Map<String, Object> request;
private String query;
@Override
public String execute() throws Exception {
// business logic
request.put("searchResults", searchResults);
return SUCCESS;
}
@Override
public void validate() {
if(getQuery().length() == 0) {
addFieldError("query", BLANK_SEARCH);
}
}
@Override
public void setRequest(Map<String, Object> request) {
this.request = request;
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
}
Output:
It works, but it seems unnatural for the user to return to index.jsp
every time the parameter is invalid (i.e. blank).
My goal is to keep the user on the current page when the Please enter... message appears.
Questions:
- How do I get the current page, where the action was called?
(For example, a visitor used the search while at the Log In page, how do I getlogin.jsp
from the address bar?) - How do I make this current page the location at
<result name="input">/currentpage</result>
?
You can get the current page name using following code:
In Struts.xml, use a dynamic result such as:
In the action, use getter method for url. By default set the value of url as "index.jsp". If you want to change it, set appropriate value for url. Like login.jsp etc.