与MVC和前端控制器的友好链接

时间:2015-04-27 19:40:01

标签: jsp java-ee url-rewriting front-controller

我有一个jee项目,我使用MVC和前端控制器设计模式。

我实际上拥有这样的所有链接:

<a href="Controller?page=ForwardProducts">Products</a>

或者从javascript进行ajax调用:

Controller?page=AJAX&type=CheckID&_id=something

还有一些代码,无论何时按下链接,它们都会转到一个servlet,它将信息转发给正确的.class并接收信息(PD:交换机更大,只是缩小了):

        switch (request.getParameter("page")) {
            case "AJAX":
                String ajaxClass = request.getParameter("type");
                IAJAX _ajax = (IAJAX) Class.forName("my.package.Ajax." + ajaxClass).newInstance();
                String _json = _ajax.getJSON(request, response);
                try (PrintWriter out = response.getWriter()) {
                    out.print(_json);
                }   
                break;
            default:
                ICommand _command = (ICommand) Class.forName("my.package.classes." + request.getParameter("page")).newInstance();
                _command.initPage(request, response);
                _includePage = _command.execute(request, response);
                request.getSession().setAttribute("_includePage", _includePage);
                request.getRequestDispatcher("/index.jsp").forward(request, response);
                break;
        }

ForwardAbout内部类包看起来像这样:

public class ForwardAbout extends ICommand{
@Override
public void initPage(HttpServletRequest request, HttpServletResponse response) throws Exception {

}

@Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    return "/about.jsp";
}
}

和ICommand:

public abstract class ICommand {

public void initPage(HttpServletRequest request, HttpServletResponse response) throws Exception {

}

public abstract String execute(HttpServletRequest request, HttpServletResponse response) throws Exception;

}

我想制作漂亮的链接,例如:

http://localhost:8084/testWeb/Controller?page=ForwardAbout

http://localhost:8084/testWeb/about-us

但是反过来,当用户写http://localhost:8084/testWeb/about-us时,他们应该被重定向&#34;内部&#34;到http://localhost:8084/testWeb/Controller?page=ForwardAbout

我已经尝试了http://www.tuckey.org/urlrewrite/,这样当用户编写网址时,他们应该转发到正确的内容,但似乎没有用,在类中有很多例外。

有没有办法实现这个直通代码,而不涉及apache mods?

PD:由于&#34;教学目的&#34;老师说,我们不允许使用任何框架......

0 个答案:

没有答案