java获取前端请求字段的方法
package test.request;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.Enumeration;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sun.org.apache.commons.beanutils.BeanUtils;
//HttpServletRequest获取请求头和请求数据
//请求数据一半来说要先检查再使用,检查非空和不是空格
public class RequestDemo2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("---------获取请求数据方式1-------------");
// 获取指定的请求数据
String value = request.getParameter("username");
if (value != null && !value.trim().equals("")) {
System.out.println(value);
}
System.out.println("---------获取请求数据方式2-------------");
// 获取所有的请求数据
Enumeration e = request.getParameterNames();
while (e.hasMoreElements()) {
String paramName = (String) e.nextElement();
String value2 = request.getParameter(paramName);
System.out.println(paramName + "=" + value2);
}
System.out.println("---------获取请求数据方式3-------------");
// 获取所有的请求数据,同名的只能获取一次,就是第一次
String[] values = request.getParameterValues("username");
for (int i = 0; values != null && i < values.length; i++) {
System.out.println(values[i]);
}
System.out.println("---------获取请求数据方式4-------------");
// 这个特别实用,框架的模型驱动,这个Map的value肯定是String数组类型,因为有同名的请求数据
// 实际开发中是不会 request.getParameter("username");用这种方式的,都是要创建一个model的
Map<String, String[]> map = request.getParameterMap();
User user = new User();
try {
// 用map中的数据填充bean
BeanUtils.populate(user, map);
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (InvocationTargetException e1) {
e1.printStackTrace();
}
System.out.println(user.getPassword());
System.out.println("---------获取请求数据方式5-------------");
// request.getInputStream();是上传文件的时候获取数据的方式
// 普通数据是获取不到的
InputStream in = request.getInputStream();
int len = 0;
byte[] buffer = new byte[1024];
while ((len = in.read(buffer)) > 0) {
System.out.println(new String(buffer, 0, len));
}
}
// 获取请求头
private void test1(HttpServletRequest request) {
System.out.println("---------获取请求头方式1-------------");
// 拿到指定的请求头
System.out.println(request.getHeader("cache-control"));
System.out.println("---------获取请求头方式2-------------");
// 拿到所有指定的请求头
Enumeration e = request.getHeaders("cache-control");
while (e.hasMoreElements()) {
String headValue = (String) e.nextElement();
System.out.println(headValue);
}
System.out.println("---------获取请求头方式3-------------");
// 拿到所有请求头
Enumeration e1 = request.getHeaderNames();
while (e1.hasMoreElements()) {
String headerName = (String) e1.nextElement();
String headValue = request.getHeader(headerName);
System.out.println(headerName + "=" + headValue);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}