减少冗余代码

时间:2011-12-27 19:49:17

标签: java java-ee-6

我开始感到多余,我必须指定doGet参数以及每次抛出的内容。有没有办法在Controller中完成所有这些操作,所以不必在每个页面上完成?我的Controller目前没有doGet()

@WebServlet(name = "EditServlet", urlPatterns = {"/content/edit"})
public class EditServlet extends cms.library.Controller {
    @Override
    public void doGet (HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.loadView(new cms.library.PageConfig()
                .setRequest(request)
                .setResponse(response)
                .setTemplate("/content/edit"));
    }

    @Override
    public void doPost (HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        System.out.println("posted");

        this.doGet(request, response);
    }
}

1 个答案:

答案 0 :(得分:0)

您可以将模板传递给cms.library.Controller类,这样您就不必每次都定义doGet。

public class Controller {
    private final String template;
    public Controller( String template ) {
        this.template = template;
    }
    @Override
    public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.loadView(new cms.library.PageConfig()
                .setRequest(request)
                .setResponse(response)
                .setTemplate(template));
    }
}

@WebServlet(name = "EditServlet", urlPatterns = {"/content/edit"})
public class EditServlet extends cms.library.Controller {
    public EditServlet() {
        super("/content/edit");
    }
    @Override
    public void doPost (HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("posted");
        this.doGet(request, response);
    }
}

或者您可以创建自己的注释,Controller类将在其构造函数中检查实现类以获取注释(而不是传入字符串)。