【问题标题】:How to retrieve cookies in servlet (display everything)如何在 servlet 中检索 cookie(显示所有内容)
【发布时间】:2025-12-25 04:30:07
【问题描述】:
String userNmae = req.getParameter("userName");
Cookie ck = new Cookie("hello", vall);
res.addCookie(ck);

//假设,我在 cookie 中存储了 5 个不同的用户名或整数。

Cookie [] cookies = req.getCookies();
            String name;
        for(Cookie cookie : cookies) {
                 name = cookie.getValue();
                req.setAttribute("vav", name);
                req.getRequestDispatcher("index.jsp").forward(req, res);
              }

//现在我想检索所有值并显示在jsp页面上。我该怎么做..

${vav}

jsp文件.. 先谢谢大家了。。

【问题讨论】:

  • 你在用弹簧吗?您应该在返回 jsp 之前将 var 添加到您的模型中。类似 model.put("vav", req.getAttribute("vav")) 或 jsp
  • 我正在尝试发送用户输入列表;数字历史..当我按照上面的当前方式进行操作时,我只能在 jsp 上打印出一个数字...只是卡在打印 cookie 中的所有内容..
  • 您的数据似乎很敏感,应该存储在会话中而不是 cookie 中。 Cookie 用于保存用户偏好,例如“记住密码”,并且很容易被“黑客攻击”。使用会话而不是 cookie 是否有一些限制?
  • 不...我可以做任何一种方式; cookie 或 HttpSession。我尝试先用 HttpSession 解决这个问题。我遇到了同样的问题......我只是很难打印所有东西......
  • 您能否发布更多代码:控制器方法、jsp、项目依赖项?使用会话非常简单。

标签: java jsp session servlets


【解决方案1】:

演示会话使用的简单示例:

@Controller
public class UserController {

    private static final String USER_HISTORY = UserController.class.getName() + "_USER_HISTORY";

    @GetMapping("/")
    public String home() {
        return "index";
    }

    @ModelAttribute
    public User getUserModelAttribute() {
        return new User();
    }

    @GetMapping("/history")
    public String getHistoryView(HttpSession httpSession, Map<String, Object> model) {
        model.put("userHistory", getUserHistory(httpSession));
        return "index";
    }

    private List<User> getUserHistory(HttpSession httpSession) {
        // check if session exists
        Object history = httpSession.getAttribute(USER_HISTORY);
        if (history != null && history instanceof List) {
            return (List<User>) history;
        }
        return new ArrayList<>();
    }

    @PostMapping("/user")
    public String saveUser(HttpSession httpSession, @ModelAttribute User user) {
        List<User> history = getUserHistory(httpSession);
        history.add(user);
        httpSession.setAttribute(USER_HISTORY, history);
        return "redirect:/";
    }
}

还有jsp文件:

<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

<html>
<head></head>
<body>
    <form:form method="POST" action="/user" modelAttribute="user">
         <table>
            <tr>
                <td><form:label path="firstName">First Name</form:label></td>
                <td><form:input path="firstName"/></td>
            </tr>
            <tr>
                <td><form:label path="lastName">Last Name</form:label></td>
                <td><form:input path="lastName"/></td>
            </tr>
            <tr>
                <td><input type="submit" value="Submit"/></td>
            </tr>
        </table>
    </form:form>

    <a href="/history">See Your History</a>

    <c:if test="${not empty userHistory}">
        <c:forEach var="user" items="${userHistory}">
            ${user.firstName} ${user.lastName}
        </c:forEach>
    </c:if>
</body>
</html>

【讨论】:

  • 你太棒了..谢谢..这真的很有帮助...谢谢谢谢..谢谢..非常...现在我可以解决我的问题...谢谢你又来了……阿迪娜……
  • 不客气,如果您需要更多信息,请告诉我。
  • 会的。谢谢。
【解决方案2】:

如果您使用的是 spring,我想您有一个控制器类用于要在其上显示信息的视图。只需将存储的信息添加到给定的模型中,然后您就可以使用表达式语言对其进行检索。

类似这样的:

@RequestMapping(value = "/login")
public String login(ModelMap model, HttpServletRequest request){
   // retrieve all data from cookies and save it somewhere in a List/Map
   model.addAttribute(cookieData);
   return "login";
}

然后在 JSP 中使用 JSTL 和 EL 在地图上循环并显示您需要的内容:

<c:forEach items="${cookieData}" var="cookie">
  <p>${cookieData.userName}</p>
</c:forEach>

希望这能给你一些见解。

编辑:确保在尝试 foreach 循环之前在 JSP 页面中导入 JSTL。

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

我也同意,敏感数据不应存储在 cookie 中,因为它们很容易访问。

【讨论】: