久久国产成人av_抖音国产毛片_a片网站免费观看_A片无码播放手机在线观看,色五月在线观看,亚洲精品m在线观看,女人自慰的免费网址,悠悠在线观看精品视频,一级日本片免费的,亚洲精品久,国产精品成人久久久久久久

分享

利用Spring框架封裝的JavaMail現(xiàn)實同步或異步郵件發(fā)送

 大明明小珠珠 2015-10-30
  利用Spring框架封裝的JavaMail現(xiàn)實同步或異步郵件發(fā)送

作者:張紀豪

J2EE簡單地講是在JDK上擴展了各類應用的標準規(guī)范,郵件處理便是其中一個重要的應用,。它既然是規(guī)范,那么我們就可以通過JDK遵照郵件協(xié)議編寫一個郵件處理系統(tǒng),,但事實上已經有很多廠商和開源組織這樣做了,。Apache是J2EE最積極的實現(xiàn)者之一,當然還有我們的老大——SUN,。

聊起老大,,感慨萬端!他已經加入Oracle——甲骨文(不是刻在烏龜殼上的那種文字嗎,?是我中華,,也是人類上最早的語言啊,比Java早幾千年哦),,其掌門人拉里·埃里森是個不錯的水手,,別以為那只是在帆船上,至少他不至于蓋茨那么不仁道——開源萬歲,。有理由相信Java世界還有一段輝煌的歷程,。Google的Android和Chrome OS兩大操作系統(tǒng),還會首選Java作應用開發(fā)基礎語言,,即便是推出自己的易語言,。同時筆者預感到ChromeOS前景不可估量,它可能是推動云計算一個重要組成部分,,Andtroid(主用在移動設備上,,未來可能是手機上主流的操作系統(tǒng)),乃至微軟的Windows將來可能都是該系統(tǒng)的小窗口而已,。微軟已顯得老態(tài)龍鐘了,,再與大勢已去的雅虎合作,前進步伐必將大大減緩,。投資者此時可以長線買入Google股票(投資建議,,必自判斷),。筆者也常用google搜索引擎、gmail,。

好了,,閑話少聊,言歸主題,。

可能大家如筆者一樣用的最多的是老大的javamail,,雖然老大實現(xiàn)了郵件功能,但調用起來還是需要較復雜的代碼來完成,,而且初學者調用成功率很低(因為它還要與外界服務器通信),,這就使得初學者對于它越學越迷茫。不過這方面的例子很多,,因此筆者不再在此重復這些示例代碼,,而著重利用Spring框架封裝的郵件處理功能。

開工之前,,我們先了解下環(huán)境,。筆者開的是web工程,所需要的基礎配置如下:

▲ JDK 1.6

▲ J2EE 1.5


▲ JavaMail 1.4 稍作說明:J2EE 1.5中已經納入了郵件規(guī)范,,因此在開發(fā)期不要導入javamail中的jar包,,運行期則需要,因此可以將jar包放入到web容器的java庫中(例如Tomcat的lib目錄下),,要了解其意可以參考數(shù)據(jù)庫驅動包的運用,。文章結尾會對其進一步說明;

▲ Spring 2.5


▲ 一個郵箱 如上所述,,筆者愛用Google的Gmail郵箱,。

主要文件清單:

■ MailService.java 郵件處理對象接口

■ MailServiceImpl.java 上述實現(xiàn)

■ Email.java 一個普通的JavaBean,用于封裝郵件數(shù)據(jù),,并與html頁面中form表單對應

■ MailController.java 動作處理器

■ spring-core-config.xml Spring核心配置

筆者的web工程中,,WEB層使用的是Spring @MVC,當然我們僅需要了解其原理,,利用servlet或struts框架來做web層動作處理器都能實現(xiàn),。其它的文件,例如web.xml,,WEB層配置均略,。

下面開始代碼:

