Java - 将字符串转换为列表

发布于 2024-12-11 16:12:34 字数 2247 浏览 0 评论 0原文

这是将字符串转换为列表的正确方法吗?

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;
    }
}

接下来是 servlet 类,

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);
    }
}

最后是 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>

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

不羁少年 2024-12-18 16:12:34
List<String> list = Arrays.asList(yourString);

请记住,您将无法更改列表的内容。如果您需要这样做,请手动从此列表创建另一个列表。

List<String> list = Arrays.asList(yourString);

Just keep in mind that you won't be able to change the contents of the list. If you need to do that, create another list from this one manually.

小…楫夜泊 2024-12-18 16:12:34

通过您提供的附加 servlet/JSP 上下文,代码中真正的错误似乎是在 JSP 页面中使用了 request.getParameter:该方法确实返回了一个String,并且您无法转换 List 中的 String,不能使用强制转换,甚至不能使用语言或数据结构允许的任何其他操作。您可以使用已建议的方法之一将字符串插入到列表中(或者转换>ListString 使用其他方法),但从代码来看这不是您需要的。

在 servlet 代码中,您将 styles 属性 设置为包含啤酒品牌的 List。因此,要取回 List,您需要调用 request.getAttribute 而不是 getParametergetAttribute 方法返回一个 Object,它实际上是一个 List,并且您知道,因为您已将其设置为这样,所以在在这种情况下,强制转换正是获取原始类型值所需的操作。在代码中,这意味着

List styles = (List) request.getAttribute("styles");

在您的 JSP 中,代替给您带来麻烦的行。

With the additional servlet/JSP context you provided, it seems that the real mistake in your code is the use of request.getParameter in the JSP page: that method indeed returns a String, and you can't convert a String in a List, not with a cast, not even with any other operation allowed by the language or the data structures. You may insert a String into a List, using one of the methods already suggested (or transform a List into a String using other methods), but judging from the code that's not what you need.

In the servlet code, you set the styles attribute to the List containing the beer brands. So, to get that List back, you need to invoke request.getAttribute instead of getParameter. The getAttribute methods returns an Object, which really is a List, 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 means

List styles = (List) request.getAttribute("styles");

in your JSP, in place of the line that got you troubles.

空心↖ 2024-12-18 16:12:34

事实并非如此,您正在做的是尝试将 String 转换为 List,这是不一样的。 强制转换不会转换对象,它只是试图告诉对象是什么类型

你需要做的是:

List<String> list = new LinkedList<String>();
list.add(request.getParameter("styles"));

It's not, what you're doing is trying to cast a String to a List, which is not the same. A cast doesn't convert object, it merely tries to tell what type an object is.

What you need to do is:

List<String> list = new LinkedList<String>();
list.add(request.getParameter("styles"));
胡大本事 2024-12-18 16:12:34

如果您尝试检索更多“样式”,您可以使用:

request.getParameterValues("styles")

它将返回一个字符串数组,该数组可用于创建列表,如下所示:

List<String> styles = java.util.Arrays.asList(request.getParameterValues("styles"))

If you are trying to retrieve more "styles" you can use:

request.getParameterValues("styles")

that will return an array of String, that could be used to create a List as follows:

List<String> styles = java.util.Arrays.asList(request.getParameterValues("styles"))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文