`

Spring整合Velocity JavaMail

 
阅读更多

原创转载请注明出处: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
mail.support.username=youremail@gmail.com
mail.support.password=Password1!
# VELOCITY TEMPLATES
spring.velocity.resource-loader-path=classpath:/templates/velocity

 

template.properties

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("test@test.com");
				message.setFrom("test@test.com");
				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

 

 

 

 

 

 

 


 

  • 大小: 27.2 KB
  • 大小: 8.3 KB
  • 大小: 42.4 KB
  • 大小: 16.5 KB
  • 大小: 4.3 KB
分享到:
评论

相关推荐

    spring+velocity发送邮件

    - JavaMail API:未明确指定版本,一般情况下,Spring会集成JavaMail的相关API进行使用。 ### 邮件发送类详解 #### 类结构 根据提供的代码片段,可以看到一个名为`VelocityTemplateMailMessage`的类,该类主要用于...

    简单学习使用Spring+Velocity发送邮件

    为了在Spring中集成Velocity,我们需要添加以下依赖: 1. `velocity-engine-core`:Velocity的核心库。 2. `velocity-tools-view`:Spring MVC与Velocity集成所需的工具库。 在Spring配置文件中,你需要定义一个`...

    struts2+spring3.0+mybatis3.0.4集成的邮件发送实例(可上传附件)

    对于Java开发者来说,理解和掌握这个集成过程将有助于提升在实际项目中的应用能力。 首先,Struts2作为MVC框架,主要负责控制层的处理,它通过Action类来接收和处理用户的请求。在这个实例中,我们可能有一个名为`...

    spring mail

    Spring Mail 是一个在Java应用程序中发送电子邮件的库,它与流行的Spring框架紧密集成,使得邮件发送功能的实现变得更加简单和灵活。Spring Mail 提供了一种优雅的方式来配置和使用JavaMail API,而无需直接处理复杂...

    Spring-Reference_zh_CN(Spring中文参考手册)

    2. Spring 2.0 的新特性 2.1. 简介 2.2. 控制反转(IoC)容器 2.2.1. 更简单的XML配置 2.2.2. 新的bean作用域 2.2.3. 可扩展的XML编写 2.3. 面向切面编程(AOP) 2.3.1. 更加简单的AOP XML配置 2.3.2. 对@AspectJ 切面的...

    spring+sendmail+模板+properties+vm

    Spring通过集成JavaMail API,使得开发者能够方便地在应用程序中添加邮件发送功能。 2. **模板技术**: 在Spring中,我们可以使用模板引擎来动态生成邮件内容,提高邮件的可读性和定制性。常见的模板引擎有Velocity...

    使用Spring的JAVA Mail支持简化邮件发送功能

    在本文中,我们将深入探讨如何使用Spring框架的Java Mail支持来简化邮件发送功能。Spring为开发者提供了便捷的方式来发送电子邮件,包括简单的文本邮件...这种强大的功能使得在Spring应用中集成邮件服务变得非常便捷。

    javamail最新版JAR包!

    此外,对于企业级应用,还可以考虑使用 Spring Framework 的 `JavaMailSender` 接口,以简化邮件服务的集成和配置。 总之,JavaMail 1.4.3 是Java平台上的一个强大邮件处理库,它为开发者提供了全面的邮件操作功能...

    Spring 2.0 开发参考手册

    14.4. Velocity和FreeMarker 14.4.1. 需要的资源 14.4.2. Context 配置 14.4.3. 创建模板 14.4.4. 高级配置 14.4.5. 绑定支持和表单处理 14.5. XSLT 14.5.1. 写在段首 14.5.2. 小结 14.6. 文档视图(PDF/...

    SPRING各实用开发包用途及解释

    这个库提供了Spring与Hibernate框架之间的整合支持,适用于Hibernate 2和Hibernate 3版本。如果你的应用需要与Hibernate集成,则需要此库。 ##### (7) spring-jdbc.jar 此库为Spring JDBC提供了封装支持,简化了...

    spring chm文档

    14.4. Velocity和FreeMarker 14.4.1. 需要的资源 14.4.2. Context 配置 14.4.3. 创建模板 14.4.4. 高级配置 14.4.5. 绑定支持和表单处理 14.5. XSLT 14.5.1. 写在段首 14.5.2. 小结 14.6. 文档视图(PDF/...

    cxf(jax-ws)+spring+hibernate整合包

    spring-expression-3.0.7.RELEASE.jar,spring-hibernate3.jar,spring-jms-3.0.7.RELEASE.jar,spring-tx-3.0.7.RELEASE.jar,spring-web-3.0.7.RELEASE.jar,sqljdbc4.jar,stax2-api-3.1.1.jar,velocity-1.7.jar,WHICH_...

    Spring中使用FreeMaker或Vilocity模板发送邮件

    通过以上步骤,我们可以利用Spring集成FreeMarker或Velocity,实现根据模板动态生成邮件内容并发送。这种方式使得邮件内容更具灵活性,能够适应不同的场景需求,比如发送订单确认邮件、活动通知等。同时,由于Spring...

    java发送邮件所需jar包

    Spring通过集成JavaMail API,提供了一种更加便捷的方式来配置和使用邮件服务。比如,你可以使用`org.springframework.mail.javamail.JavaMailSender`接口来发送邮件,它简化了邮件的构造和发送过程。同时,Spring还...

    java邮件

    - JavaMail API可以与其他Java库集成,例如Spring框架中的`JavaMailSender`接口,简化邮件发送的代码。 总结来说,Java邮件技术是Java开发者必备的技能之一,它涵盖了一系列复杂的协议和编码规则。通过熟练掌握...

    SpringBoot配置Email发送功能实例

    spring-boot-starter-mail提供了Email发送功能,而spring-boot-starter-velocity提供了模板引擎velocity的支持。 三、 配置Email发送功能实例 要配置Email发送功能实例,需要在application.properties文件中添加...

    宏天JAVA开发平台

    该平台涵盖了Spring2.5、Struts2.0.14、SpringSecurity2.0、SpringAOP、Hibernate3.3GA、FCKEditor2.6、EXT3、CXF2.0、JBPM4.4GA、Compass+Lucene、JasperReport4、JavaMail等一系列前沿技术组件,以及Log4j、...

    刘树全的J2EE培训教程

    2.1和3.0版本)、数据库相关技术(JDBC、DAO模式、Spring JDBC、ORM框架如Hibernate、iBatis和JDO)、JMS(Java消息服务)、JavaMail、资源连接(JNDI、DataSource、Database Connection、Mail Session、URL ...

    Struts2.0需要的包

    在搭建SSH(Spring、Struts2、Hibernate)整合框架时,除了Struts2的这些包,还需要Spring框架和Hibernate的相应依赖,以实现控制层、业务层和服务层的解耦和数据访问层的事务管理。 总结来说,搭建Struts2.0环境...

    email-service

    在邮件服务方面,Spring Boot集成了JavaMailSender接口,使得邮件发送变得简单。 3. **模板引擎**: 为了发送格式化或动态内容的邮件,项目可能使用了Thymeleaf、FreeMarker或Velocity等模板引擎。这些工具允许...

Global site tag (gtag.js) - Google Analytics