sample.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Sample</title>
</head>
<body>
<form id="form">
Username : <input type="text" id="username" name="username"><br>
Password : <input type="password" id="password" name="password"><br>
Image : <input type="file" id="image" name="image" accept="image/*"><br>
<input type="submit" value="send">
</form>
</body>
<script type="text/javascript" src="sample.js"></script>
</html>
sample.js
//Creating a form object
var form = document.getElementById("form");
//What to do when the submit event occurs
form.addEventListener("submit", function(event) {
//Delete the default function of form and manage it with JavaScript
event.preventDefault();
check();
});
function check() {
//Fetch the value of form
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var image = document.getElementById("image").value;
//Send if entered
if (username != "" && password != "" && image != "") {
sendData();
} else {
alert("Please input all item.");
}
}
function sendData() {
//Creating a FormData object
var formData = new FormData(form);
//Send HTTP request with XMLHttpRequest
var req = new XMLHttpRequest();
//Processing when transmission / reception is completed
req.addEventListener("load", function(event) {
if (req.responseText == "done") {
//Processing when processing is successful
alert("Succeeded.");
} else {
alert("Failed to send.");
}
});
//Processing when transmission / reception fails
req.addEventListener("error", function(event) {
alert("Error");
});
//HTTP request settings
req.open("POST", "/sample/SampleServlet"); // /application name/Servlet name
//Send request
req.send(formData);
}
SampleServlet.java
package controller;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
@WebServlet("/SampleServlet")
public class SampleServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public SampleServlet() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
//Response text
String responseText = "done";
//Create ServletFileUpload from DiskFileItemFactory
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload sfu = new ServletFileUpload(factory);
try {
//Store request form data in a list
List list = sfu.parseRequest(request);
for (Object o : list) {
//Treat each form data as FileItem
FileItem item = (FileItem) o;
//Branch depending on whether FileItem is a field or a file
if (item.isFormField()) {
//For fields, get the field name and value
// (In the form<input name="Field name" value="concents inputted")
String fieldName = item.getFieldName();
String value = item.getString();
if (fieldName.equals("username")) {
//Username processing
System.out.println("username : " + value);
} else if (fieldName.equals("password")){
//Password processing
System.out.println("password : " + value);
}
} else {
File file = new File(item.getName());
try {
String dirPath = "Image file save destination";
String filePath = dirPath + File.separator + file.getName();
//Save image file
item.write(new File(filePath));
} catch (IOException e) {
e.printStackTrace();
responseText = "error";
} catch (Exception e) {
e.printStackTrace();
responseText = "error";
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
responseText = "error";
}
//Send response
response.getWriter().print(responseText);
}
}
If not entered
When all items are entered
JavaScript
Servlet
Recommended Posts