我遇到了HttpServlet
请求问题。我有一个用于检索请求标头的应用程序。如果应用程序发现重复的标头名称,它应该抛出一个错误。然而,经过一番谷歌搜索,我发现它HttpServletRequest
忽略了重复的标题名称,并继续获取它遇到的第一个标题名称。我能做些什么来捕捉那些重复的请求标头吗?
我使用 Tomcat 6 作为应用程序容器。
这是代码:
int headerChecker=0;
for(Enumeration<String>names = request.getHeaderNames(); names.hasMoreElements(); ) {
String name = (String)names.nextElement();
if(name.equalsIgnoreCase("abcd")){
headerChecker++; // add 1 to headerChecker if abcd header is encountered
}
for(Enumeration<String>values = request.getHeaders(name); values.hasMoreElements(); ) {
String value=(String)values.nextElement();
System.out.println("name: "+name+"\tvalue: "+value);
}
}
if(headerChecker! = 1){
logger.error("abcd is duplicated, returning HTTP 404");
} else {
//...proceed with application
}
}
这是日志:
name: host value: localhost:8080 name: user-agent value: CocoaRestClient/8 CFNetwork/520.4.3 Darwin/11.4.2 (x86_64) (MacBookPro9%2C2) name: content-length value: 23 name: accept value: **name: abcd value: 1234556** name: accept-language value: en-us name: accept-encoding value: gzip, deflate name: content-type value: application/x-www-form-urlencoded name: connection value: keep-alive
这是测试截图:
编辑:这是servlet
public class HeaderServlet extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse res)
{
doGet(req, res);
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
{
int xmsisdnChecker = 0;
String value = "";
for(Enumeration<String> names = req.getHeaderNames();names.hasMoreElements();){
String name = (String) names.nextElement();
Enumeration<String> values = req.getHeaders(name);
if(values != null)
{
while(values.hasMoreElements()) {
if(name.equalsIgnoreCase("abcd"))
{
xmsisdnChecker++;
System.out.println("ee: " + xmsisdnChecker) ;
}
value = (String) values.nextElement();
System.out.println("header name: " + name + "\theader value: " + value);
}
}
}
}
}