Is this the right way to convert a string to a list?
List styles = (List)request.getParameter("styles");
Model (BeerExpert.java)
package com.example.model;
import java.util.*;
public class BeerExpert {
public List getBrands(String color){
List brands = new ArrayList();
if(color.equals("amber")){
brands.add("Jack Amber");
brands.add("Red Moose");
}
else{
brands.add("Jail Pale Ale");
brands.add("Gout Scott");
}
return brands;
}
}
The next is the servlet class
BeerSelect.java
package com.example.web;
import com.example.model.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class BeerSelect extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException,ServletException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Beer Selection Advice <br>");
String c = request.getParameter("color");
BeerExpert be = new BeerExpert();
List result = be.getBrands(c);
request.setAttribute("styles", result);
RequestDispatcher view = request.getRequestDispatcher("results.jsp");
view.forward(request, response);
}
}
Finally the jsp.
results.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@page import="java.util.*" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1 align="center">Beer Recommendations in JSP!!!</h1>
<%
List styles = (List)request.getParameter("styles");
Iterator it = styles.iterator();
while(it.hasNext()){
out.print("<br> try " + it.hasNext());
}
%>
</body>
</html>
Thanks
With the additional servlet/JSP context you provided, it seems that the real mistake in your code is the use of
request.getParameterin the JSP page: that method indeed returns aString, and you can’t convert aStringin aList, not with a cast, not even with any other operation allowed by the language or the data structures. You may insert aStringinto aList, using one of the methods already suggested (or transform aListinto aStringusing other methods), but judging from the code that’s not what you need.In the servlet code, you set the
stylesattribute to theListcontaining the beer brands. So, to get thatListback, you need to invokerequest.getAttributeinstead ofgetParameter. ThegetAttributemethods returns anObject, which really is aList, and you know that because you have set it to be as such, so in this case a cast is exactly the operation that is needed to get back the value with its original type. In code, this meansin your JSP, in place of the line that got you troubles.