通过发送邮件找回密码

 

警告: javamail包与 geronimo-javamail_1.4_spec-1.3.jar 它有冲突,
类似这种冲突的包有好多,大家要千万注意,否则会让你纠结许久。此工程我使用 javaMail包

开始正题:
1:在工程下创建 发送邮件模板,此处我采取的是 用velocity 的方式,所以后缀名为 .vm

Html代码 复制代码 
  1. <html>  
  2. <body>  
  3. <div id="contentDiv" style="font-size:14px;height:auto;padding:15px 0 10px 15px;*padding:15px 0 0 15px;overflow:visible;line-height:170%;min-height:100px;_height:100px;" class="" >  
  4.     <table id="" width="100%" cellpadding="0" cellspacing="0" border="0">  
  5.         <tr>  
  6.             <td valign="top" style="font-size:14px;padding:0;height:auto;min-height:auto;font-family: 'lucida Grande',Verdana;" class="body">  
  7.                 <div id="mailContentContainer" class="left">  
  8.                     <style type='text/css'>  
  9.                      <!--   
  10.                      body,td,th {   
  11.                         font-size: 12px;   
  12.                         color: #393939;   
  13.                         line-height: 24px;   
  14.                      }   
  15.                      .te2 {WIDTH: 80px; HEIGHT: 17px;BACKGROUND-COLOR: #ffffff;border: 1px solid #A6BEE0;}   
  16.                      .font_line28 {line-height: 32px; ; ;}   
  17.                      .font_blue14_bold {color:#1369BF;font-weight: bold;    font-size: 14px;line-height: 23px;}   
  18.                      .font_blue122_bold {color:#4D728F;font-weight: bold;;}   
  19.                      .font_red12 { font-size:12px;color:#FF0000;}   
  20.                      .fant_hui12 { font-size:12px;color:#B9B9B9;}   
  21.                      .font_blue12{color:#4D728F;    padding-right: 7px;}   
  22.                      .font_blue12 a:link{ color:#4D728F; text-decoration:underline;}   
  23.                      .font_blue12 a:visited{color:#4D728F; text-decoration:underline;}   
  24.                     .font_blue12 a:hover {color:#4D728F; text-decoration:underline;}   
  25.                     -->  
  26.                     </style>  
  27.                         <table width='500' border='0' align='center' cellpadding='0' cellspacing='1' bgcolor='#0BA5EB'>  
  28.                           <tr>  
  29.                             <td align='left' valign='top' bgcolor='#FFFFFF'>  
  30.                                 <table width='100%' border='0' cellspacing='0' cellpadding='0'>  
  31.                                   <tr>  
  32.                                     <td width='39' height='26' background='http://uc.cun365.com/images/cun365/reg_r2_c4.jpg'><img src='http://10.10.1.11/ucenter/images/cun365/reg_r2_c21.jpg' width='34' height='26'/></td>  
  33.                                     <td width='577' align='left' valign='bottom' background='http://uc.cun365.com/images/cun365/reg_r2_c4.jpg' class='font_blue14_bold'>确认邮件</td>  
  34.                                     <td width='32' align='left' valign='middle' background='http://uc.cun365.com/images/cun365/reg_r2_c4.jpg'><img src='http://uc.cun365.com/images/cun365/gif-0081.gif' width='23' height='17'/></td>  
  35.                                   </tr>  
  36.                                 </table>  
  37.                             </td>  
  38.                           </tr>  
  39.                           <tr>  
  40.                             <td align='center' valign='top' bgcolor='#FFFFFF'>  
  41.                                 <table width='92%' border='0' cellspacing='0' cellpadding='0'>  
  42.                                   <tr>  
  43.                                     <td height='12'></td>  
  44.                                   </tr>  
  45.                                   <tr>  
  46.                                     <td align='left' valign='top'>  
  47.                                         亲爱的<span class='font_red12'>$!{userName}</span>,您好:<br/>  
  48.                             &nbsp;&nbsp;&nbsp; 当您收到这封信的时候,您已经可以用新密码正常登录了。<br/>  
  49.                             &nbsp;&nbsp;&nbsp; 您的新密码为:&nbsp;&nbsp;&nbsp;<span class='font_red12'>  
  50.                             $!{password}</span>  
  51.                                     </td>  
  52.                                   </tr>  
  53.                                   <tr>  
  54.                                     <td height='13' align='left' valign='top'></td>  
  55.                                   </tr>  
  56.                                   <tr>  
  57.                                     <td height='13' align='left' valign='top' background='http://uc.cun365.com/images/cun365/reg_line.jpg'></td>  
  58.                                   </tr>  
  59.                                   <tr>  
  60.                                     <td align='left' valign='top'>  
  61.                                         <span class='font_blue122_bold'>点击以下链接,访问我xxx:</span><br/>  
  62.                                        <a href='http://www.xxx.com' target="_blank" class='font_blue12'>http://www.cun365.com</a>  
  63.                                        <span class='fant_hui12'><br/>(如果不能点击该链接地址,请复制并粘贴到浏览器的地址输入框)</span>  
  64.                                     </td>  
  65.                                   </tr>  
  66.                                   <tr>  
  67.                                     <td align='left' valign='top'>  
  68.                                         <span class='font_blue122_bold'>点击以下链接,进行修改密码:</span><br/>  
  69.                                        <a href='http://uc.cun365.com/login?service=http://xx.com/xx?oldPwd=$!{password}' target="_blank" class='font_blue12'>http://uc.cun365.com/login?service=http://xx.com/?oldPwd=$!{password}</a>  
  70.                                        <span class='fant_hui12'><br/>(如果不能点击该链接地址,请复制并粘贴到浏览器的地址输入框)</span>  
  71.                                     </td>  
  72.                                   </tr>                                       
  73.                                   <tr>  
  74.                                     <td height='40' align='center' valign='middle'><span class='font_gray14'>  
  75.                                       <a href='http://xxx?service=http://xxx?json=abcdeu123' target='_blank'><img src='http://uc.cun365.com/images/cun365/but-1.gif' width='203' height='24' border=0//></a>  
  76.                                     </span></td>  
  77.                                   </tr>  
  78.                                      
  79.                                   <tr>  
  80.                                     <td height='13' align='left' valign='top'></td>  
  81.                                   </tr>  
  82.                                   <tr>  
  83.                                     <td height='13' align='left' valign='top' background='http://uc.cun365.com/images/cun365/reg_line.jpg'></td>  
  84.                                   </tr>  
  85.                                   <tr>  
  86.                                     <td align='left' valign='top'>  
  87.                                         <p> 此邮件为系统所发,请勿直接回复。&nbsp; &nbsp; <br/><br/></p>  
  88.                                     </td>  
  89.                                   </tr>  
  90.                                   <tr>  
  91.                                     <td align='left' valign='top'>&nbsp;</td>  
  92.                                   </tr>  
  93.                                 </table>  
  94.                             </td>  
  95.                           </tr>  
  96.                         </table>  
  97.                 </div>  
  98.             </td>  
  99.             <td width="170">&nbsp;</td>  
  100.         </tr>  
  101.     </table>  
  102. </div>  
  103. <div id="mailContentContainer">  
  104. &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;如果您有任何问题,请查看<a href="#">隐私权保护规则</a><br/>  
  105. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;服务热线:15034401440   电子邮箱:<a href="mailto:renwg@transna.com">renwg@transnal.com</a>  
  106. </div>  
  107. </body>  
  108. </html>  



2:写认证类(因为我采取的是国际标准,所以比较繁琐,当然也有简单的方法,大家在开发中还是以标准为好)

Java代码 复制代码  收藏代码
  1. package com.transnal.utils;   
  2.   
  3. import javax.mail.*;      
  4.   
  5. /**  
  6.  * Smtp认证,此类事必须要有的,是为了遵循sum公司定下的规范  
  7.  * @author renwg  
  8.  * @since 2010.5.30  
  9.  * @version 1.0  
  10.  *  
  11.  */  
  12. public class MyAuthenticator extends Authenticator{      
  13.     private String userName=null;      
  14.     private String password=null;      
  15.            
  16.   
  17.     public MyAuthenticator(){}      
  18.        
  19.     /**    
  20.      * SMTP身份验证    
  21.      * @param username    
  22.      * @param password    
  23.      */       
  24.     public MyAuthenticator(String username, String password) {       
  25.         this.userName = username;       
  26.         this.password = password;       
  27.     }       
  28.     protected PasswordAuthentication getPasswordAuthentication(){     
  29.         System.out.println("服务器正在验证用户:"+userName);   
  30.         System.out.println("服务器正在验证密码:"+password);   
  31.         return new PasswordAuthentication(userName, password);     
  32.     }      
  33. }     
package com.transnal.utils;

import javax.mail.*;   

/**
 * Smtp认证,此类事必须要有的,是为了遵循sum公司定下的规范
 * @author renwg
 * @since 2010.5.30
 * @version 1.0
 *
 */
public class MyAuthenticator extends Authenticator{   
    private String userName=null;   
    private String password=null;   
        

	public MyAuthenticator(){}   
    
    /**  
     * SMTP身份验证  
     * @param username  
     * @param password  
     */    
    public MyAuthenticator(String username, String password) {    
        this.userName = username;    
        this.password = password;    
    }    
    protected PasswordAuthentication getPasswordAuthentication(){  
    	System.out.println("服务器正在验证用户:"+userName);
    	System.out.println("服务器正在验证密码:"+password);
        return new PasswordAuthentication(userName, password);  
    }   
}   




以下是一个公共类,此类中包含企业常用的方法

Java代码 复制代码  收藏代码
  1. package com.transnal.utils;   
  2.   
  3. import java.io.File;   
  4. import java.io.IOException;   
  5. import java.io.InputStream;   
  6. import java.io.StringWriter;   
  7. import java.util.Date;   
  8. import java.util.HashMap;   
  9. import java.util.Iterator;   
  10. import java.util.Map;   
  11. import java.util.Properties;   
  12. import java.util.ResourceBundle;   
  13. import java.util.regex.Pattern;   
  14.   
  15. import javax.mail.internet.InternetAddress;   
  16. import javax.mail.internet.MimeBodyPart;   
  17. import javax.mail.internet.MimeMultipart;   
  18. import javax.mail.Address;   
  19. import javax.mail.BodyPart;   
  20. import javax.mail.Message;   
  21. import javax.mail.Multipart;   
  22. import javax.mail.Session;   
  23. import javax.mail.Transport;   
  24. import javax.mail.internet.MimeMessage;   
  25. import javax.servlet.http.Cookie;   
  26. import javax.servlet.http.HttpServletRequest;   
  27. import javax.servlet.http.HttpServletResponse;   
  28. import net.sxinfo.profile.Profile;   
  29. import net.sxinfo.profile.ProfileInfo;   
  30. import net.sxinfo.user.User;   
  31. import net.sxinfo.user.UserFactory;  //这个东西我不说,你也知道了,就是一个读取 资源文件的 类。   
  32.   
  33. import org.apache.commons.io.FileUtils;   
  34. import org.apache.commons.lang.StringUtils;   
  35. import org.apache.struts2.ServletActionContext;   
  36. import org.apache.velocity.Template;   
  37. import org.apache.velocity.VelocityContext;   
  38. import org.apache.velocity.app.VelocityEngine;   
  39.   
  40. import com.opensymphony.xwork2.ActionContext;   
  41.   
  42. /**  
  43.  * 所有共用的方法都被调到这个类里  
  44.  *   
  45.  * @author RenWeigang  
  46.  *   
  47.  * @since 2010.08.02  
  48.  *   
  49.  * @version 1.0  
  50.  *  
  51.  */  
  52. public class WebUtil {   
  53.        
  54.     private static String directoryId;   
  55.     private static String userName;   
  56.        
  57.        
  58.     /**  
  59.      * 設置提示信息(僅限request請求輸出)  
  60.      * @param paramString  
  61.      */  
  62.     public static void addError(String paramString){   
  63.         ServletActionContext.getRequest().setAttribute("msg",paramString);   
  64.     }   
  65.        
  66.     /**  
  67.      * URI跳转  
  68.      */  
  69.     public static void redirectService(){   
  70.         HttpServletRequest request = ServletActionContext.getRequest();   
  71.         String s_m = request.getParameter("success_msg");   
  72.         if(StringUtils.isNotBlank(s_m) && (s_m.equals("%E6%88%90%E5%8A%9F") || s_m.equals("成功"))){   
  73.             HttpServletResponse response = ServletActionContext.getResponse();   
  74.             StringBuilder sb = new StringBuilder("修改成功!");   
  75.             String paramService = request.getParameter("service");   
  76.             if(StringUtils.isNotBlank(paramService) && (paramService.startsWith("http") || paramService.startsWith("ftp"))){   
  77.                 if(paramService.startsWith("http"))   
  78.                 {   
  79.                     paramService ="http://"+paramService.replaceAll("^http\\:\\/+","");   
  80.                 }   
  81.                 if(paramService.startsWith("ftp")){   
  82.                     paramService ="ftp://"+paramService.replaceAll("^ftp\\:\\/+","");   
  83.                 }   
  84.                 sb.append("3秒后跳转到您原始的页面!如没有相应,请点击<font color='red'><a href='");   
  85.                 sb.append(paramService);   
  86.                 sb.append("' target='_blank'>");   
  87.                 sb.append("这里");   
  88.                 sb.append("</a>");   
  89.                 sb.append("</font>");   
  90.                 String url = getBasePath(request)+"logout?url="+paramService;   
  91.                 response.setHeader("Refresh","3;URL="+url);   
  92.             }   
  93.             ServletActionContext.getRequest().setAttribute("msg",sb.toString());       
  94.         }   
  95.     }   
  96.        
  97.     /**  
  98.      * 发送密码到邮箱  
  99.      * @param user  
  100.      *          用户对象  
  101.      * @param password  
  102.      *          新密码  
  103.      * @param email  
  104.      *          收密码的邮箱号码  
  105.      */  
  106.     public static void sendEmail(User user,String password,String email){   
  107.         try {   
  108.             InputStream in = UserFactory.class.getResourceAsStream("/spring-jpa.properties");   
  109.             Properties p = new Properties();   
  110.             if (in != null) {   
  111.                 p.load(in);   
  112.             }   
  113.             String authuser=p.getProperty("mail.username");  //发送人用户名   
  114.             String authpwd= p.getProperty("mail.password");  //邮箱密码   
  115.             String host = p.getProperty("mail.host");        //smtp服务器名字   
  116.             String port = p.getProperty("mail.port");        //端口号   
  117.             String from = p.getProperty("mail.from");        //来自哪里   
  118.             String title = p.getProperty("ucenter.title");   //邮件标题,替换发送的邮箱名字   
  119.             String url = p.getProperty("ucenter.url");       //链接地址   
  120.                
  121.             Properties sessionPro = new Properties();   
  122.             sessionPro.put("mail.smtp.host", host);   
  123.             sessionPro.put("mail.smtp.port",port);   
  124.             sessionPro.put("mail.smtp.auth","true");   
  125.                
  126.             // 根据邮件会话属性和密码验证器构造一个发送邮件的session    
  127.             Session sendMailSession = Session.getDefaultInstance(sessionPro,new MyAuthenticator(authuser,authpwd));   
  128.                
  129.             // 根据session创建一个邮件消息       
  130.             Message mailMessage = new MimeMessage(sendMailSession);   
  131.                
  132.             // 创建邮件发送者地址       
  133.             Address fromAddress = new InternetAddress(from);   
  134.                
  135.             // 创建邮件的接收者地址,并设置到邮件消息中       
  136.             Address toAddress = new InternetAddress(email);   
  137.                
  138.             // 设置邮件消息的发送者    
  139.             mailMessage.setFrom(fromAddress);   
  140.                
  141.             mailMessage.setFileName(title);   
  142.                
  143.             mailMessage.setRecipient(Message.RecipientType.TO,toAddress);   
  144.             // 设置邮件消息发送的时间       
  145.             mailMessage.setSentDate(new Date());    
  146.             mailMessage.setSubject("找回密码");   
  147.                
  148.             // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象       
  149.             Multipart mainPart = new MimeMultipart();   
  150.             // 创建一个包含HTML内容的MimeBodyPart       
  151.             BodyPart html = new MimeBodyPart();   
  152.                
  153.             //设置邮件内容   
  154.             Map<String,String> props=new HashMap<String,String>();   
  155.             props.put("title", title);   
  156.             props.put("url", url);   
  157.             props.put("userName",user.getUserName());   
  158.             props.put("password",password);   
  159.                
  160.             //读取邮件内容   
  161.             String result=emailTemplate(props,"mail/findpwd_mail.vm");;   
  162.                
  163.             html.setContent(result,"text/html;charset=utf-8");   
  164.             mainPart.addBodyPart(html);   
  165.                
  166.              // 将MiniMultipart对象设置为邮件内容       
  167.             mailMessage.setContent(mainPart);   
  168.                
  169.             //保存要发送的邮件   
  170.             mailMessage.saveChanges();   
  171.                
  172.             //发送邮件   
  173.             Transport.send(mailMessage);   
  174.                
  175.             StringBuilder sb = new StringBuilder();   
  176.             sb.append("系统已经把密码发送到您的邮箱,请点击");   
  177.             sb.append("<font color='red'><a target='_blank' href='http://mail.");   
  178.             sb.append(email.substring(email.indexOf("@")+1,email.length())+"'");   
  179.             sb.append(">");   
  180.             sb.append("这里登录邮箱");   
  181.             sb.append("</a></font>");   
  182.             sb.append("查收!");   
  183.             System.out.println(sb.toString());   
  184.             addError(sb.toString());   
  185.         } catch (Exception ex) {   
  186.             addError("网络连接失败!检查您的网络是否正常!");   
  187.         }   
  188.                    
  189.     }   
  190.        
  191.     /**  
  192.      * 读取邮件模板  
  193.      * @param data  
  194.      * @return  
  195.      */  
  196.     private static String emailTemplate(Map<String, String> data,String filePath) {   
  197.         String result = null;   
  198.         try {   
  199.             VelocityEngine velocity = new VelocityEngine();   
  200.             Properties properties = new Properties();   
  201.             properties.setProperty("resource.loader""class");   
  202.             properties.setProperty("class.resource.loader.class""org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");   
  203.             velocity.init(properties);   
  204.             Template t = velocity.getTemplate(filePath, "utf-8");   
  205.             VelocityContext context = new VelocityContext();   
  206.             for (Map.Entry<String, String> entry : data.entrySet()) {   
  207.                 context.put(entry.getKey(), entry.getValue());   
  208.             }   
  209.             StringWriter writer = new StringWriter();   
  210.             t.merge(context, writer);   
  211.             result = writer.toString();   
  212.             writer.close();   
  213.         } catch (Exception e1) {   
  214.             e1.printStackTrace();   
  215.         }   
  216.         return result;   
  217.     }      
  218.            
  219.   
  220.     /**  
  221.      * 检查验证码  
  222.      * @param verifycodeBeValid   
  223.      *          验证码是否正确  
  224.      * @param verifycode  
  225.      *          验证码  
  226.      * @return  
  227.      */  
  228.     public static boolean checkVerifycode(String verifycode) {   
  229.         boolean verifycodeBeValid = false;   
  230.         String rand_image = null;   
  231.         try {   
  232.             rand_image = (String) ActionContext.getContext().getSession().get("rand_image");   
  233.             if (verifycode.equals(rand_image)) {   
  234.                 verifycodeBeValid = true;   
  235.             }   
  236.         } catch (Exception ex) {   
  237.             verifycodeBeValid = false;   
  238.         }   
  239.         return verifycodeBeValid;   
  240.     }      
  241.        
  242.         
  243.     /***  
  244.      * 获取URI的路径,如路径为http://www.cun365.com/passport/center.action?ssid=1, 得到的值为"/passport.center.action"  
  245.      * @param request  
  246.      * @return  
  247.      */  
  248.     public static String getRequestURI(HttpServletRequest request){        
  249.         return request.getRequestURI();   
  250.     }   
  251.     /**  
  252.      * 获取完整请求路径(含内容路径及请求参数)  
  253.      * @param request  
  254.      * @return  
  255.      */  
  256.     public static String getRequestURIWithParam(HttpServletRequest request){        
  257.         return getRequestURI(request) + (request.getQueryString() == null ? "" : "?"+ request.getQueryString());   
  258.     }   
  259.        
  260.     /**  
  261.      * 添加cookie  
  262.      * @param response  
  263.      * @param name cookie的名称  
  264.      * @param value cookie的值  
  265.      * @param maxAge cookie存放的时间(以秒为单位,假如存放三天,即3*24*60*60; 如果值为0,cookie将随浏览器关闭而清除)  
  266.      */  
  267.     public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) {           
  268.         Cookie cookie = new Cookie(name, value);   
  269.         cookie.setPath("/");   
  270.         if (maxAge>0) cookie.setMaxAge(maxAge);   
  271.         response.addCookie(cookie);   
  272.     }   
  273.        
  274.     /**  
  275.      * 获取cookie的值  
  276.      * @param request  
  277.      * @param name cookie的名称  
  278.      * @return  
  279.      */  
  280.     public static String getCookieByName(HttpServletRequest request, String name) {   
  281.         Map<String, Cookie> cookieMap = WebUtil.readCookieMap(request);   
  282.         if(cookieMap.containsKey(name)){   
  283.             Cookie cookie = (Cookie)cookieMap.get(name);   
  284.             return cookie.getValue();   
  285.         }else{   
  286.             return null;   
  287.         }   
  288.     }   
  289.        
  290.     protected static Map<String, Cookie> readCookieMap(HttpServletRequest request) {   
  291.         Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();   
  292.         Cookie[] cookies = request.getCookies();   
  293.         if (null != cookies) {   
  294.             for (int i = 0; i < cookies.length; i++) {   
  295.                 cookieMap.put(cookies[i].getName(), cookies[i]);   
  296.             }   
  297.         }   
  298.         return cookieMap;   
  299.     }   
  300.        
  301.     /**  
  302.      * 去除html代码  
  303.      * @param inputString  
  304.      * @return  
  305.      */  
  306.     public static String HtmltoText(String inputString) {   
  307.         String htmlStr = inputString; //含html标签的字符串   
  308.         String textStr ="";   
  309.         java.util.regex.Pattern p_script;   
  310.         java.util.regex.Matcher m_script;   
  311.         java.util.regex.Pattern p_style;   
  312.         java.util.regex.Matcher m_style;   
  313.         java.util.regex.Pattern p_html;   
  314.         java.util.regex.Matcher m_html;             
  315.         java.util.regex.Pattern p_ba;   
  316.         java.util.regex.Matcher m_ba;   
  317.            
  318.         try {   
  319.             String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"//定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script> }   
  320.             String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"//定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style> }   
  321.             String regEx_html = "<[^>]+>"//定义HTML标签的正则表达式   
  322.             String patternStr = "\\s+";   
  323.                
  324.             p_script = Pattern.compile(regEx_script,Pattern.CASE_INSENSITIVE);   
  325.             m_script = p_script.matcher(htmlStr);   
  326.             htmlStr = m_script.replaceAll(""); //过滤script标签   
  327.   
  328.             p_style = Pattern.compile(regEx_style,Pattern.CASE_INSENSITIVE);   
  329.             m_style = p_style.matcher(htmlStr);   
  330.             htmlStr = m_style.replaceAll(""); //过滤style标签   
  331.             
  332.             p_html = Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE);   
  333.             m_html = p_html.matcher(htmlStr);   
  334.             htmlStr = m_html.replaceAll(""); //过滤html标签   
  335.                
  336.             p_ba = Pattern.compile(patternStr,Pattern.CASE_INSENSITIVE);   
  337.             m_ba = p_ba.matcher(htmlStr);   
  338.             htmlStr = m_ba.replaceAll(""); //过滤空格   
  339.             
  340.          textStr = htmlStr;   
  341.             
  342.         }catch(Exception e) {   
  343.                     System.err.println("Html2Text: " + e.getMessage());   
  344.         }             
  345.         return textStr;//返回文本字符串   
  346.      }       
  347.        
  348.     /**  
  349.      * 获取项目的 basePath 路径,例如:http://uc.cun365.com/  
  350.      * @return  
  351.      */  
  352.     public static String getBasePath(HttpServletRequest request){   
  353.         String path = request.getContextPath();    
  354.         String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";   
  355.         return basePath;   
  356.     }   
  357.        
  358.     public static String getBasePath(HttpServletRequest request,boolean flag){   
  359.         String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/";   
  360.         return basePath;   
  361.     }       
  362.        
  363.     /**  
  364.      * 清除缓存  
  365.      */  
  366.     @Deprecated  
  367.     public static void setBuffer(HttpServletResponse response){   
  368.             response.setHeader("Pragma","No-cache");    
  369.             response.setHeader("Cache-Control","no-cache");    
  370.             response.setDateHeader("Expires"0);    
  371.             try {   
  372.                 response.flushBuffer();   
  373.             } catch (IOException e) {   
  374.                 System.out.println(new Date()+":清除 缓存时 出现异常");   
  375.             }              
  376.     }   
  377.            
  378.     public static String getUserName() {   
  379.         return userName;   
  380.     }   
  381.   
  382.     public static void setUserName(String userName) {   
  383.         WebUtil.userName = userName;   
  384.     }   
  385.   
  386.     public static String getDirectoryId() {   
  387.         return directoryId;   
  388.     }   
  389.   
  390.     public static void setDirectoryId(String directoryId) {   
  391.         WebUtil.directoryId = directoryId;   
  392.     }   
  393. }  
package com.transnal.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.regex.Pattern;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sxinfo.profile.Profile;
import net.sxinfo.profile.ProfileInfo;
import net.sxinfo.user.User;
import net.sxinfo.user.UserFactory;  //这个东西我不说,你也知道了,就是一个读取 资源文件的 类。

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

import com.opensymphony.xwork2.ActionContext;

/**
 * 所有共用的方法都被调到这个类里
 * 
 * @author RenWeigang
 * 
 * @since 2010.08.02
 * 
 * @version 1.0
 *
 */
public class WebUtil {
	
	private static String directoryId;
	private static String userName;
	
	
	/**
	 * 設置提示信息(僅限request請求輸出)
	 * @param paramString
	 */
	public static void addError(String paramString){
		ServletActionContext.getRequest().setAttribute("msg",paramString);
	}
	
	/**
	 * URI跳转
	 */
	public static void redirectService(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String s_m = request.getParameter("success_msg");
		if(StringUtils.isNotBlank(s_m) && (s_m.equals("%E6%88%90%E5%8A%9F") || s_m.equals("成功"))){
			HttpServletResponse response = ServletActionContext.getResponse();
			StringBuilder sb = new StringBuilder("修改成功!");
			String paramService = request.getParameter("service");
			if(StringUtils.isNotBlank(paramService) && (paramService.startsWith("http") || paramService.startsWith("ftp"))){
				if(paramService.startsWith("http"))
				{
					paramService ="http://"+paramService.replaceAll("^http\\:\\/+","");
				}
				if(paramService.startsWith("ftp")){
					paramService ="ftp://"+paramService.replaceAll("^ftp\\:\\/+","");
				}
				sb.append("3秒后跳转到您原始的页面!如没有相应,请点击<font color='red'><a href='");
				sb.append(paramService);
				sb.append("' target='_blank'>");
				sb.append("这里");
				sb.append("</a>");
				sb.append("</font>");
				String url = getBasePath(request)+"logout?url="+paramService;
				response.setHeader("Refresh","3;URL="+url);
			}
			ServletActionContext.getRequest().setAttribute("msg",sb.toString());	
		}
	}
	
	/**
	 * 发送密码到邮箱
	 * @param user
	 * 			用户对象
	 * @param password
	 * 			新密码
	 * @param email
	 * 			收密码的邮箱号码
	 */
	public static void sendEmail(User user,String password,String email){
		try {
			InputStream in = UserFactory.class.getResourceAsStream("/spring-jpa.properties");
			Properties p = new Properties();
			if (in != null) {
				p.load(in);
			}
			String authuser=p.getProperty("mail.username");  //发送人用户名
			String authpwd= p.getProperty("mail.password");  //邮箱密码
			String host = p.getProperty("mail.host");        //smtp服务器名字
			String port = p.getProperty("mail.port");		 //端口号
			String from = p.getProperty("mail.from");        //来自哪里
			String title = p.getProperty("ucenter.title");   //邮件标题,替换发送的邮箱名字
			String url = p.getProperty("ucenter.url");       //链接地址
			
			Properties sessionPro = new Properties();
			sessionPro.put("mail.smtp.host", host);
			sessionPro.put("mail.smtp.port",port);
			sessionPro.put("mail.smtp.auth","true");
			
			// 根据邮件会话属性和密码验证器构造一个发送邮件的session 
			Session sendMailSession = Session.getDefaultInstance(sessionPro,new MyAuthenticator(authuser,authpwd));
			
			// 根据session创建一个邮件消息    
			Message mailMessage = new MimeMessage(sendMailSession);
			
			// 创建邮件发送者地址    
			Address fromAddress = new InternetAddress(from);
			
			// 创建邮件的接收者地址,并设置到邮件消息中    
			Address toAddress = new InternetAddress(email);
			
			// 设置邮件消息的发送者 
			mailMessage.setFrom(fromAddress);
			
			mailMessage.setFileName(title);
			
			mailMessage.setRecipient(Message.RecipientType.TO,toAddress);
			// 设置邮件消息发送的时间    
			mailMessage.setSentDate(new Date()); 
			mailMessage.setSubject("找回密码");
			
			// MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象    
			Multipart mainPart = new MimeMultipart();
			// 创建一个包含HTML内容的MimeBodyPart    
			BodyPart html = new MimeBodyPart();
			
			//设置邮件内容
			Map<String,String> props=new HashMap<String,String>();
			props.put("title", title);
			props.put("url", url);
			props.put("userName",user.getUserName());
			props.put("password",password);
			
			//读取邮件内容
			String result=emailTemplate(props,"mail/findpwd_mail.vm");;
            
			html.setContent(result,"text/html;charset=utf-8");
			mainPart.addBodyPart(html);
			
			 // 将MiniMultipart对象设置为邮件内容    
			mailMessage.setContent(mainPart);
			
     		//保存要发送的邮件
		    mailMessage.saveChanges();
            
			//发送邮件
			Transport.send(mailMessage);
			
			StringBuilder sb = new StringBuilder();
			sb.append("系统已经把密码发送到您的邮箱,请点击");
			sb.append("<font color='red'><a target='_blank' href='http://mail.");
			sb.append(email.substring(email.indexOf("@")+1,email.length())+"'");
			sb.append(">");
			sb.append("这里登录邮箱");
			sb.append("</a></font>");
			sb.append("查收!");
			System.out.println(sb.toString());
			addError(sb.toString());
		} catch (Exception ex) {
			addError("网络连接失败!检查您的网络是否正常!");
		}
				
	}
	
	/**
	 * 读取邮件模板
	 * @param data
	 * @return
	 */
	private static String emailTemplate(Map<String, String> data,String filePath) {
		String result = null;
		try {
			VelocityEngine velocity = new VelocityEngine();
			Properties properties = new Properties();
			properties.setProperty("resource.loader", "class");
			properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
			velocity.init(properties);
			Template t = velocity.getTemplate(filePath, "utf-8");
			VelocityContext context = new VelocityContext();
			for (Map.Entry<String, String> entry : data.entrySet()) {
				context.put(entry.getKey(), entry.getValue());
			}
			StringWriter writer = new StringWriter();
			t.merge(context, writer);
			result = writer.toString();
			writer.close();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return result;
	}	
		

	/**
	 * 检查验证码
	 * @param verifycodeBeValid 
	 * 			验证码是否正确
	 * @param verifycode
	 * 			验证码
	 * @return
	 */
	public static boolean checkVerifycode(String verifycode) {
		boolean verifycodeBeValid = false;
		String rand_image = null;
		try {
			rand_image = (String) ActionContext.getContext().getSession().get("rand_image");
			if (verifycode.equals(rand_image)) {
				verifycodeBeValid = true;
			}
		} catch (Exception ex) {
			verifycodeBeValid = false;
		}
		return verifycodeBeValid;
	}	
	
	 
    /***
     * 获取URI的路径,如路径为http://www.cun365.com/passport/center.action?ssid=1, 得到的值为"/passport.center.action"
     * @param request
     * @return
     */
    public static String getRequestURI(HttpServletRequest request){     
        return request.getRequestURI();
    }
    /**
     * 获取完整请求路径(含内容路径及请求参数)
     * @param request
     * @return
     */
    public static String getRequestURIWithParam(HttpServletRequest request){     
        return getRequestURI(request) + (request.getQueryString() == null ? "" : "?"+ request.getQueryString());
    }
    
    /**
     * 添加cookie
     * @param response
     * @param name cookie的名称
     * @param value cookie的值
     * @param maxAge cookie存放的时间(以秒为单位,假如存放三天,即3*24*60*60; 如果值为0,cookie将随浏览器关闭而清除)
     */
    public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) {        
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        if (maxAge>0) cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }
    
    /**
     * 获取cookie的值
     * @param request
     * @param name cookie的名称
     * @return
     */
    public static String getCookieByName(HttpServletRequest request, String name) {
    	Map<String, Cookie> cookieMap = WebUtil.readCookieMap(request);
        if(cookieMap.containsKey(name)){
            Cookie cookie = (Cookie)cookieMap.get(name);
            return cookie.getValue();
        }else{
            return null;
        }
    }
    
    protected static Map<String, Cookie> readCookieMap(HttpServletRequest request) {
        Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (int i = 0; i < cookies.length; i++) {
                cookieMap.put(cookies[i].getName(), cookies[i]);
            }
        }
        return cookieMap;
    }
    
    /**
     * 去除html代码
     * @param inputString
     * @return
     */
    public static String HtmltoText(String inputString) {
        String htmlStr = inputString; //含html标签的字符串
        String textStr ="";
        java.util.regex.Pattern p_script;
        java.util.regex.Matcher m_script;
        java.util.regex.Pattern p_style;
        java.util.regex.Matcher m_style;
        java.util.regex.Pattern p_html;
        java.util.regex.Matcher m_html;          
        java.util.regex.Pattern p_ba;
        java.util.regex.Matcher m_ba;
        
        try {
            String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; //定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script> }
            String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; //定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style> }
            String regEx_html = "<[^>]+>"; //定义HTML标签的正则表达式
            String patternStr = "\\s+";
            
            p_script = Pattern.compile(regEx_script,Pattern.CASE_INSENSITIVE);
            m_script = p_script.matcher(htmlStr);
            htmlStr = m_script.replaceAll(""); //过滤script标签

            p_style = Pattern.compile(regEx_style,Pattern.CASE_INSENSITIVE);
            m_style = p_style.matcher(htmlStr);
            htmlStr = m_style.replaceAll(""); //过滤style标签
         
            p_html = Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE);
            m_html = p_html.matcher(htmlStr);
            htmlStr = m_html.replaceAll(""); //过滤html标签
            
            p_ba = Pattern.compile(patternStr,Pattern.CASE_INSENSITIVE);
            m_ba = p_ba.matcher(htmlStr);
            htmlStr = m_ba.replaceAll(""); //过滤空格
         
         textStr = htmlStr;
         
        }catch(Exception e) {
                    System.err.println("Html2Text: " + e.getMessage());
        }          
        return textStr;//返回文本字符串
     }    
	
    /**
     * 获取项目的 basePath 路径,例如:http://uc.cun365.com/
     * @return
     */
    public static String getBasePath(HttpServletRequest request){
    	String path = request.getContextPath(); 
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
		return basePath;
    }
    
    public static String getBasePath(HttpServletRequest request,boolean flag){
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/";
		return basePath;
    }    
    
    /**
     * 清除缓存
     */
    @Deprecated
    public static void setBuffer(HttpServletResponse response){
        	response.setHeader("Pragma","No-cache"); 
        	response.setHeader("Cache-Control","no-cache"); 
        	response.setDateHeader("Expires", 0); 
        	try {
    			response.flushBuffer();
    		} catch (IOException e) {
    			System.out.println(new Date()+":清除 缓存时 出现异常");
    		}     		
    }
        
	public static String getUserName() {
		return userName;
	}

	public static void setUserName(String userName) {
		WebUtil.userName = userName;
	}

	public static String getDirectoryId() {
		return directoryId;
	}

	public static void setDirectoryId(String directoryId) {
		WebUtil.directoryId = directoryId;
	}
}



不好意思,忘记说 所读取的 资源文件了,
spring-jpa.properties
中的内容如下

Xml代码 复制代码
  1. ###部署环境   
  2. jee=${jee}   
  3. ucenter.title=伟业中国用户中心   
  4. ucenter.url=http://www.xxx.com   
  5.   
  6. mailmail.host=mail.xxx.com   
  7. mail.username=xxx  
  8. mail.password=xxx  
  9. mail.from=renwg@xxx.com   
  10. mail.port=25  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值