spring-core-config.xml:
  1. <!--①郵件服務器-->
  2. <beanid="mailSender"class="org.springframework.mail.javamail.JavaMailSenderImpl">
  3. <propertyname="protocol"value="smtp"/>
  4. <propertyname="host"value="smtp.gmail.com"/>
  5. <propertyname="port"value="465"/><!--Gmail的SMTP端口居然是這個,去google網站上了解吧-->
  6. <propertyname="username"value="到google注冊一個gmail賬戶"/>
  7. <propertyname="password"value="這里是密碼"/>
  8. <propertyname="javaMailProperties">
  9. <props>
  10. <propkey="mail.smtp.auth">true</prop>
  11. <propkey="mail.smtp.starttls.enable">true</prop>
  12. <propkey="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop><!--gmail要求的ssl連接-->
  13. </props>
  14. </property>
  15. </bean>
  16. <!--②異步線程執(zhí)行器-->
  17. <beanid="taskExecutor"class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
  18. <propertyname="corePoolSize"value="10"/>
  19. <propertyname="maxPoolSize"value="30"/>
  20. </bean>
  1. <!--①郵件服務器-->  
  2. <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">  
  3.     <property name="protocol" value="smtp"/>  
  4.     <property name="host" value="smtp.gmail.com"/>  
  5.     <property name="port" value="465" /><!--Gmail的SMTP端口居然是這個,,去google網站上了解吧-->  
  6.     <property name="username" value="到google注冊一個gmail賬戶"/>  
  7.     <property name="password" value="這里是密碼"/>  
  8.     <property name="javaMailProperties">  
  9.         <props>  
  10.             <prop key="mail.smtp.auth">true</prop>  
  11.             <prop key="mail.smtp.starttls.enable">true</prop>  
  12.             <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>                        <!--gmail要求的ssl連接-->  
  13.         </props>  
  14.     </property>  
  15. </bean>  
  16.   
  17. <!--②異步線程執(zhí)行器-->  
  18. <bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">  
  19.     <property name="corePoolSize" value="10"/>  
  20.     <property name="maxPoolSize" value="30"/>  
  21. </bean>  


這是郵件處理的兩個核心配置,,第一個配置(①)是往容器中裝配一個JavaMailSender Bean,它就是JavaMail的封裝,其中最關鍵的是裝配過程的屬性參數(shù),,這些屬性既要嚴格遵照JavaMail規(guī)范,,又要滿足郵件提供商的要求,例如SMTP服務器端口是多少,、發(fā)送時是否要身份驗證,、服務器是否采用安全連接、連接時是否加密以及采用什么樣的加密方式,,郵件服務商提供的這些參數(shù)直接影響到上述的配置,,這往往是新手最容易忽視的環(huán)節(jié),因此配置之前一定要到郵件提供商的站點上詳細了解郵箱的技術參數(shù),。

同步異步發(fā)送問題:JavaMail郵件處理是同步的,,即用戶觸發(fā)事件、與SMTP Server通信,、服務器返回狀態(tài)消息,、程序結束是單線程內,這時往往因Socket通信,、服務器業(yè)務處理速度等原因而使得處理時間是個未知數(shù),。舉個簡單的應用實例:若用戶在提交注冊的同時發(fā)送一封激活賬戶郵件,用戶有可能不知道是因為郵件服務器那兒阻塞致半天沒有反應而以為注冊失敗并放棄,,這將是失敗的設計,但異步方式能解決這些問題,。異步方式簡單地說就是將郵件處理任務交給另外一個線程,,J2EE有兩種解決方案,一是種利用JMS,,JMS可以實現(xiàn)同步和異步的消息處理,,將郵件作為一個異步的消息,就可以實現(xiàn)異步郵件發(fā)送,。JMS屬于J2EE的高級應用,,所以對于僅以WEB功能的容器還不支持這種服務,例如Tomcat(當然可以找到插件來解決),,由于篇幅限制,,本文不再牽涉到新的模塊。另一種方案是利用JDK中Executor的支持,,JDK 5.0后繼版本增加了java.util.concurrent一個強大的并發(fā)工具包,,它包含了執(zhí)行器、計時器,、鎖,、線程安全隊列、線程任務框架等等。Executor——執(zhí)行器,,它可以將任務的“提交”與“執(zhí)行”分離解耦,,我們的郵件處理任務完全可以借用它實現(xiàn)異步執(zhí)行。而Spring框架提供了封裝,,見②,。下面我們來看如何使用它,代碼如下,。

