2

我正在浏览一个 servlet 站点,几乎在每个 doPost 中我都会遇到这样的代码:

@Override
protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    // set encoding to UTF-8
    if (request.getCharacterEncoding() == null)
        request.setCharacterEncoding("UTF-8");
    // TODO : this may be needed in doGet too ?????????
    response.setCharacterEncoding("UTF-8");

    // check if session exists
    boolean sessionExists = request.isRequestedSessionIdValid();
    HttpSession session = request.getSession();

    if (!sessionExists)
        session.setMaxInactiveInterval(1000);

    // if session does not exist we create it
    ServletContext context = session.getServletContext();
    Integer numSessions = (Integer) context
            .getAttribute("numberOfSessions");
    if (numSessions == null)
        context.setAttribute("numberOfSessions", 1);
    else if (!sessionExists)
        context.setAttribute("numberOfSessions", ++numSessions);
}

创建一个 BaseController 类并将此代码移到那里是否是个好主意 - 我应该将它移到 init() 方法还是 doPost() 中 - 然后调用super.doPostsession.setAttribute("photo", photo);在某些 servlet 中也有类似的行。那么session在 BaseController 中有一个字段是否是一个好主意 - 如果我理解正确的话,它应该是易变的。

我对这一切都很陌生。

谢谢

4

2 回答 2

3

You should use the Template Pattern.

Example:

public abstract class BaseController extends HttpServlet {

public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    if (request.getCharacterEncoding() == null) {
        request.setCharacterEncoding("UTF-8");
    }
    response.setCharacterEncoding("UTF-8"); [...]

    doService(request, response);
}

protected abstract void doService(HttpServletRequest request, HttpServletResponse response) throws Exception, Error;

}

And then you have to extend the BaseContoller class, and implement just the doService (or whatever) method.

于 2012-07-18T17:23:17.267 回答
2

You can move setting the request character encoding to a helper method and call it from doPost. Also check if your code behaved correctly in case that the encoding is set to something else than utf-8.

On the other hand, the session stuff is a bit weird. If you want to keep track of the number of sessions, remove all that and use javax.servlet.http.HttpSessionListener. It is more elegant and you will have your code in a single place.

If you need to keep track of variables that belong to a session, keep using the HttpSession class, do not save them in a field in the controller.

于 2012-07-18T17:22:49.787 回答