Skip to content

Instantly share code, notes, and snippets.

@rubydubee
Created April 19, 2012 23:00
Show Gist options
  • Save rubydubee/2424756 to your computer and use it in GitHub Desktop.
Save rubydubee/2424756 to your computer and use it in GitHub Desktop.
Tiny MVC for J2EE
Howdy, ${user.name}!
public class AccountAction implements Action
{
@Override
public void process(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//do your processing here, take values from DB, may be!
SomeBean user = new SomeBean("Paddy")
//Very important. we are setting attribute to the request and forwarding that request.
// forward will keep the request intact unlike redirect!
request.setAttribute("user", user);
ServletContext context = request.getSession().getServletContext();
context.getRequestDispatcher("/WEB-INF/users/account.jsp").forward(request, response);
}
}
public interface Action
{
public void process(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException;
}
package com.myapp;
public class FrontController extends HttpServlet{
private Map<String, Action> actions = new HashMap<String, Action>();
public void init()
{
this.actions.put("/account.do", new AccountAction());
}
public void takeAction(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String reqUri = request.getRequestURI();
Action action = (Action)actions.get(reqUri);
action.process(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
takeAction(request, response);
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
takeAction(request, response);
}
}
<servlet>
<servlet-name>FrontController</servlet-name>
<servlet-class>com.myapp.FrontController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FrontController</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment