为什么jsp页面中使用session.setAttribute();会报错

本文探讨了在JSP页面中使用session.setAttribute方法时遇到的常见错误,主要原因是未正确导入servlet-api资源包。文章深入解析了servlet-api的作用,以及如何在项目中正确配置和引用。

为什么在jsp页面中使用session.setAttribute("user",user);会报错,因为servlet-api资源包没有导入

``` package main.java.com.example; import javax.servlet.*; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; import java.io.IOException; import java.util.HashMap; import java.util.Map; @WebServlet("/exampleServlet") public class ExampleServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Map<String, String> requestMap = new HashMap<>(); requestMap.put("key1", "value1"); requestMap.put("key2", "value2"); request.setAttribute("requestMap", requestMap); Map<String, String> sessionMap = new HashMap<>(); sessionMap.put("key3", "value3"); sessionMap.put("key4", "value4"); request.getSession().setAttribute("sessionMap", sessionMap); Map<String, String> contextMap = new HashMap<>(); contextMap.put("key5", "value5"); contextMap.put("key6", "value6"); getServletContext().setAttribute("contextMap", contextMap); RequestDispatcher dispatcher = request.getRequestDispatcher("/example.jsp"); dispatcher.forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } <%@ page import="java.util.Map" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>EL Expression Example</title> </head> <body> <h2>Request Scope Map</h2> <ul> <c:forEach var="entry" items="${requestScope.requestMap}"> <li>${entry.key} : ${entry.value}</li> </c:forEach> </ul> <h2>Session Scope Map</h2> <ul> <c:forEach var="entry" items="${sessionScope.sessionMap}"> <li>${entry.key} : ${entry.value}</li> </c:forEach> </ul> <h2>ServletContext Scope Map</h2> <ul> <c:forEach var="entry" items="${applicationScope.contextMap}"> <li>${entry.key} : ${entry.value}</li> </c:forEach> </ul> </body> </html>```java代码为1-33行,jsp页面代码为34-64行,我通过IDEA运行tomcat9,使用java-web框架运行后,遍历map集合一直无法实现效果,请问代码有什么问题吗
03-21
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值