I am crawling through a servlet site and in almost every doPost I encounter code like this :
@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);
}
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 super.doPost ? Also there are lines like session.setAttribute("photo", photo); in some of the servlets. Would it then be a good idea to have a session field in the BaseController – which if I understand things correctly should be volatile.
I am new to all this.
Thanks
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.