This seems so easy, but I don’t know why I’m having such difficulty with it…So in the getURL, I return the String “total”. I’m trying to return the SAME value “total” already has in the method handleRequest. Suggestions? Thanks in advance!
public class Multiply implements Controller {
static int product;
private static String total;
public static String getURL(HttpServletRequest req) {
String scheme = req.getScheme(); // http
String serverName = req.getServerName(); // hostname.com
int serverPort = req.getServerPort(); // 80
String contextPath = req.getContextPath(); // /mywebapp
String servletPath = req.getServletPath(); // /servlet/MyServlet
String pathInfo = req.getPathInfo(); // /a/b;c=123
String queryString = req.getQueryString(); // d=789
String[] item = queryString.split("&");
product = 1;
for (int i = 0; i < item.length; i++) {
String[] s = item[i].split("=");
String name = s[0];
String value = s[1];
int numValue = Integer.parseInt(value);
product = product * numValue;
}
total = "" + product;
return total;
}
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String Mess = total;
ModelAndView modelAndView = new ModelAndView("hello");
modelAndView.addObject("message", Mess);
return modelAndView;
}
}
You have a number of problems with your implementation of this. First, by declaring
totalstatic, all instances of this class will have the same value oftotal. If you’re using a framework that creates your controller and reuses it, this could lead to problems because all instances of the class will be referring to and updating the same member field.What you want is to have your
getURLmethod to return the value of total and then call it from yourhandleRequest.getURLcan be static because it relies on no non-static member fields. You should really renamegetURLtogetTotalorgetTotalFromURLbecause that is what you’re doing. What you’re askinggetURLto do is actually a side effect, and should be avoided as a practice.