I'm trying to write a simple program to have the background on a html page changed by selecting the colour on radio buttons, this I managed to do successfully. As soon as I add a cookie to remember the colour and load the same background the next time I get null pointer exceptions all over the place.
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ColourSelect extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{ String pageColour = "Black"; String colour = req.getParameter("colour"); Cookie colourCookie = new Cookie("colour", colour); if (colourCookie != null) { res.addCookie(colourCookie); colourCookie.setMaxAge(100000); Cookie[] cookies = req.getCookies(); pageColour = getLastColour(cookies); } else { pageColour = colour; } res.setContentType("text/html"); ServletOutputStream out = res.getOutputStream(); out.println("<html>"); out.println("<body bgcolor=\"" + pageColour + "\">"); out.println("<font color=\"White\">"); out.println("<head><title>Change Colour</title></head>"); out.println("<h1><p>Background Colour</p></h1>"); out.println("<p>What colour do you want the background?</p>"); out.println("<form>"); out.println("Yellow</br><input type=\"radio\" name=\"colour\" value=\"Yellow\" /></br>"); out.println("Green</br><input type=\"radio\" name=\"colour\" value=\"Green\" /></br>"); out.println("Blue</br><input type=\"radio\" name=\"colour\" value=\"Blue\" /></br>"); out.println("Black</br><input type=\"radio\" name=\"colour\" value=\"Black\" /></br>"); out.println("<input type=submit value=\"Change Background\"/>"); out.println("</font>"); out.println("</form>"); out.println("</body>"); out.println("</html>"); } public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { doPost(req, res); } String getLastColour(Cookie[] cookies){ String inColour="white"; for (int i = 0; i < cookies.length; i++) { String cookieName = cookies[i].getName(); if (cookieName.equals("colour")) inColour = cookies[i].getValue(); } return inColour; } }
Can anyone help, I'm really stuck with this, no matter what I try it just doesn't seem to work.