原创转载请注明出处:http://agilestyle.iteye.com/admin/blogs/2323882
Project Directory
Maven Dependency
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.fool</groupId> <artifactId>springmvc</artifactId> <name>springmvc</name> <packaging>war</packaging> <version>1.0.0-BUILD-SNAPSHOT</version> <properties> <org.springframework-version>4.2.7.RELEASE</org.springframework-version> </properties> <dependencies> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.1</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>19.0</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency> <!-- @Inject --> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> <!-- Servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- Test --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity</artifactId> <version>1.7</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-eclipse-plugin</artifactId> <version>2.10</version> <configuration> <additionalProjectnatures> <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature> </additionalProjectnatures> <additionalBuildcommands> <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand> </additionalBuildcommands> <downloadSources>true</downloadSources> <downloadJavadocs>true</downloadJavadocs> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.8</source> <target>1.8</target> <compilerArgument>-Xlint:all</compilerArgument> <showWarnings>true</showWarnings> <showDeprecation>true</showDeprecation> </configuration> </plugin> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>9.3.11.v20160721</version> <configuration> <scanIntervalSeconds>10</scanIntervalSeconds> <httpConnector> <port>8888</port> </httpConnector> <webApp> <contextPath>/springmvc</contextPath> </webApp> </configuration> </plugin> </plugins> </build> </project>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- The definition of the Root Spring Container shared by all Servlets and Filters --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/root-context.xml</param-value> </context-param> <!-- Creates the Spring Container shared by all Servlets and Filters --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Processes application requests --> <servlet> <servlet-name>appServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>appServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
root-context.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- Root Context: defines shared resources visible to all other web components --> </beans>
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure --> <!-- Enables the Spring MVC @Controller programming model --> <annotation-driven /> <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory --> <resources mapping="/resources/**" location="/resources/" /> <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory --> <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <beans:property name="prefix" value="/WEB-INF/views/" /> <beans:property name="suffix" value=".jsp" /> </beans:bean> <context:component-scan base-package="org.fool.springmvc" /> </beans:beans>
mail.properties(自行测试的话,需要将对应的属性Value替换掉)
# Mailing mail.transport.protocol=smtp mail.smtp.host=atom.test.com mail.smtp.port=25 [email protected] mail.support.password=Password1! # VELOCITY TEMPLATES spring.velocity.resource-loader-path=classpath:/templates/velocity
template.properties
扫描二维码关注公众号,回复:
581581 查看本文章
monitor.template.name=templates/velocity/monitor.vm
User.java
package org.fool.springmvc; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; public class User { private Long id; private String username; private String password; private String email; public User() { } public User(Long id, String username, String password) { this.id = id; this.username = username; this.password = password; } public User(Long id, String username, String password, String email) { this.id = id; this.username = username; this.password = password; this.email = email; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
UserService.java
package org.fool.springmvc; import java.util.Map; import javax.inject.Inject; import javax.mail.internet.MimeMessage; import org.apache.velocity.app.VelocityEngine; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.mail.javamail.MimeMessagePreparator; import org.springframework.stereotype.Service; import org.springframework.ui.velocity.VelocityEngineUtils; import com.google.common.collect.Maps; @Service @PropertySource("classpath:template.properties") public class UserService { @Inject private JavaMailSender javaMailSender; @Inject private VelocityEngine velocityEngine; @Value("${monitor.template.name}") private String monitorTemplateName; public User saveUser(User user) { System.out.println("---From Service---"); System.out.println(user.getId()); System.out.println(user.getUsername()); System.out.println(user.getPassword()); System.out.println(user.getEmail()); this.sendConfirmationEmail(user); return user; } private void sendConfirmationEmail(User user) { MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setTo("[email protected]"); message.setFrom("[email protected]"); message.setSubject("Registration Confirmation"); Map<String, Object> model = Maps.newHashMap(); model.put("user", user); message.setText(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, monitorTemplateName, "UTF-8", model)); } }; this.javaMailSender.send(preparator); } }
UserController.java
@Controller @RequestMapping("/user") public class UserController { @Inject private UserService userService; @RequestMapping(value = "/addUser", method = RequestMethod.POST) @ResponseBody public User addUser(@RequestBody User user) { System.out.println("===From Controller==="); System.out.println(user.getId()); System.out.println(user.getUsername()); System.out.println(user.getPassword()); System.out.println(user.getEmail()); return userService.saveUser(user); } ...
MailConfig.java
package org.fool.springmvc.email; import java.util.Properties; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.ui.velocity.VelocityEngineFactoryBean; @Configuration @PropertySource("classpath:mail.properties") public class MailConfig { @Value("${mail.transport.protocol}") private String protocol; @Value("${mail.smtp.host}") private String host; @Value("${mail.smtp.port}") private Integer port; @Value("${mail.support.username}") private String username; @Value("${mail.support.password}") private String password; @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfig() { return new PropertySourcesPlaceholderConfigurer(); } @Bean public JavaMailSender javaMailSender() { JavaMailSenderImpl sender = new JavaMailSenderImpl(); sender.setProtocol(protocol); sender.setHost(host); sender.setPort(port); // sender.setUsername(username); // sender.setPassword(password); // sender.setJavaMailProperties(getMailProperties()); return sender; } @Bean public VelocityEngineFactoryBean velocityEngineFactoryBean() { VelocityEngineFactoryBean velocityEngine = new VelocityEngineFactoryBean(); velocityEngine.setVelocityProperties(getVelocityProperties()); return velocityEngine; } // private Properties getMailProperties() { // Properties properties = new Properties(); // properties.setProperty("mail.smtp.auth", "true"); // properties.setProperty("mail.smtp.starttls.enable", "true"); // properties.setProperty("mail.debug", "false"); // return properties; // } private Properties getVelocityProperties() { Properties properties = new Properties(); properties.setProperty("resource.loader", "class"); properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); return properties; } }
这里需要注意的是,如果你使用Annotation来进行Context Config的话,为了避免@Value解析不到值,需要手动定义一个static的PropertySourcesPlaceholderConfigurer的Bean
Test
http://localhost:8888/springmvc/user/addUser
Console Output
Email Output
Reference
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mail.html