JavaWeb getParameter和getAttribute的区别

  1. HttpServletRequest类有setAttribute()方法,而没有setParameter()方法

  2. getParameter()用于用于客户端重定向时,即当两个Web组件之间为链接关系时,被链接的组件通过getParameter()方法来获得请求参数

  3. getAttribute()用于服务器端重定向时,即两个Web组件之间为转发关系时,转发目标组件通过getAttribute()方法来和转发源组件共享request,session范围内的数据。

从更深的层次考虑,

request.getParameter()方法传递的数据,会从Web客户端传到Web服务器端,代表HTTP请求数据。request.getParameter()方法返回String类型的数据。

request.setAttribute()和getAttribute()方法传递的数据只会存在于Web**容器内部,在具有转发关系的Web组件之间共享。这两个方法能够设置**Object类型的共享数据。

request.getParameter()取得是通过容器的实现来取得通过类似post,get等方式传入的数据。会从Web客户端传到Web服务器端,代表HTTP请求数据,返回字符串

request.setAttribute()和getAttribute()只是在web容器内部流转,仅仅是请求处理阶段,在具有转发关系的Web组件之间共享。这两个方法能够设置Object类型的共享数据。

总的来说:

request.getAttribute()方法返回reques,sessiont范围内存在的对象

而request.getParameter()方法是获取http提交过来的数据。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
购物车通常是一个用来存储已选商品的列表,我们可以使用Java中的session来存储购物车信息。在购物车中,商品通常是以一个对象的形式被添加到购物车中,并且每个商品通常有一个唯一的ID来标识它。 以下是一个使用getAttribute方法来实现购物车的示例: 首先,在JSP页面中,我们将商品添加到购物车中,我们可以使用一个表单来获取用户输入的商品ID和数量,然后将其存储到session中: ```html <form method="post" action="addToCart.jsp"> <input type="hidden" name="productId" value="1"> Quantity: <input type="text" name="quantity" value="1"> <input type="submit" value="Add to Cart"> </form> ``` 在addToCart.jsp页面中,我们将获取到的商品ID和数量存储到一个CartItem对象中,并将CartItem对象存储到session中的购物车列表中。如果购物车列表不存在,则创建一个新的列表: ```java // Get the product ID and quantity from the request int productId = Integer.parseInt(request.getParameter("productId")); int quantity = Integer.parseInt(request.getParameter("quantity")); // Create a new cart item with the product ID and quantity CartItem item = new CartItem(productId, quantity); // Get the cart from the session, or create a new one if it doesn't exist List<CartItem> cart = (List<CartItem>) request.getSession().getAttribute("cart"); if (cart == null) { cart = new ArrayList<CartItem>(); request.getSession().setAttribute("cart", cart); } // Add the item to the cart cart.add(item); ``` 在购物车中,我们可以使用getAttribute方法来获取购物车列表,然后遍历列表并显示每个CartItem对象的详细信息: ```java // Get the cart from the session List<CartItem> cart = (List<CartItem>) request.getSession().getAttribute("cart"); // Display the cart items for (CartItem item : cart) { out.println("Product ID: " + item.getProductId() + "<br>"); out.println("Quantity: " + item.getQuantity() + "<br><br>"); } ``` 总的来说,使用getAttribute方法来实现购物车功能可以很方便地存储和获取购物车信息,而不需要使用数据库或其他存储方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值