MailServiceImpl.java :

  1. package com.zhangjihao.service.impl;
  2. import java.io.IOException;
  3. import javax.annotation.Resource;
  4. import javax.mail.MessagingException;
  5. import javax.mail.internet.MimeMessage;
  6. import org.apache.commons.logging.Log;
  7. import org.apache.commons.logging.LogFactory;
  8. import org.springframework.core.io.ByteArrayResource;
  9. import org.springframework.core.task.TaskExecutor;
  10. import org.springframework.mail.javamail.JavaMailSender;
  11. import org.springframework.mail.javamail.MimeMessageHelper;
  12. import org.springframework.stereotype.Service;
  13. import org.springframework.web.multipart.MultipartFile;
  14. import com.zhangjihao.bean.Email;
  15. import com.zhangjihao.service.MailService;
  16. import com.zhangjihao.util.StringUtil;
  17. /**
  18. * 說明:<br>
  19. * * @author 張紀豪
  20. * @version
  21. * Build Time Jul 24, 2009
  22. */
  23. @Service("mailService")
  24. public class MailServiceImplimplements MailService {
  25. @Resource JavaMailSender mailSender;//注入Spring封裝的javamail,,Spring的xml中已讓框架裝配
  26. @Resource TaskExecutor taskExecutor;//注入Spring封裝的異步執(zhí)行器 private Log log = LogFactory.getLog(getClass());
  27. private StringBuffer message =new StringBuffer();
  28. public void sendMail(Email email)throws MessagingException, IOException {
  29. if(email.getAddress() == null || email.getAddress().length == 0) {
  30. this.message.append("沒有收件人");
  31. return;
  32. }
  33. if(email.getAddress().length >5){//收件人大于5封時,采用異步發(fā)送 sendMailByAsynchronousMode(email);
  34. this.message.append("收件人過多,,正在采用異步方式發(fā)送...<br/>");
  35. }else{
  36. sendMailBySynchronizationMode(email);
  37. this.message.append("正在同步方式發(fā)送郵件...<br/>");
  38. }
  39. }
  40. /**
  41. * 異步發(fā)送
  42. * @see com.zhangjihao.service.MailService#sendMailByAsynchronousMode(com.zhangjihao.bean.Email)
  43. */
  44. public void sendMailByAsynchronousMode(final Email email){ taskExecutor.execute(new Runnable(){
  45. public void run(){
  46. try {
  47. sendMailBySynchronizationMode(email);
  48. } catch (Exception e) {
  49. log.info(e);
  50. }
  51. }
  52. });
  53. }
  54. /**
  55. * 同步發(fā)送
  56. * @throws IOException
  57. * @see com.zhangjihao.service.MailServiceMode#sendMail(com.zhangjihao.bean.Email)
  58. */
  59. public void sendMailBySynchronizationMode(Email email)throws MessagingException, IOException {
  60. MimeMessage mime = mailSender.createMimeMessage(); MimeMessageHelper helper =new MimeMessageHelper(mime, true,"utf-8");
  61. helper.setFrom("[email protected]");//發(fā)件人
  62. helper.setTo(email.getAddress());//收件人
  63. helper.setBcc("[email protected]");//暗送
  64. if(StringUtil.hasLength(email.getCc())){
  65. String cc[] = email.getCc().split(";");
  66. helper.setCc(cc);//抄送
  67. }
  68. helper.setReplyTo("[email protected]");//回復到
  69. helper.setSubject(email.getSubject());//郵件主題
  70. helper.setText(email.getContent(), true);//true表示設定html格式
  71. //內嵌資源,,這種功能很少用,因為大部分資源都在網上,,只需在郵件正文中給個URL就足夠了.
  72. //helper.addInline("logo", new ClassPathResource("logo.gif")); //處理附件
  73. for(MultipartFile file : email.getAttachment()){
  74. if(file == null || file.isEmpty()){
  75. continue;
  76. }
  77. String fileName = file.getOriginalFilename();
  78. try {
  79. fileName = new String(fileName.getBytes("utf-8"),"ISO-8859-1");
  80. } catch (Exception e) {
  81. }
  82. helper.addAttachment(fileName, new ByteArrayResource(file.getBytes()));
  83. }
  84. mailSender.send(mime);
  85. }
  86. public StringBuffer getMessage() {return message; }
  87. public void setMessage(StringBuffer message) {this.message = message; }}
  1. package com.zhangjihao.service.impl;  
  2.   
  3. import java.io.IOException;  
  4. import javax.annotation.Resource;  
  5. import javax.mail.MessagingException;  
  6. import javax.mail.internet.MimeMessage;  
  7. import org.apache.commons.logging.Log;  
  8. import org.apache.commons.logging.LogFactory;  
  9. import org.springframework.core.io.ByteArrayResource;  
  10. import org.springframework.core.task.TaskExecutor;  
  11. import org.springframework.mail.javamail.JavaMailSender;  
  12. import org.springframework.mail.javamail.MimeMessageHelper;  
  13. import org.springframework.stereotype.Service;  
  14. import org.springframework.web.multipart.MultipartFile;  
  15. import com.zhangjihao.bean.Email;  
  16. import com.zhangjihao.service.MailService;  
  17. import com.zhangjihao.util.StringUtil;  
  18. /**  
  19. * 說明:<br>  
  20. *  * @author 張紀豪  
  21. * @version  
  22. * Build Time Jul 24, 2009  
  23. */  
  24.   
  25. @Service("mailService")  
  26. public class MailServiceImpl implements MailService {  
  27.  @Resource JavaMailSender mailSender;//注入Spring封裝的javamail,,Spring的xml中已讓框架裝配   
  28. @Resource TaskExecutor taskExecutor;//注入Spring封裝的異步執(zhí)行器  private Log log = LogFactory.getLog(getClass());  
  29. private StringBuffer message = new StringBuffer();    
  30. public void sendMail(Email email) throws MessagingException, IOException {    
  31.    if(email.getAddress() == null || email.getAddress().length == 0)    {     
  32.         this.message.append("沒有收件人");    
  33.         return;    
  34.       }    
  35.    if(email.getAddress().length > 5){//收件人大于5封時,采用異步發(fā)送   sendMailByAsynchronousMode(email);    
  36.  this.message.append("收件人過多,,正在采用異步方式發(fā)送...<br/>");  
  37.   }else{    
  38.  sendMailBySynchronizationMode(email);   
  39.   this.message.append("正在同步方式發(fā)送郵件...<br/>");   
  40.  }   
  41. }    
  42. /**    
  43. * 異步發(fā)送   
  44. * @see com.zhangjihao.service.MailService#sendMailByAsynchronousMode(com.zhangjihao.bean.Email)   
  45.  */  
  46. public void sendMailByAsynchronousMode(final Email email){  taskExecutor.execute(new Runnable(){    
  47.  public void run(){      
  48. try {      
  49.  sendMailBySynchronizationMode(email);   
  50.    } catch (Exception e) {    
  51.    log.info(e);     
  52.  }    
  53.  }    
  54. });   
  55. }   
  56.   
  57.  /**    
  58. * 同步發(fā)送   
  59. * @throws IOException    
  60. * @see com.zhangjihao.service.MailServiceMode#sendMail(com.zhangjihao.bean.Email)   
  61. */   
  62.   
  63. public void sendMailBySynchronizationMode(Email email) throws MessagingException, IOException {   
  64.  MimeMessage mime = mailSender.createMimeMessage();  MimeMessageHelper helper = new MimeMessageHelper(mime, true, "utf-8");    
  65. helper.setFrom("[email protected]");//發(fā)件人    
  66. helper.setTo(email.getAddress());//收件人    
  67. helper.setBcc("[email protected]");//暗送    
  68. if(StringUtil.hasLength(email.getCc())){    
  69.  String cc[] = email.getCc().split(";");   
  70.   helper.setCc(cc);//抄送   
  71.  }    
  72. helper.setReplyTo("[email protected]");//回復到   
  73.  helper.setSubject(email.getSubject());//郵件主題    
  74. helper.setText(email.getContent(), true);//true表示設定html格式    
  75.   //內嵌資源,,這種功能很少用,因為大部分資源都在網上,,只需在郵件正文中給個URL就足夠了.    
  76. //helper.addInline("logo", new ClassPathResource("logo.gif"));    //處理附件    
  77. for(MultipartFile file : email.getAttachment()){   
  78.   if(file == null || file.isEmpty()){     
  79.  continue;    
  80.  }     
  81. String fileName = file.getOriginalFilename();     
  82. try {     
  83.  fileName = new String(fileName.getBytes("utf-8"),"ISO-8859-1");   
  84.   } catch (Exception e) {  
  85. }   
  86.   helper.addAttachment(fileName, new ByteArrayResource(file.getBytes()));   
  87.  }    
  88. mailSender.send(mime);  
  89.  }  
  90.  public StringBuffer getMessage() {  return message; }  
  91.  public void setMessage(StringBuffer message) {  this.message = message; }}  


