I would like invoking methods based on URL mappings using Servlet/JSP.
A Servlet is mapped to a pattern like /xxx/*. I have created an interface with only one method as follows.
public interface Action
{
public void execute(HttpServletRequest request, HttpServletResponse response) throws IllegalAccessException, InvocationTargetException, SQLException, ServletException, IOException;
}
A java.util.Map initialized with different implementations of this interface to perform different actions based on a URL in the Servlet we are talking about in its init() method as follows.
@WebServlet(name = "Country", urlPatterns = {"/Country/*"})
public final class Country extends HttpServlet
{
private Map<String, Action>map;
@Override
public void init(ServletConfig config) throws ServletException
{
super.init(config);
map=new HashMap<String, Action>();
map.put("Create", new CreateAction());
map.put("Read", new ReadAction());
map.put("Delete", new DeleteAction());
map.put("Edit", new EditAction());
}
}
The execute() method is invoked precisely from either the doGet() or doPost() method just like as follows.
map.get(request.getPathInfo().substring(1)).execute(request, response);
For instance, a URL like, http://localhost:8080/Assignment/Country/Create would invoke the execute() method in the CreateAction class.
Similarly, a URL like, http://localhost:8080/Assignment/Country/Delete would invoke the execute() method in the DeleteAction class and so on.
While using links, we can easily form a URL of our choice like,
<c:url var="editURL" value="/Country/Edit">
<c:param name="countryId" value="${row.countryId}"/>
<c:param name="currentPage" value="${currentPage}"/>
<c:param name="countryName" value="${row.countryName}"/>
<c:param name="countryCode" value="${row.countryCode}"/>
</c:url>
<a href="${editURL}" class="action2"/>
This produces a URL like http://localhost:8080/Assignment/Country/Edit which will call the execute() method in the EditAction class.
How to do the same while using a submit button? Can we have an appropriate URL, when a given submit button is pressed which causes the execute() method in the CreateAction class?
When pressing this submit button, the URL should be
http://localhost:8080/Assignment/Country/Create
The default URL to render an initial page view is like,
http://localhost:8080/Assignment/Country
Can we construct such URLs while making a POST request something similar to those provided by request/action based MVC frameworks (The Struts framework provides an action attribute for a submit button)?