- 该方式提交表单数据以什么形式传递给服务器?抓包分析
- 1 这种方式发送到服务器的数据,需要一些其他方法处理才能还原原貌。先通过基本套路拿到处理的对象upload
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 拿到一个文件长传类的工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
factory.setSizeThreshold( 1024*1024*5);
// Configure a repository (to ensure a secure temp location is used)
//文件上传的时候的临时文件夹
ServletContext servletContext = this.getServletConfig().getServletContext();
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
//把临时文件夹给到Factory使用
factory.setRepository(repository);
// Create a new file upload handler 使用工厂获取一个文件上传处理器
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(1024*1024*10);
}
- 2得到数据列表,分别解析,得到表单基本数据和文件,因为浏览器发过来的时候会给与区分基本表单和文件
// Parse the request 解析请求
try {
List<FileItem> items = upload.parseRequest(request);
for (FileItem fileItem : items) {
if (fileItem.isFormField()) { //simple form field.
processFormField(fileItem); // 基本的表单数据 文件除外
} else {
processUploadedFile(fileItem);// 该item是一个文件数据
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
- 3处理基本表单数据方法为
private void processFormField(FileItem item) {
String fieldName = item.getFieldName();
byte[] bs = item.get();
String value = new String(bs);
switch (fieldName) {
case "username":
user.setUsername(value);
break;
case "password":
user.setPassword(value);
break;
case "gender":
user.setGender(value);
break;
case "age":
user.setAge(value);
break;
case "email":
user.setEmail(value);
break;
default:
break;
}
}
- 4
private void processUploadedFile(FileItem item) {
//把该文件保存起来
String fieldName = item.getFieldName(); //表达名
String fileName = item.getName(); //文件名
InputStream uploadedStream=null;
try {
uploadedStream = item.getInputStream();
String filename =new Random().nextInt(1000)+fileName ;
//文件夹的realPath
String realPath = getServletContext().getRealPath("pic");
File file = new File(realPath);
if (!file.exists()) {
file.mkdir();
}
String fileString = realPath+"/"+filename;
File picFile = new File(fileString);
user.setPic("pic/"+filename);//为了存储到xml中
FileOutputStream fos = new FileOutputStream(picFile);
byte [] bs=new byte[1024];
int length=0;
while( (length=uploadedStream.read(bs))!=-1){
fos.write(bs, 0, length);
}
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if (uploadedStream!=null) {
try {
uploadedStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
- 4表单没有这个属性提交的就比较常规
这种方式就可以使用一些工具比如BeanUtils对表单数据进行封装