如何参数化getParameterNames以避免MyEclipse告警

背景

在MyEclipse2014环境下,使用JDK7.0时,在调用request.getParameterNames()给出了如下告警:

public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
	...
	Enumeration<String> e =  request.getHeaderNames();
	...
}

Warning: 
Type safety: the expression of type Enumeration needs unchecked conversion to conform to Enumeration<String>

问题原因排查

如果你去查询getHeaderNames()的帮助手册,可能会让你更加困惑,因为赋值操作两侧数据类型相同,确报出了上述错误信息。

Enumeration<String> getHeaderNames()

Returns an enumeration of all the header names this request contains. If the request has no headers, this method returns an empty enumeration.

Some servlet containers do not allow servlets to access headers using this method, in which case this method returns null

Returns:
    an enumeration of all the header names sent with this request; if the request has no headers, an empty enumeration; if the servlet container does not allow servlets to use this method, null

此问题的原因在于从Servlet API 3.0(Java EE 6)开始,将此函数返回值进行了参数化处理。在一些老的版本像Servlet API 2.5(Java EE 5)及之前版本并没有将此函数参数。Servlet API 2.5中此函数的说明如下:

Enumeration getParameterNames()

    Returns an Enumeration of String objects containing the names of the parameters contained in this request. If the request has no parameters, the method returns an empty Enumeration.

    Returns:
        an Enumeration of String objects, each String containing the name of a request parameter; or an empty Enumeration if the request has no parameters


很显然,你可能使用的是老的容器,可以查看web.xml进行确认。

<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
......
</web-app>

解决方案

1. 将容器servlet版本升级到3.0,这样就可以使用下面的语句,而MyEclipse不会告警

Enumeration<String> params = request.getParameterNames();
2. 使用unchecked转换

@SuppressWarnings("unchecked")
Enumeration<String> params = (Enumeration<String>) request.getParameterNames();


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值