此類實現(xiàn)了MailService接口,,該接口僅三個方法(接口文件代碼省略):一個發(fā)送分流器、一個同步發(fā)送方法,、一個異步發(fā)送方法,。通過其實現(xiàn)者MailServiceImpl的代碼可以看出,郵件發(fā)送僅在同步發(fā)送這個方法中,,當需要異步執(zhí)行的時候,,只需要將其扔進taskExecutor異步執(zhí)行器中,就這么簡單,。這三個方法都是public修飾的,,所以在上層隨意調用哪個都行。以下看一個簡單的調用代碼,。

調用之前,,為讓初學者能更好地接受,先列出Email.java代碼:

Email.java:

  1. package com.zhangjihao.bean;
  2. import java.io.Serializable;
  3. import org.springframework.web.multipart.MultipartFile;
  4. import com.zhangjihao.util.StringUtil;
  5. /**
  6. * 說明:<br>
  7. *
  8. * @author 張紀豪
  9. * @version
  10. * Build Time Jul 24, 2009
  11. */
  12. public class Emailimplements Serializable {
  13. private staticfinal long serialVersionUID = 9063903350324510652L;
  14. /**用戶組:可以按用戶組來批量發(fā)送郵件**/
  15. private UserGroups userGroups;
  16. /**收件人**/
  17. private String addressee;
  18. /**抄送給**/
  19. private String cc;
  20. /**郵件主題**/
  21. private String subject;
  22. /**郵件內容**/
  23. private String content;
  24. /**附件**/
  25. private MultipartFile[] attachment =new MultipartFile[0];
  26. //////////////////////////解析郵件地址////////////////////////////// public String[] getAddress() {
  27. if(!StringUtil.hasLength(this.addressee)) {
  28. return null;
  29. }
  30. addressee = addressee.trim();
  31. addressee.replaceAll(",;", ";");
  32. addressee.replaceAll(" ", ";");
  33. addressee.replaceAll(",", ";");
  34. addressee.replaceAll(",,", ";");
  35. addressee.replaceAll("|", ";");
  36. return addressee.split(";"); }
  37. /////////////////////////////Getter && Setter///////////////////////////////
  38. ...... }
  1. package com.zhangjihao.bean;  
  2. import java.io.Serializable;  
  3. import org.springframework.web.multipart.MultipartFile;  
  4. import com.zhangjihao.util.StringUtil;  
  5. /**  
  6. * 說明:<br>  
  7. *   
  8. * @author 張紀豪  
  9. * @version  
  10. * Build Time Jul 24, 2009  
  11. */  
  12. public class Email implements Serializable {  
  13.  private static final long serialVersionUID = 9063903350324510652L;    
  14.   
  15. /**用戶組:可以按用戶組來批量發(fā)送郵件**/   
  16. private UserGroups userGroups;  
  17.  /**收件人**/  
  18.  private String addressee;    
  19. /**抄送給**/   
  20. private String cc;    
  21. /**郵件主題**/  
  22.  private String subject;   
  23.  /**郵件內容**/  
  24.  private String content;    
  25. /**附件**/   
  26. private MultipartFile[] attachment = new MultipartFile[0];    
  27.   
  28. //////////////////////////解析郵件地址//////////////////////////////  public String[] getAddress() {   
  29.  if(!StringUtil.hasLength(this.addressee)) {    
  30.  return null;    
  31. }   
  32.  addressee = addressee.trim();    
  33. addressee.replaceAll(";", ";");   
  34.  addressee.replaceAll(" ", ";");   
  35.  addressee.replaceAll(",", ";");   
  36.  addressee.replaceAll(",,", ";");    
  37. addressee.replaceAll("|", ";");    
  38. return addressee.split(";"); }  
  39.  /////////////////////////////Getter && Setter///////////////////////////////  
  40.  ...... }  


