为什么request.getParameter("userid")可以获得值getAttribute不能
时间: 2024-06-01 12:08:19 浏览: 8
`request.getParameter("userid")` 是用于获取 HTTP 请求中的参数值的方法,而 `getAttribute()` 是用于获取 Servlet 请求范围内的属性值的方法。如果你想要从 HTTP 请求中获取参数值,应该使用 `request.getParameter("userid")` 方法;如果你想要从 Servlet 请求范围内获取属性值,应该使用 `request.getAttribute("userid")` 方法。请确保在使用这些方法之前,你已经正确地设置了参数值或属性值。如果你仍然无法获取值,请检查你的代码是否正确,并确保你的应用程序已经正确地处理了请求。
相关问题
jsp中(String)request.getAttribute("userid")获取为空
如果 `(String)request.getAttribute("userid")` 获取为空,有以下几种可能的原因:
1. 该属性在请求中并不存在。可能是在前一个页面中没有设置,或者在请求中被重置了。
2. 该属性在请求中存在,但是它的值为空。可以通过在设置属性时检查值是否为空来避免此情况。
3. 该属性在请求中存在,但是在获取属性值时使用了错误的属性名。请确保使用正确的属性名。
你可以在设置属性时使用 `request.setAttribute("userid", "xxxxx")` 来设置属性值。如果你已经确定该属性存在于请求中,可以尝试使用 `request.getParameter("userid")` 来获取属性值。此外,还可以在 JSP 页面中使用 EL 表达式 `${userid}` 来获取属性值。
// 添加产品到购物车 @RequestMapping("addcart.action") public String addcart() { this.front(); if (this.getSession().getAttribute("userid") == null) { return "redirect:/index/preLogin.action"; } String userid = (String) this.getSession().getAttribute("userid"); Cart cart = new Cart(); cart.setAddtime(VeDate.getStringDateShort()); cart.setGoodsid(getRequest().getParameter("goodsid")); cart.setNum(getRequest().getParameter("num")); cart.setPrice(getRequest().getParameter("price")); cart.setUsersid(userid); this.cartService.insertCart(cart); return "redirect:/index/cart.action"; }该段核心代码是哪些
该段核心代码是:
```java
String userid = (String) this.getSession().getAttribute("userid");
Cart cart = new Cart();
cart.setAddtime(VeDate.getStringDateShort());
cart.setGoodsid(getRequest().getParameter("goodsid"));
cart.setNum(getRequest().getParameter("num"));
cart.setPrice(getRequest().getParameter("price"));
cart.setUsersid(userid);
this.cartService.insertCart(cart);
return "redirect:/index/cart.action";
```
它的作用是将商品添加到购物车中。其中,通过session获取当前用户的id,创建一个Cart对象,并设置商品id、数量、单价、用户id等属性,最后调用cartService的insertCart方法将cart对象插入到数据库中,最终重定向到购物车页面。
相关推荐
![sql](https://img-home.csdnimg.cn/images/20210720083646.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)