title: java - servlets - set encoding and session in base class?
body: <p>I am crawling through a servlet site and in almost every doPost I encounter code like this :</p>
  
  <pre><code>@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);
  }
  </code></pre>
  
  <p>Would it be a good idea to create a BaseController class and move this code there - and should I move it in the init() method or in the doPost() - and then call <code>super.doPost</code> ? Also there are lines like <code>session.setAttribute("photo", photo);</code> in some of the servlets. Would it then be a good idea to have a <code>session</code> field in the BaseController - which if I understand things correctly should be volatile.</p>
  
  <p>I am new to all this.</p>
  
  <p>Thanks</p>