Java Web Devel - MVC RequestDispatcher - Passing Arrays?

Dopers,

I’m brushing up on some Java web development and read about implementing an app with MVC using the Request Dispatcher. I coded together a quick example, passing strings and handing them off to a JSP page to display. I’m stumped, though, with how to pass arrays.

In my Servlet:


public class Action extends HttpServlet {
	
	static final long serialVersionUID = 1;	
  
	public void doGet(HttpServletRequest req,
                    HttpServletResponse res)
    	throws ServletException, IOException
    	{

		 String months[] = 
	       {"Jan", "Feb", "Mar", "Apr", "May", "Jun", 
	        "July", "Aug", "Sep", "Oct", "Nov", "Dec"};
		
	    req.setAttribute("months", months);
	
	    ServletContext app = getServletContext();
	
	    RequestDispatcher disp;
	    disp = app.getRequestDispatcher("/view/resize.jsp");
	
	    disp.forward(req, res);
    	}
}

My jsp:


<html>
<head>
<title>Test Page</title>
</head>
<%String[] months = session.getAttribute("months");%>
<body bgcolor='white'>
<%for(int i = 0; i < months.length; i++ ){%>
	<%=months*%>
<%}%>
</body>
</html>

This returns this error:


org.apache.jasper.JasperException: Unable to compile class for JSP

An error occurred at line: 4 in the jsp file: /view/resize.jsp
Generated servlet error:
/opt/tomcat5/work/Catalina/localhost/flowWeb/org/apache/jsp/view/resize_jsp.java:45: incompatible types
found   : java.lang.Object
required: java.lang.String[]
String[] months = session.getAttribute("months");

I’m using Gentoo Linux with Sun’s JDK 5 and Tomcat5.

Thanks,

LarsenMTL

This is really just a guess, but have you tried this?


req.setAttribute("months", {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sep", "Oct", "Nov", "Dec"});

Strike that. My better guess is that req is set up to store attributes of any type, and so it just stores them as objects. So when you get an attribute, it just comes back as an object and you have to do something to get that into an object of the right type. You’re either going to have to cast the object you get back into a String, or write a more type-specific get/set pair.

First I had an error in my jsp, session.getAttribute(“months”); should be request.getAttribute(“months”);.

Regardless,

was dead on. Casting like so →


<%String months[] = (String[])request.getAttribute("months");%>

worked. Thanks ultrafilter.