這個類就是一個簡單的JavaBean,,用于封裝郵件數(shù)據(jù),,對于習慣使用Struts框架的讀者,完全可以把它理解為一個ActionForm,。但對于MultipartFile類型且是數(shù)組的attachment屬性可能較難理解,,熟悉Struts框架的可以看作是FormFile,在Struts2中可能好理解些,。筆者使用的是Spring MVC,,框架中內置了這種屬性編輯器,因此很容易地將form表單上傳的文件進行轉換成這個字段,。

我們來看看WEB層調用,,其實到此為止,就已經完成本文的主題了,,因此WEB怎么調用都是圍繞MailService中的三個方法,,為便有全面的認識,將代碼列出,,不過最好需要了解Spring @MVC的一些知識,。

MailController.java:

  1. package com.zhangjihao.web.controller.system;
  2. import java.util.List;
  3. import javax.annotation.Resource;
  4. import javax.servlet.http.HttpServletRequest;
  5. import org.springframework.mail.javamail.JavaMailSender;
  6. import org.springframework.stereotype.Controller;
  7. import org.springframework.ui.ModelMap;
  8. import org.springframework.validation.BindingResult;
  9. import org.springframework.web.bind.annotation.ModelAttribute;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  11. import org.springframework.web.bind.annotation.RequestMethod;
  12. import org.springframework.web.bind.annotation.RequestParam;
  13. import com.zhangjihao.bean.Email;
  14. import com.zhangjihao.domain.user.User;
  15. import com.zhangjihao.service.MailService;
  16. import com.zhangjihao.service.UserService;
  17. import com.zhangjihao.util.StringUtil;
  18. import com.zhangjihao.web.controller.MasterController;
  19. import com.zhangjihao.web.validator.EmailValidator;
  20. /**
  21. * 說明:<br>
  22. * 郵件發(fā)送處理器
  23. * @author 張紀豪
  24. * @version
  25. * Build Time Jul 24, 2009
  26. */
  27. @Controllerpublic class MailControllerextends MasterController {
  28. @Resource MailService mailService;
  29. @Resource UserService userService;
  30. @RequestMapping(value = "/sendEmail", method=RequestMethod.GET) public String sendEmail(@RequestParam(value="email",required=false) String singleEmailAddress , HttpServletRequest request){
  31. Email email = new Email();
  32. if(StringUtil.hasLength(singleEmailAddress)){
  33. email.setAddressee(singleEmailAddress);
  34. }
  35. request.setAttribute("email", email);
  36. return "system/sendMail"; }@RequestMapping(value = "/sendEmail", method=RequestMethod.POST)
  37. public String send(
  38. @ModelAttribute Email email,//Spring MVC將form表單的數(shù)據(jù)封裝到這個對象中
  39. BindingResult result, ModelMap model, HttpServletRequest request){
  40. try {
  41. new EmailValidator().validate(email, result);
  42. if(result.hasErrors()){
  43. throw new RuntimeException("數(shù)據(jù)填寫不正確");
  44. }
  45. if(email.getEmailGroup()!=null){
  46. List<User> users = userService.getUserByUserGroups(email.getEmailGroup(),"userName,email", null,null); StringBuffer sb = new StringBuffer(StringUtil.hasLengthBytrim(email.getAddressee()) ? (email.getAddressee().trim() +";") : "");
  47. for(User user : users){
  48. sb.append(user.getEmail()).append(";");
  49. } email.setAddressee(sb.toString());
  50. }
  51. if(email.getAddress()==null || email.getAddress().length==0){ request.setAttribute("message","沒有收件人!"); return"message"; }
  52. mailService.sendMail(email); //大于5個收件人時,分流器會自動選擇異步方式發(fā)送
  53. request.setAttribute("message", mailService.getMessage().append("本次共發(fā)送了 ").append(email.getAddress().length).append(" 封郵件.").toString());
  54. }
  55. catch (Exception e) {
  56. request.setAttribute("message","Has errors! The info by "+e.getMessage()+"<br/>Can log in to view more detailed information on abnormalities.");
  57. log.error(this.getClass().getName()+"中發(fā)生異常---------------:\n", e);
  58. }
  59. return BACK + "message";
  60. }
  61. }
  1. package com.zhangjihao.web.controller.system;  
  2. import java.util.List;  
  3. import javax.annotation.Resource;  
  4. import javax.servlet.http.HttpServletRequest;  
  5. import org.springframework.mail.javamail.JavaMailSender;  
  6. import org.springframework.stereotype.Controller;  
  7. import org.springframework.ui.ModelMap;  
  8. import org.springframework.validation.BindingResult;  
  9. import org.springframework.web.bind.annotation.ModelAttribute;  
  10. import org.springframework.web.bind.annotation.RequestMapping;  
  11. import org.springframework.web.bind.annotation.RequestMethod;  
  12. import org.springframework.web.bind.annotation.RequestParam;  
  13. import com.zhangjihao.bean.Email;  
  14. import com.zhangjihao.domain.user.User;  
  15. import com.zhangjihao.service.MailService;  
  16. import com.zhangjihao.service.UserService;  
  17. import com.zhangjihao.util.StringUtil;  
  18. import com.zhangjihao.web.controller.MasterController;  
  19. import com.zhangjihao.web.validator.EmailValidator;  
  20. /**  
  21. * 說明:<br>  
  22. * 郵件發(fā)送處理器  
  23. * @author 張紀豪  
  24. * @version  
  25. * Build Time Jul 24, 2009  
  26. */  
  27. @Controllerpublic class MailController extends MasterController {  
  28.  @Resource MailService mailService;   
  29. @Resource UserService userService;  
  30.  @RequestMapping(value = "/sendEmail", method=RequestMethod.GET) public String sendEmail(@RequestParam(value="email",required=false) String singleEmailAddress , HttpServletRequest request){   
  31.  Email email = new Email();    
  32. if(StringUtil.hasLength(singleEmailAddress)){    
  33.  email.setAddressee(singleEmailAddress);   
  34.  }    
  35. request.setAttribute("email", email);    
  36. return "system/sendMail"; }  @RequestMapping(value = "/sendEmail", method=RequestMethod.POST)  
  37.  public String send(     
  38. @ModelAttribute Email email,  //Spring MVC將form表單的數(shù)據(jù)封裝到這個對象中    
  39.  BindingResult result,   ModelMap model,   HttpServletRequest request){   
  40.  try {   
  41.   new EmailValidator().validate(email, result);    
  42.  if(result.hasErrors()){    
  43.   throw new RuntimeException("數(shù)據(jù)填寫不正確");    
  44.  }    
  45.  if(email.getEmailGroup()!=null){    
  46.   List<User> users = userService.getUserByUserGroups(email.getEmailGroup(), "userName,email", null, null);    StringBuffer sb = new StringBuffer(StringUtil.hasLengthBytrim(email.getAddressee()) ? (email.getAddressee().trim() + ";") : "");     
  47.  for(User user : users){     
  48.   sb.append(user.getEmail()).append(";");      
  49. }    email.setAddressee(sb.toString());    
  50.  }   
  51.   if(email.getAddress()==null || email.getAddress().length==0){    request.setAttribute("message", "沒有收件人!");    return "message";   }    
  52.     mailService.sendMail(email);  //大于5個收件人時,,分流器會自動選擇異步方式發(fā)送     
  53. request.setAttribute("message", mailService.getMessage().append("本次共發(fā)送了 ").append(email.getAddress().length).append(" 封郵件.").toString());      
  54.  }   
  55. catch (Exception e) {   
  56.   request.setAttribute("message", "Has errors! The info by "+e.getMessage()+"<br/>Can log in to view more detailed information on abnormalities.");     
  57. log.error(this.getClass().getName()+"中發(fā)生異常---------------:\n", e);    
  58. }    
  59. return BACK + "message";   
  60. }  
  61. }  


