FrontControllerpublic class FrontController extends HttpServlet A simple implementation of a front controller servlet. This servlet
intercepts all requests to urls starting with "/pages." After processing
it strips "/pages" off the given URL and forwards to that. |
Fields Summary |
---|
public static final String | USERNAME_PARAM | public static final String | PASSWORD_PARAM | public static final String | USERBEAN_ATTR | public static final String | CONTROLLER_PREFIX |
Methods Summary |
---|
protected void | doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)Handle get requests by forwarding to a common processor
process(request, response);
| protected void | doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)Handle post requests by forwarding to a common processor
process(request, response);
| protected void | process(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)The common processor method. Check if this user is logged in or not.
If they are not, forward to the login page, otherwise forward to the
requested URL.
// the default next page
String nextPage = request.getPathInfo();
// find userbean from session
HttpSession session = request.getSession(true);
UserBean userBean = (UserBean) session.getAttribute(USERBEAN_ATTR);
if (userBean == null || !userBean.isLoggedIn()) {
// read request parameters
String username = request.getParameter(USERNAME_PARAM);
String password = request.getParameter(PASSWORD_PARAM);
// if the userbean doesn't exists, create it
if (userBean == null) {
userBean = UserBeanFactory.newInstance();
session.setAttribute(USERBEAN_ATTR, userBean);
}
// record the username and password values
userBean.setUsername(username);
userBean.setPassword(password);
// attempt to login
boolean result = userBean.doLogin();
// if we failed, redirect to the login page
if (!result) {
nextPage = "/login.jsp";
}
}
// transfer control to the desired view
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(nextPage);
dispatcher.forward(request, response);
|
|