微信

使用微信服务,更方便

职友集>Java面试题 > 在Servlet中获得请求参数代码示例

在Servlet中获得请求参数代码示例

2015-09-15 06:30:01 阅读( 146 )

2463人 收藏本页

标签:Java面试题

《在Servlet中获得请求参数代码示例》

Servlet文件实现如下

package cn.outofmemory.snippets.enterprise;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GetAllRequestParametersInServlet extends HttpServlet {

private static final long serialVersionUID = -2128122335811219481L;

public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
handleRequest(req, res);
}

public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
handleRequest(req, res);
}

public void handleRequest(HttpServletRequest req, HttpServletResponse res) throws IOException {

PrintWriter out = res.getWriter();
res.setContentType("text/plain");

Enumeration<String> parameterNames = req.getParameterNames();

while (parameterNames.hasMoreElements()) {

String paramName = parameterNames.nextElement();
out.write(paramName);
out.write("\n");

String[] paramValues = req.getParameterValues(paramName);
for (int i = 0; i < paramValues.length; i++) {
String paramValue = paramValues[i];
out.write("\t" + paramValue);
out.write("\n");
}

}

out.close();

}

}

【web.xml】

<?xml version="1.0" encoding="UTF-8"?>

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

<display-name>JCG Snippets Web Project</display-name>

<servlet>
<servlet-name>JCG Snippets Application</servlet-name>
<servlet-class>com.javacodegeeks.snippets.enterprise.GetAllRequestParametersInServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>JCG Snippets Application</servlet-name>
<url-pattern>/jcgservlet</url-pattern>
</servlet-mapping>

</web-app>

【输出:】

param2
paramvalue2a
paramvalue2b
param1
paramvalue1

下一篇:Java Socket Server-client端多线程处理代码示例

上一篇:Java使用appache deamon实现linux守护进程

亲~ 如果您有更好的答案 可在评论区发表您独到的见解。

您想查看更多的信息: 面试题