文章目录
- 一、提交信息
- 前端
- 后端
- 二、上传文件
- 通过 form 表单进行文件上传
- 前端
- 后端
提示:以下是本篇文章正文内容,Java系列学习将会持续更新
一、提交信息
如何将用户键入在网页中的信息提交给服务器?
前端
form 表单发送 POST 请求(提交信息)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>提交信息</title>
</head>
<body>
<form method="post" action="/submit">
用户名: <input type="text" name="username">
密码: <input type="password" name="password">
<button>提交</button>
</form>
</body>
</html>
后端
@WebServlet("/submit")
public class SubmitServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println("用户名: " + username);
System.out.println("密码: " + password);
// 后面就可以封装对象,将数据插入到数据库中了
}
}
回到目录…
二、上传文件
文件上传的方式有两种:
- 通过 form 表单的方式 (需要掌握)
- 通过 js + ajax 的方式 (比较复杂)
通过 form 表单进行文件上传
前端
enctype
属性规定在发送到服务器之前应该如何对表单数据进行编码。
值 | 描述 |
application/x-www-form-urlencoded | 在发送前编码所有字符(默认) |
multipart/form-data | 不对字符编码。在使用包含文件上传控件的表单时,必须使用该值。 |
text/plain | 空格转换为 “+” 加号,但不对特殊字符编码。 |
form 表单发送 POST 请求(上传文件)
- form的enctype 属性必须是multipart/ form-data
- method 必须是POST
- form的input 的type 是file
- 引起HTTP请求体的格式以multipart 的形式传输
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="file">
<button>上传</button>
</form>
</body>
</html>
后端
- 支持POST请求的动态资源
继承HttpServlet
+@WebServlet("...")
+重写doPost
方法 - Servlet 规定,读取
multipart
类型的form
数据时,必须使用@MultipartConfig
修饰类 - 使用
req.getPart("...");
获取请求的文件
@MultipartConfig // 这里是死规定,否则会有 500 错误
@WebServlet("/upload.do")
public class UploadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
Part file = req.getPart("file");
System.out.println(file.getName()); // form表单中对文件的命名
System.out.println(file.getContentType()); // 文件内容的类型
System.out.println(file.getSubmittedFileName()); // 提交时的文件名
// 打印文件内容
InputStream is = file.getInputStream();
byte[] buf = new byte[1024];
int n = is.read(buf);
String s = new String(buf, 0, n, "UTF-8");
System.out.println(s);
// 获取文件的保存路径: webapp的路径 + 子目录
String realPath = req.getServletContext().getRealPath("/files");
System.out.println(realPath);
// 保存路径 + 文件名
String fileName = realPath + "\\" + file.getSubmittedFileName();
// 保存文件
file.write(fileName);
}
}
回到目录…
总结:
提示:这里对文章进行总结:
以上就是今天的学习内容,本文是JavaWeb的学习,学习了后端如何获取前端传来的信息,以及如何从前端上传文件到浏览器。之后的学习内容将持续更新!!!