How to Create Webservice in Java Which Has Upload Functionality
Document Data
Preface
Function I Introduction
1. Overview
2. Using the Tutorial Examples
Part II The Web Tier
3. Getting Started with Web Applications
four. JavaServer Faces Technology
5. Introduction to Facelets
6. Expression Linguistic communication
7. Using JavaServer Faces Technology in Spider web Pages
8. Using Converters, Listeners, and Validators
ix. Developing with JavaServer Faces Technology
ten. JavaServer Faces Technology: Advanced Concepts
eleven. Using Ajax with JavaServer Faces Technology
12. Composite Components: Advanced Topics and Example
13. Creating Custom UI Components and Other Custom Objects
14. Configuring JavaServer Faces Applications
15. Java Servlet Technology
16. Uploading Files with Coffee Servlet Technology
The @MultipartConfig Annotation
The getParts and getPart Methods
17. Internationalizing and Localizing Web Applications
Part 3 Web Services
18. Introduction to Web Services
19. Edifice Web Services with JAX-WS
twenty. Edifice RESTful Web Services with JAX-RS
21. JAX-RS: Advanced Topics and Example
Function Four Enterprise Beans
22. Enterprise Beans
23. Getting Started with Enterprise Beans
24. Running the Enterprise Bean Examples
25. A Bulletin-Driven Bean Instance
26. Using the Embedded Enterprise Bean Container
27. Using Asynchronous Method Invocation in Session Beans
Office V Contexts and Dependency Injection for the Java EE Platform
28. Introduction to Contexts and Dependency Injection for the Java EE Platform
29. Running the Basic Contexts and Dependency Injection Examples
30. Contexts and Dependency Injection for the Java EE Platform: Advanced Topics
31. Running the Advanced Contexts and Dependency Injection Examples
Role Half dozen Persistence
32. Introduction to the Java Persistence API
33. Running the Persistence Examples
34. The Java Persistence Query Language
35. Using the Criteria API to Create Queries
36. Creating and Using String-Based Criteria Queries
37. Controlling Concurrent Access to Entity Data with Locking
38. Using a Second-Level Cache with Coffee Persistence API Applications
Function Vii Security
39. Introduction to Security in the Java EE Platform
40. Getting Started Securing Web Applications
41. Getting Started Securing Enterprise Applications
42. Java EE Security: Advanced Topics
Function Viii Java EE Supporting Technologies
43. Introduction to Coffee EE Supporting Technologies
44. Transactions
45. Resources and Resource Adapters
46. The Resource Adapter Example
47. Java Bulletin Service Concepts
48. Java Bulletin Service Examples
49. Bean Validation: Advanced Topics
50. Using Java EE Interceptors
Role IX Case Studies
51. Duke's Bookstore Case Written report Example
52. Knuckles's Tutoring Case Study Example
53. Duke'south Forest Case Study Example
Index
The fileupload Example Awarding
The fileupload example illustrates how to implement and use the file upload feature.
The Duke's Forest example study provides a more complex example that uploads an image file and stores its content in a database.
Architecture of the fileupload Example Application
The fileupload instance application consists of a single servlet and an HTML course that makes a file upload request to the servlet.
This example includes a very simple HTML form with two fields, File and Destination. The input type, file, enables a user to scan the local file arrangement to select the file. When the file is selected, it is sent to the server as a office of a POST request. During this process two mandatory restrictions are applied to the class with input blazon file:
-
The enctype attribute must be set to a value of multipart/grade-data.
-
Its method must be Postal service.
When the form is specified in this manner, the entire request is sent to the server in encoded class. The servlet then handles the request to process the incoming file information and to extract a file from the stream. The destination is the path to the location where the file volition exist saved on your calculator. Pressing the Upload push button at the bottom of the form posts the data to the servlet, which saves the file in the specified destination.
The HTML class in tut-install /examples/web/fileupload/web/index.html is as follows:
<!DOCTYPE html> <html lang="en"> <caput> <title>File Upload</championship> <meta http-equiv="Content-Blazon" content="text/html; charset=UTF-8"> </head> <trunk> <form method="Mail" activity="upload" enctype="multipart/form-data" > File: <input type="file" name="file" id="file" /> <br/> Destination: <input type="text" value="/tmp" name="destination"/> </br> <input type="submit" value="Upload" proper noun="upload" id="upload" /> </class> </body> </html>
A POST request method is used when the customer needs to send data to the server every bit part of the request, such as when uploading a file or submitting a completed form. In contrast, a Go asking method sends a URL and headers only to the server, whereas Post requests also include a message body. This allows arbitrary-length data of whatsoever type to exist sent to the server. A header field in the POST request usually indicates the bulletin body'south Net media blazon.
When submitting a form, the browser streams the content in, combining all parts, with each part representing a field of a form. Parts are named afterwards the input elements and are separated from each other with cord delimiters named purlieus.
This is what submitted information from the fileupload course looks similar, after selecting sample.txt equally the file that will be uploaded to the tmp directory on the local file system:
Post /fileupload/upload HTTP/1.i Host: localhost:8080 Content-Type: multipart/course-data; boundary=---------------------------263081694432439 Content-Length: 441 -----------------------------263081694432439 Content-Disposition: form-data; proper name="file"; filename="sample.txt" Content-Type: text/plain Data from sample file -----------------------------263081694432439 Content-Disposition: class-data; proper name="destination" /tmp -----------------------------263081694432439 Content-Disposition: class-data; name="upload" Upload -----------------------------263081694432439--
The servlet FileUploadServlet.java can be found in the tut-install /examples/web/fileupload/src/java/fileupload/ directory. The servlet begins equally follows:
@WebServlet(name = "FileUploadServlet", urlPatterns = {"/upload"}) @MultipartConfig public class FileUploadServlet extends HttpServlet { individual terminal static Logger LOGGER = Logger.getLogger(FileUploadServlet.class.getCanonicalName());
The @WebServlet annotation uses the urlPatterns belongings to define servlet mappings.
The @MultipartConfig notation indicates that the servlet expects requests to made using the multipart/form-data MIME type.
The processRequest method retrieves the destination and file role from the request, and then calls the getFileName method to retrieve the file name from the file part. The method then creates a FileOutputStream and copies the file to the specified destination. The error-handling section of the method catches and handles some of the about common reasons why a file would not exist establish. The processRequest and getFileName methods await like this:
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); // Create path components to save the file concluding String path = request.getParameter("destination"); last Part filePart = request.getPart("file"); final String fileName = getFileName(filePart); OutputStream out = aught; InputStream filecontent = null; final PrintWriter writer = response.getWriter(); try { out = new FileOutputStream(new File(path + File.separator + fileName)); filecontent = filePart.getInputStream(); int read = 0; final byte[] bytes = new byte[1024]; while ((read = filecontent.read(bytes)) != -1) { out.write(bytes, 0, read); } writer.println("New file " + fileName + " created at " + path); LOGGER.log(Level.INFO, "File{0}existence uploaded to {1}", new Object[]{fileName, path}); } catch (FileNotFoundException fne) { writer.println("You either did not specify a file to upload or are " + "trying to upload a file to a protected or nonexistent " + "location."); writer.println("<br/> Error: " + fne.getMessage()); LOGGER.log(Level.Astringent, "Problems during file upload. Error: {0}", new Object[]{fne.getMessage()}); } finally { if (out != cypher) { out.close(); } if (filecontent != zilch) { filecontent.close(); } if (writer != null) { writer.close(); } } } private String getFileName(final Part part) { final String partHeader = office.getHeader("content-disposition"); LOGGER.log(Level.INFO, "Part Header = {0}", partHeader); for (String content : part.getHeader("content-disposition").split(";")) { if (content.trim().startsWith("filename")) { return content.substring( content.indexOf('=') + 1).trim().supplant("\"", ""); } } return null; }
Running the fileupload Instance
Yous can utilize either NetBeans IDE or Ant to build, package, deploy, and run the fileupload case.
To Build, Packet, and Deploy the fileupload Example Using NetBeans IDE
- From the File menu, choose Open Project.
- In the Open Projection dialog, navigate to:
tut-install /examples/web/
- Select the fileupload folder.
- Select the Open as Main Project checkbox.
- Click Open Project.
- In the Projects tab, right-click fileupload and select Deploy.
To Build, Package, and Deploy the fileupload Instance Using Ant
- In a terminal window, go to:
tut-install /examples/spider web/fileupload/
- Type the post-obit control:
ant
- Type the following command:
ant deploy
To Run the fileupload Example
- In a web browser, type the post-obit URL:
http://localhost:8080/fileupload/
The File Upload page opens.
- Click Scan to display a file browser window.
- Select a file to upload and click Open.
The name of the file you selected is displayed in the File field. If yous do not select a file, an exception will exist thrown.
- In the Destination field, type a directory name.
The directory must take already been created and must too be writable. If you exercise not enter a directory name, or if you enter the proper noun of a nonexistent or protected directory, an exception will be thrown.
- Click Upload to upload the file you selected to the directory y'all specified in the Destination field.
A bulletin reports that the file was created in the directory you specified.
- Go to the directory yous specified in the Destination field and verify that the uploaded file is nowadays.
Copyright © 2013, Oracle and/or its affiliates. All rights reserved. Legal Notices
Source: https://docs.oracle.com/javaee/6/tutorial/doc/glraq.html
0 Response to "How to Create Webservice in Java Which Has Upload Functionality"
Post a Comment