There are some things to set. First things first.
Struts-config
In BookAction the application will show the form, while in BookActionDo it will update the book in the database.
<!-- Book -->
<action path="/book" type="com.github.jcpp.jathenaeum.actions.BookAction" parameter="op">
<forward name="edit" path="page.book.edit"/>
</action>
<!-- Book Operations -->
<action
path="/doBook"
type="com.github.jcpp.jathenaeum.actions.BookActionDo"
name="bookForm"
scope="request"
validate="false"
parameter="op">
<!-- Edit-->
<forward name="editErrors" path="/book.do?op=edit" redirect="true"/>
<forward name="editSuccess" path="page.book.edit.confirm" />
<forward name="editFailed" path="page.book.edit.failed" />
Here it tells to struts to not validate the form with validate="false"
.
Actions
public class BookActionDo extends DispatchAction {
public ActionForward edit(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String actionTarget = null;
HttpSession session = request.getSession();
Book book = new Book();
BookForm uf = (BookForm) form;
//Check the id
if(!uf.validateId(mapping, request).isEmpty()){
actionTarget = "invalidId";
ActionRedirect redirect = new ActionRedirect(mapping.findForward(actionTarget));
return redirect;
}
ActionErrors actionErrors = uf.validate(mapping, request);
int id = Integer.parseInt(request.getParameter("id"));
//If there are some errors, redirect to the form page
if(!actionErrors.isEmpty()){
actionTarget = "editErrors";
session.setAttribute("errors", actionErrors);
session.setAttribute("form", uf);
ActionRedirect redirect = new ActionRedirect(mapping.findForward(actionTarget));
redirect.addParameter("id", Integer.toString(id));
return redirect;
}
if(form != null){
book = new Book(uf);
book.setId(id);
try{
int bookId = (int) BookDAO.update(book);
}catch(Exception e){
actionTarget = "editFailed";
}
}
return mapping.findForward(actionTarget);
}
}
Here it checks if validate of the form returns some ActionErrors
. If yes it create an ActionRedirect
with the id
parameter, otherwise it tries to update the book.
So when it creates the url, ActionRedirect
will redirect to: /book.do?op=edit&id=<book_id>
.