电商网站按类别筛选产品时触发java.lang.NumberFormatException: null问题
解决java.lang.NumberFormatException: null 问题(类别筛选产品时)
这个错误的核心原因很明确:你在尝试将一个null值转换为整数——当get("categoryId")获取不到有效参数时,parameterOne会是null,直接调用Integer.valueOf(parameterOne)就会触发这个异常。我们一步步来修复:
问题代码定位
先看你的getbycat()方法,这里是报错的重灾区:
public Collection<ProductTbl>getbycat() { Map<String,String> params =FacesContext.getCurrentInstance(). getExternalContext().getRequestParameterMap(); String parameterOne = params.get("categoryId"); int foo = Integer.valueOf(parameterOne); // 这里parameterOne可能为null,直接抛出异常 dispbycat(foo); return ad.getbycategoryid(foo); }
还有两个隐藏问题:
- 如果用户直接访问
products.xhtml而不传入categoryId参数,同样会触发错误 - 在
getbycat()这个数据获取的getter方法里调用dispbycat(foo)(跳转方法)完全不合适,这会把数据获取和页面跳转逻辑混在一起,导致页面行为混乱
修复后的代码
1. 给请求参数添加严格校验
修改getbycat()方法,先检查参数有效性再做转换:
public Collection<ProductTbl> getbycat() { Map<String,String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap(); String parameterOne = params.get("categoryId"); // 先校验参数是否为空或null if (parameterOne == null || parameterOne.trim().isEmpty()) { // 参数无效时,返回空集合或者重定向到首页(根据你的业务需求选) return Collections.emptyList(); // 要是想跳转的话可以用这段: // FacesContext.getCurrentInstance().getExternalContext().redirect("/client/index.xhtml"); // return null; } int foo; try { foo = Integer.valueOf(parameterOne); } catch (NumberFormatException e) { // 处理参数不是有效整数的情况,比如返回空集合 return Collections.emptyList(); } // 注意:这里不需要调用dispbycat(foo),它是用来生成跳转URL的,不是在getter里触发的 return ad.getbycategoryid(foo); }
2. 优化跳转方法的调用逻辑
dispbycat(int cid)是生成跳转URL的方法,应该在页面的点击事件里调用,比如在JSF页面中:
<h:commandLink value="查看该类别产品" action="#{productBean.dispbycat(1)}" />
这样跳转后,products.xhtml会拿到合法的categoryId参数,getbycat()就能正常工作了。
3. 同步修复getproductbyid()方法
为了避免产品详情页出现同样的问题,给它也加上参数校验:
public Collection<ProductTbl> getproductbyid() { Map<String,String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap(); String parameterOne = params.get("product_id"); if (parameterOne == null || parameterOne.trim().isEmpty()) { return Collections.emptyList(); } int foo; try { foo = Integer.parseInt(parameterOne); } catch (NumberFormatException e) { return Collections.emptyList(); } return ad.getAllProductByProductid(foo); }
额外提示
- 永远不要信任前端传过来的参数,用户可能手动修改URL传入无效值,必须做校验
- 在JSF里尽量让getter只负责数据获取,跳转、业务逻辑放在专门的action方法里,避免逻辑耦合
内容的提问来源于stack exchange,提问作者K...
相关产品推荐
相关产品推荐

