一、建立连接
要实现Servlet传递表单数据的效果,我们需要一个表单数据输入端的页面和一个表单数据接收端的Java文件。
首先需要创建一个Web工程,再将下载好的servlet-api.jar导入工程,位置如下:
工程名–>WebContent–>WebINF–>lib
接下来我们在WebContent文件夹内创建JSP页面文件,比如“login.jsp”,同时创建表单
然后在Java Resources目录下的src目录中创建相应接收端"LoginServlet.java"
创建完之后如何把两个文件联系起来呢?
需要首先在login.jsp中创建好的表单标签中添加action元素指向java文件,格式如下:
action="./LoginServlet"
这样就指定好了用户输入的表单数据将要传递给谁。
二、传递单/多条表单数据
若要传输单条表单数据,需要重写doGet()方法,并且调用getParameter()方法,实例如下:
①页面输入端
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="./LoginServlet">
<input placeholder="Pleace write your name" name="user_name"/>
</form>
</body>
</html>
②数据接收端
package com.jd.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userName = request.getParameter("user_name");
System.out.println(userName);
}
}
若要传递多条数据,则需要调用getParameterValues()方法,实例如下:
①页面输入端
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="./LoginServlet">
<input type="checkbox" name="hobby" value="1" />sing
<input type="checkbox" name="hobby" value="2" />dance
<input type="checkbox" name="hobby" value="3" />Rap
<input type="checkbox" name="hobby" value="4" />basketball
</form>
</body>
</html>
②数据接收端
package com.jd.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String [] hobbies = request.getParameterValues("hobby");
for (String hobby : hobbies) {//在控制台打印出用户选择对应的Value值
System.out.println(hobby);
}
}
}
三、传递文件
在上面的操作中,我们传递的表单数据一般仅仅有一个字符或几个字符,而如果要传递文件该怎么办?一般来说,要实现传递文件的功能,我们需要用到一个额外的jar包commons-fileupload-1.2.1.jar和commons-io-2.4.jar,同样导入到lib目录中。
而要实现传输各类型文件的功能,我们还需要重写doPost()方法,重写部分代码如下(直接复制过去即可):
if(ServletFileUpload.isMultipartContent(request)){//1、判断当前form表单的编码方式是不是为enctype="multipart/form-data"
FileItemFactory fileItemFactory = new DiskFileItemFactory();
ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
servletFileUpload.setFileSizeMax(1024*1024*6*10);
List<FileItem> fileItemList = null;
try {
fileItemList = servletFileUpload.parseRequest(request);//2、将form表单中每个携带数据的标签转换成每个FileItem对象并存到集合中
} catch (FileUploadException e) {
e.printStackTrace();
request.setAttribute("message", "文件太大,上传失败");
request.getRequestDispatcher("result.jsp").forward(request, response);
return;
}
for(FileItem fileItem : fileItemList){//3、获取form表单所携带的数据
if(fileItem.isFormField()){//为true表示为非文件类型的标签
String key = fileItem.getFieldName();//summary
String value = fileItem.getString();//summary对相的数据
System.out.println(key+":"+value);
}else{//文件类型
try {
String oldFileName = fileItem.getName();
StringfileNameSuffix=oldFileName.substring(oldFileName.lastIndexOf("."));
System.out.println(fileNameSuffix);
String fileNamePrefix = UUID.randomUUID().toString();
// fileItem.write(new File("D:\\"+fileNamePrefix+fileNameSuffix));//未发布路径
String path = "D://"+fileNamePrefix+fileNameSuffix;
fileItem.write(new File(path+fileNamePrefix+fileNameSuffix));//发布路径
System.out.println(path);
} catch (Exception e) {
e.printStackTrace();
}
}
}
request.setAttribute("message", "文件上传成功");
request.getRequestDispatcher("result.jsp").forward(request, response);
}else{
request.setAttribute("message", "当前form表单enctype属性的属性值非multipart/form-data");
request.getRequestDispatcher("result.jsp").forward(request, response);
}
}