Java Spring Mvc Post Example
- Details
- Written by
- Last Updated on 21 June 2019 | Print Email
In the tutorial Sending e-mail with Spring MVC, we describe how to develop a basic Java web application for sending e-mail based on Spring MVC and JavaMail. However, the e-mail sending form in that application is pretty simple with only text fields (e-mail to, subject and message). Sometimes we have a need of adding some files as attachment to the e-mail also. So this tutorial is going to extend that by adding a file field on which user can pick up a file to be attached to the outgoing e-mail. The new e-mail sending form looks like this:
Before sending the e-mail, we have to handle the file upload (see the tutorial Upload files with Spring MVC). Let's go to see how such application is implemented.
Table of contents:
-
- Required jar files
- Writing e-mail sending form (with attach file)
- Configuring Spring MVC for file upload and e-mail
- Implementing Spring MVC controller
- Writing result and error pages
- Configuring web deployment descriptor file
- Download Eclipse project/WAR file
1. Required jar files
The following table lists the jar files needed for this application (click on a hyperlink to download the corresponding software):
Required jar files | |
JavaMail | mail.jar |
Spring framework | spring-beans-3.2.0.RELEASE.jar spring-context-3.2.0.RELEASE.jar spring-context-support-3.2.0.RELEASE.jar spring-core-3.2.0.RELEASE.jar spring-expression-3.2.0.RELEASE.jar spring-web-3.2.0.RELEASE.jar spring-webmvc-3.2.0.RELEASE.jar |
Apache Commons Logging | commons-logging-1.1.1.jar |
Apache Commons File Upload | commons-fileupload-1.2.2.jar |
Apache Commons IO | commons-io-2.3.jar |
The application would consist of the following files:
-
- EmailForm.jsp
- spring-mvc.xml
- SendEmailAttachController.java
- Result.jsp
- Error.jsp
- web.xml
Let's look at detail of each one.
2. Writing e-mail sending form (with attach file)
Code of the e-mail form (EmailForm.jsp) is as follows:
<%@ 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=UTF-8"> <title>Spring MVC - Email</title> </head> <body> <center> <h1>Spring MVC - Send e-mail with attachments</h1> <form method="post" action="sendEmail.do" enctype="multipart/form-data"> <table border="0" width="80%"> <tr> <td>Email To:</td> <td><input type="text" name="mailTo" size="65" /></td> </tr> <tr> <td>Subject:</td> <td><input type="text" name="subject" size="65" /></td> </tr> <tr> <td>Message:</td> <td><textarea cols="50" rows="10" name="message"></textarea></td> </tr> <tr> <td>Attach file:</td> <td><input type="file" name="attachFile" size="60" /></td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" value="Send E-mail" /> </td> </tr> </table> </form> </center> </body> </html>
There are three notices for this HTML form:
-
- action="sendmail.do": specifies the action name which will handle submission of this form.
- enctype="multipart/form-data": tells the browser that this form contains multipart data so it will construct a multipart request to be sent to the server.
- Using <input type="file"… />to show a file browse button from which the user can pick up a file.
3. Configuring Spring MVC for file upload and e-mail
Create a Spring's context configuration file spring-mvc.xml with the following XML code:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="net.codejava.spring" /> <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="smtp.gmail.com" /> <property name="port" value="587" /> <property name="username" value="youremail" /> <property name="password" value="yourpassword" /> <property name="javaMailProperties"> <props> <prop key="mail.transport.protocol">smtp</prop> <prop key="mail.smtp.auth">true</prop> <prop key="mail.smtp.starttls.enable">true</prop> </props> </property> </bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- max upload size in bytes --> <property name="maxUploadSize" value="20971520" /> <!-- 20MB --> <!-- max size of file in memory (in bytes) --> <property name="maxInMemorySize" value="1048576" /> <!-- 1MB --> </bean> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/" /> <property name="suffix" value=".jsp" /> </bean> <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <prop key="java.lang.Exception">Error</prop> </props> </property> </bean> </beans>
There are four beans declared in this configuration which draws our attention:
-
- mailSender: configures SMTP settings and JavaMail properties. Here the configuration is for a GMail account. So please update this to match with your account setting.
- multipartResolver: this bean is for parsing multipart request with CommonsMultipartResolver implementation which is based on Apache Commons File Upload. We also configure two file upload settings:
-
-
- maxUploadSize: maximum size (in bytes) of the multipart request, including the upload file, is set to 20 MB.
- maxInMemorySize: a threshold beyond which the upload file will be saved into disk, instead of in memory. Here it is set to 1 MB.
-
-
- viewResolver: maps logical view names to real JSP file names.
- SimpleMappingExceptionResolver: specifies the page (Error.jsp) which handles exception thrown (all exceptions of type java.langException).
The <context:component-scan .../> element tell Spring to look in the package net.codejava.spring for loading annotated classes (because we'll create a Spring controller using annotations later).
4. Implementing Spring MVC controller
Create a Java class named as SendEmailAttachController with the following code:
package net.codejava.spring; import java.io.IOException; import java.io.InputStream; import javax.mail.internet.MimeMessage; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.InputStreamSource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.mail.javamail.MimeMessagePreparator; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.commons.CommonsMultipartFile; @Controller @RequestMapping("/sendEmail.do") public class SendEmailAttachController { @Autowired private JavaMailSender mailSender; @RequestMapping(method = RequestMethod.POST) public String sendEmail(HttpServletRequest request, final @RequestParam CommonsMultipartFile attachFile) { // reads form input final String emailTo = request.getParameter("mailTo"); final String subject = request.getParameter("subject"); final String message = request.getParameter("message"); // for logging System.out.println("emailTo: " + emailTo); System.out.println("subject: " + subject); System.out.println("message: " + message); System.out.println("attachFile: " + attachFile.getOriginalFilename()); mailSender.send(new MimeMessagePreparator() { @Override public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper messageHelper = new MimeMessageHelper( mimeMessage, true, "UTF-8"); messageHelper.setTo(emailTo); messageHelper.setSubject(subject); messageHelper.setText(message); // determines if there is an upload file, attach it to the e-mail String attachName = attachFile.getOriginalFilename(); if (!attachFile.equals("")) { messageHelper.addAttachment(attachName, new InputStreamSource() { @Override public InputStream getInputStream() throws IOException { return attachFile.getInputStream(); } }); } } }); return "Result"; } }
This Spring controller (marked by @Controller annotation) is responsible for handling e-mail form's submission which is configured by two @RequestMapping annotations.
The second parameter of the sendEmail() method is annotated by @RequestParam annotation which maps the form field attachFile to a CommonsMultipartFile object that represents an upload file.
In the method sendEmail(), we capture input fields from the e-mail form (mailTo, subject and message) and send an e-mail by invoking the send() method on the mailSender object (which is automatically injected to this controller via the autowired property mailSender).
The send() method is passed with an anonymous class which implements the MimeMessagePreparator interface and implements the prepare() method. In the prepare() method we construct the e-mail message object with help of the MimeMessageHelper class and invoke its addAttachment() method to attach the upload file as attachment to the e-mail. This method reads data of upload file from the input stream which is returned by the attachFile object.
Finally, the controller redirects the user to a result page whose logical name is "Result".
NOTE: if the user doesn't pick up a file to attach, the attachName will be empty, so that there is a check to make sure we only add attachment if the upload file available.
5. Writing result and error pages
Code of the result page (Result.jsp) as follow:
<%@ 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=UTF-8"> <title>Send e-mail result</title> </head> <body> <center> <h2>Thank you, your email has been sent.</h2> </center> </body> </html>
This page simply shows a successful message after the file was uploaded and the e-mail has been sent.
And code of the error page (Error.jsp) would look like:
<%@ 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=UTF-8"> <title>Error</title> </head> <body> <center> <h2>Sorry, the email was not sent because of the following error:</h2> <h3>${exception.message}</h3> </center> </body> </html>
This page displays a detailed error message in case of exceptions thrown, such as the upload file's size exceeds the limit or SMTP setting is wrong.
6. Configuring web deployment descriptor file
Configure the web.xml file as follows:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>EmailAttachSpringMVC</display-name> <servlet> <servlet-name>SpringController</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>SpringController</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>EmailForm.jsp</welcome-file> </welcome-file-list> </web-app>
As usual, that declares the Spring controller servlet to intercept requests coming to the application, and specifies the default page (EmailForm.jsp) when accessing the application.
You can download this application in an Eclipse project or a deployable WAR file, under the attachment section.
Related Java E-mail Tutorials:
- Sending e-mail with Spring MVC
- How to send e-mail in HTML format in Java
- How to send email with attachments in Java
Other Spring Tutorials:
- Understand the core of Spring framework
- Understand Spring MVC
- Spring MVC beginner tutorial with Spring Tool Suite IDE
- Spring MVC Form Handling Tutorial
- Spring MVC Form Validation Tutorial
- Spring MVC with JdbcTemplate Example
- Spring MVC + Spring Data JPA + Hibernate - CRUD Example
- 14 Tips for Writing Spring MVC Controller
- Spring and Hibernate Integration Tutorial Part (XML Configuration)
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.
Add comment
Source: https://cpanel.codejava.net/frameworks/spring/spring-mvc-send-e-mail-with-attachments
0 Response to "Java Spring Mvc Post Example"
Post a Comment