當一個get方法請求的連接進來,,此控制器會轉向一個html頁面,其頁面中有form表單,,表單中的字段與Email.java對應,,當post方法過來后,Spring MVC會把表單中的數(shù)據(jù)填充到Email對象中,,交給MailService處理就ok了,。

最后講述下最容易出現(xiàn)的錯誤:

網上很多人都說J2EE5兼容性不好,例如典型的javamail1.4中包與J2EE5中包接口包引起沖突,,導致單元測試經常報如下錯誤:

java.lang.NoClassDefFoundError: com/sun/mail/util/BEncoderStream

當然這個錯誤是沒有將javamail的實現(xiàn)者引進工程(沒有導包),但導包后,,就會出現(xiàn)另外一個錯誤:

java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream

此時甚至web容器都無法啟動,,經常會有網友們?yōu)檫@兩個異常搞得焦頭爛額,如此更換J2EE1.4,,會對工程造成影響,。但是一定要把概念弄清楚,問題就好解決,。J2EE5中mail.jar包定義的只是接口,,沒有實現(xiàn),是不能真正發(fā)送郵件的,,但開發(fā)編譯肯定是可以過去的,,因為我們是針對J2EE規(guī)范編的程序。而運行期用Sun公司的JavaMail1.4的實現(xiàn)才可以開始發(fā)送郵件,但老大為什么把這兩個弄沖突了?

筆者的解決辦法是:

開發(fā)期不要導包,,運行期將javamail1.4壓縮文件中的mail.jar包放入到tomcat\lib目錄下,,這樣完全可以通過開發(fā)和運行。若要做單元測試則新開一個Java Project,,注意,,不是web工程,此時可以將javamail1.4壓縮包中的mail.jar放入到工程的classpath下,。 

    本站是提供個人知識管理的網絡存儲空間,,所有內容均由用戶發(fā)布,不代表本站觀點,。請注意甄別內容中的聯(lián)系方式,、誘導購買等信息,謹防詐騙,。如發(fā)現(xiàn)有害或侵權內容,,請點擊一鍵舉報。
    轉藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多