Commit 22619666 by manxiaoqiang

大后台系统用户

parent feed76f0
<component name="libraryTable">
<library name="Maven: org.hibernate:hibernate-core:4.2.1.Final">
<CLASSES>
<root url="jar://E:/apache-maven-3.1.0/dependcies2/org/hibernate/hibernate-core/4.2.1.Final/hibernate-core-4.2.1.Final.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://E:/apache-maven-3.1.0/dependcies2/org/hibernate/hibernate-core/4.2.1.Final/hibernate-core-4.2.1.Final-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://E:/apache-maven-3.1.0/dependcies2/org/hibernate/hibernate-core/4.2.1.Final/hibernate-core-4.2.1.Final-sources.jar!/" />
</SOURCES>
</library>
</component>
\ No newline at end of file
<component name="libraryTable">
<library name="Maven: org.jboss.logging:jboss-logging:3.1.1.GA">
<CLASSES>
<root url="jar://E:/apache-maven-3.1.0/dependcies2/org/jboss/logging/jboss-logging/3.1.1.GA/jboss-logging-3.1.1.GA.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://E:/apache-maven-3.1.0/dependcies2/org/jboss/logging/jboss-logging/3.1.1.GA/jboss-logging-3.1.1.GA-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://E:/apache-maven-3.1.0/dependcies2/org/jboss/logging/jboss-logging/3.1.1.GA/jboss-logging-3.1.1.GA-sources.jar!/" />
</SOURCES>
</library>
</component>
\ No newline at end of file
...@@ -41,6 +41,9 @@ ...@@ -41,6 +41,9 @@
<default.datasource.username>root</default.datasource.username> <default.datasource.username>root</default.datasource.username>
<default.datasource.password>reyun123</default.datasource.password> <default.datasource.password>reyun123</default.datasource.password>
<office.url>jdbc:mysql://192.168.2.57:3306/office?characterEncoding=utf-8</office.url>
<office.username>root</office.username>
<office.password>reyun123</office.password>
<mail.host>smtp.exmail.qq.com</mail.host> <mail.host>smtp.exmail.qq.com</mail.host>
<mail.username>service1@reyun.com</mail.username> <mail.username>service1@reyun.com</mail.username>
......
...@@ -10,6 +10,7 @@ import org.slf4j.LoggerFactory; ...@@ -10,6 +10,7 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import util.CipherUtil;
import util.ResultModel; import util.ResultModel;
import javax.servlet.http.Cookie; import javax.servlet.http.Cookie;
...@@ -28,7 +29,7 @@ public class LoginController { ...@@ -28,7 +29,7 @@ public class LoginController {
@RequestMapping(value = "login", method = RequestMethod.GET) @RequestMapping(value = "login", method = RequestMethod.GET)
@ResponseBody @ResponseBody
public ResultModel login(HttpServletResponse response, @RequestParam String email, @RequestParam String password) { public ResultModel login(HttpServletResponse response, @RequestParam String email, @RequestParam String password) {
User user = userRepository.login(email, password); User user = userRepository.login(email, CipherUtil.generatePassword(password));
if(null != user){ if(null != user){
Cookie cookie = new Cookie("TOKEN", user.getId().toString()); Cookie cookie = new Cookie("TOKEN", user.getId().toString());
cookie.setPath("/"); cookie.setPath("/");
...@@ -36,9 +37,17 @@ public class LoginController { ...@@ -36,9 +37,17 @@ public class LoginController {
response.addCookie(cookie); response.addCookie(cookie);
return ResultModel.OK(true); return ResultModel.OK(true);
} }
return ResultModel.OK(false); return ResultModel.OK(false);
} }
@RequestMapping(value = "login/check", method = RequestMethod.GET)
@ResponseBody
public ResultModel loginCheck(HttpServletResponse response, @RequestParam String email) {
User user = userRepository.login(email);
if(null != user){
return ResultModel.OK(true);
}
return ResultModel.OK(false);
}
} }
...@@ -3,14 +3,14 @@ package common.controller; ...@@ -3,14 +3,14 @@ package common.controller;
import common.model.Menu; import common.model.Menu;
import common.model.User; import common.model.User;
import common.service.MenuService; import common.service.MenuService;
import common.service.UserService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import security.annotation.CurrentAccount; import security.annotation.CurrentAccount;
import util.ResultModel; import util.ResultModel;
import javax.servlet.http.HttpServletResponse;
import java.util.List; import java.util.List;
/** /**
...@@ -20,13 +20,69 @@ import java.util.List; ...@@ -20,13 +20,69 @@ import java.util.List;
@RequestMapping("user") @RequestMapping("user")
public class UserController { public class UserController {
@Autowired @Autowired
private User menuService; private UserService userService;
@RequestMapping(value = "find", method = RequestMethod.GET) @RequestMapping(value = "/create", method = RequestMethod.POST)
@ResponseBody @ResponseBody
public ResultModel findAll(@CurrentAccount User loginAccount) { public ResultModel create(@CurrentAccount User loginAccount, @RequestBody User resource) {
List<Menu> menus = menuService.listAll(); userService.create(loginAccount, resource);
return ResultModel.OK(menus); return ResultModel.OK();
}
@RequestMapping(value = "/update", method = RequestMethod.PUT)
@ResponseBody
public ResultModel update(@CurrentAccount User loginAccount, @RequestBody User resource) {
userService.create(loginAccount, resource);
return ResultModel.OK();
}
@RequestMapping(value = "/find", method = RequestMethod.GET)
@ResponseBody
public ResultModel find(@CurrentAccount User loginAccount, @RequestBody User resource) {
userService.create(loginAccount, resource);
return ResultModel.OK();
}
@RequestMapping(value = "/delete", method = RequestMethod.GET)
@ResponseBody
public ResultModel delete(@CurrentAccount User loginAccount, @RequestBody User resource) {
userService.create(loginAccount, resource);
return ResultModel.OK();
}
@RequestMapping(value = "/update/{id}", method = RequestMethod.PUT)
@ResponseBody
public ResultModel updateName(@CurrentAccount User loginAccount, @RequestParam String name, @PathVariable Long id) {
userService.updateName(loginAccount, id, name);
return ResultModel.OK();
}
@RequestMapping(value = "/update/{id}/pwd", method = RequestMethod.PUT)
@ResponseBody
public ResultModel updatePwd(@CurrentAccount User loginAccount, @RequestParam String pwd, @PathVariable Long id) {
userService.updatePwd(loginAccount, id, pwd);
return ResultModel.OK();
}
@RequestMapping(value = "/update/pwd", method = RequestMethod.PUT)
@ResponseBody
public ResultModel updatePwd(@RequestParam String email, @RequestParam String pwd) {
return ResultModel.OK(userService.updatePwd(email, pwd));
}
@RequestMapping(value = "forget/", method = RequestMethod.GET)
@ResponseBody
public ResultModel sengCode(@RequestParam String email) {
return ResultModel.OK(userService.sendCode(email));
}
@RequestMapping(value = "valid/code", method = RequestMethod.GET)
@ResponseBody
public ResultModel validCode(@RequestParam String email, @RequestParam String code) {
userService.validCode(email, code);
return ResultModel.OK();
} }
} }
...@@ -13,8 +13,8 @@ public class Auth { ...@@ -13,8 +13,8 @@ public class Auth {
private Long user; private Long user;
private String auth; private String auth;
private String modifyAccountName; private Long modifyAccount;
private String createAccountName; private Long createAccount;
private Date modifyTime; private Date modifyTime;
private Date createTime; private Date createTime;
private Boolean delFlag; private Boolean delFlag;
...@@ -45,20 +45,20 @@ public class Auth { ...@@ -45,20 +45,20 @@ public class Auth {
this.auth = auth; this.auth = auth;
} }
public String getModifyAccountName() { public Long getModifyAccount() {
return modifyAccountName; return modifyAccount;
} }
public void setModifyAccountName(String modifyAccountName) { public void setModifyAccount(Long modifyAccount) {
this.modifyAccountName = modifyAccountName; this.modifyAccount = modifyAccount;
} }
public String getCreateAccountName() { public Long getCreateAccount() {
return createAccountName; return createAccount;
} }
public void setCreateAccountName(String createAccountName) { public void setCreateAccount(Long createAccount) {
this.createAccountName = createAccountName; this.createAccount = createAccount;
} }
public Date getModifyTime() { public Date getModifyTime() {
...@@ -91,8 +91,8 @@ public class Auth { ...@@ -91,8 +91,8 @@ public class Auth {
"id=" + id + "id=" + id +
", user=" + user + ", user=" + user +
", auth='" + auth + '\'' + ", auth='" + auth + '\'' +
", modifyAccountName='" + modifyAccountName + '\'' + ", modifyAccount=" + modifyAccount +
", createAccountName='" + createAccountName + '\'' + ", createAccount=" + createAccount +
", modifyTime=" + modifyTime + ", modifyTime=" + modifyTime +
", createTime=" + createTime + ", createTime=" + createTime +
", delFlag=" + delFlag + ", delFlag=" + delFlag +
......
package common.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.util.Date;
@Entity
public class Code {
private Long id;
private String email;
private String code;
private Date createTime;
@Id
@GeneratedValue
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}
package common.model;
import java.util.List;
public class Email {
private boolean isHaveMultPaths;
private String subject;
private String contents;
private List<String> userEmailAddress;
private String[] multiPaths;
public boolean isHaveMultPaths() {
return isHaveMultPaths;
}
public void setHaveMultPaths(boolean isHaveMultPaths) {
this.isHaveMultPaths = isHaveMultPaths;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContents() {
return contents;
}
public void setContents(String contents) {
this.contents = contents;
}
public List<String> getUserEmailAddress() {
return userEmailAddress;
}
public void setUserEmailAddress(List<String> userEmailAddress) {
this.userEmailAddress = userEmailAddress;
}
public String[] getMultiPaths() {
return multiPaths;
}
public void setMultiPaths(String[] multiPaths) {
this.multiPaths = multiPaths;
}
}
...@@ -16,9 +16,10 @@ public class User { ...@@ -16,9 +16,10 @@ public class User {
private String name; private String name;
private Long role; private Long role;
private Long roleType; private Long roleType;
private String auth;
private String modifyAccountName; private Long modifyAccount;
private String createAccountName; private Long createAccount;
private Date modifyTime; private Date modifyTime;
private Date createTime; private Date createTime;
private Boolean delFlag; private Boolean delFlag;
...@@ -74,20 +75,20 @@ public class User { ...@@ -74,20 +75,20 @@ public class User {
this.roleType = roleType; this.roleType = roleType;
} }
public String getModifyAccountName() { public Long getModifyAccount() {
return modifyAccountName; return modifyAccount;
} }
public void setModifyAccountName(String modifyAccountName) { public void setModifyAccount(Long modifyAccount) {
this.modifyAccountName = modifyAccountName; this.modifyAccount = modifyAccount;
} }
public String getCreateAccountName() { public Long getCreateAccount() {
return createAccountName; return createAccount;
} }
public void setCreateAccountName(String createAccountName) { public void setCreateAccount(Long createAccount) {
this.createAccountName = createAccountName; this.createAccount = createAccount;
} }
public Date getModifyTime() { public Date getModifyTime() {
...@@ -114,6 +115,15 @@ public class User { ...@@ -114,6 +115,15 @@ public class User {
this.delFlag = delFlag; this.delFlag = delFlag;
} }
@Transient
public String getAuth() {
return auth;
}
public void setAuth(String auth) {
this.auth = auth;
}
@Override @Override
public String toString() { public String toString() {
return "User{" + return "User{" +
...@@ -123,8 +133,9 @@ public class User { ...@@ -123,8 +133,9 @@ public class User {
", name='" + name + '\'' + ", name='" + name + '\'' +
", role=" + role + ", role=" + role +
", roleType=" + roleType + ", roleType=" + roleType +
", modifyAccountName='" + modifyAccountName + '\'' + ", auth='" + auth + '\'' +
", createAccountName='" + createAccountName + '\'' + ", modifyAccount=" + modifyAccount +
", createAccount=" + createAccount +
", modifyTime=" + modifyTime + ", modifyTime=" + modifyTime +
", createTime=" + createTime + ", createTime=" + createTime +
", delFlag=" + delFlag + ", delFlag=" + delFlag +
......
package common.repository;
import common.model.Auth;
import common.model.Menu;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Transactional
public interface AuthRepository extends JpaRepository<Auth, Long> {
}
package common.repository;
import common.model.Auth;
import common.model.Code;
import common.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
@Transactional
public interface CodeRepository extends JpaRepository<Code, Long> {
@Query(value="select * from code where email = ?1 and create_time > ?2 group by id desc limit 1",nativeQuery=true)
Code findValid(String email, Date date);
}
package common.repository;
import common.model.RoleType;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public interface RoleTypeRepository extends JpaRepository<RoleType, Long> {
}
...@@ -11,9 +11,16 @@ import java.util.List; ...@@ -11,9 +11,16 @@ import java.util.List;
@Transactional @Transactional
public interface UserRepository extends JpaRepository<User, Long> { public interface UserRepository extends JpaRepository<User, Long> {
@Query(value="select * from User where email = ?1 and password = ?2",nativeQuery=true) @Query(value="select * from user where email = ?1 and password = ?2 and del_flag is not true",nativeQuery=true)
User login(String email, String pwd); User login(String email, String pwd);
@Query(value="select * from User where id = ?1",nativeQuery=true) @Query(value="select * from user where role = ?1 and del_flag is not true",nativeQuery=true)
User findOne(Long id); List<User> findOneDepartment(Long role);
@Query(value="select * from user where del_flag is not true",nativeQuery=true)
List<User> findAll();
@Query(value="select * from user where email = ?1 and del_flag is not true",nativeQuery=true)
User login(String email);
} }
...@@ -11,4 +11,20 @@ import java.util.List; ...@@ -11,4 +11,20 @@ import java.util.List;
public interface UserService { public interface UserService {
User create(User login, User resource); User create(User login, User resource);
User update(User login, User resource);
List<User> find(User login);
User delete(User login, Long id);
User updateName(User login, Long id, String name);
User updatePwd(User login, Long id, String pwd);
User updatePwd(String email, String pwd);
Boolean sendCode(String email);
String validCode(String email, String code);
} }
package common.service.impl; package common.service.impl;
import common.model.Menu; import common.model.Auth;
import common.model.Code;
import common.model.User; import common.model.User;
import common.repository.MenuRepository; import common.repository.AuthRepository;
import common.service.MenuService; import common.repository.CodeRepository;
import common.repository.UserRepository;
import common.service.UserService; import common.service.UserService;
import dic.RoleEnum;
import dic.RoleTypeEnum;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import util.CharacterUtils;
import util.CipherUtil;
import util.MailUtils;
import java.util.ArrayList; import java.util.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** /**
* Created by mxq on 2017/12/21. * Created by mxq on 2017/12/21.
...@@ -20,16 +24,131 @@ import java.util.Map; ...@@ -20,16 +24,131 @@ import java.util.Map;
public class UserServiceImpl implements UserService { public class UserServiceImpl implements UserService {
@Autowired @Autowired
private MenuRepository menuRepository; private UserRepository userRepository;
@Autowired
private AuthRepository authRepository;
@Autowired
private CodeRepository codeRepository;
@Override @Override
public User create(User login, User resource) { public User create(User login, User resource) {
if(login.getRole().equals("")){
} else{ if(!login.getRole().equals(RoleEnum.MANAGER.getKey())){//非管理员只能创建本部门普通账户
resource.setRole(login.getRole());
resource.setRoleType(RoleTypeEnum.COMMON.getKey());
}
resource.setPassword(CipherUtil.generatePassword("111111"));
resource.setCreateTime(new Date());
resource.setCreateAccount(login.getId());
User save = userRepository.save(resource);
//auth
Auth auth = new Auth();
auth.setCreateTime(new Date());
auth.setCreateAccount(login.getId());
auth.setAuth(resource.getAuth());
auth.setUser(save.getId());
authRepository.save(auth);
return save;
}
@Override
public User update(User login, User resource) {
if(!login.getRole().equals(RoleEnum.MANAGER.getKey())){//非管理员只能创建本部门普通账户
resource.setRole(login.getRole());
resource.setRoleType(RoleTypeEnum.COMMON.getKey());
}
resource.setModifyTime(new Date());
resource.setModifyAccount(login.getId());
User save = userRepository.save(resource);
//auth
Auth auth = new Auth();
auth.setCreateTime(new Date());
auth.setCreateAccount(login.getId());
auth.setAuth(resource.getAuth());
auth.setUser(save.getId());
authRepository.save(auth);
return save;
}
@Override
public List<User> find(User login) {
List<User> userList = null;
if(!login.getRole().equals(RoleEnum.MANAGER.getKey())) {
userList = userRepository.findAll();
} else if(RoleTypeEnum.MANAGER.getKey().equals(login.getRoleType())){
userList = userRepository.findOneDepartment(login.getRole());
}
return userList;
}
@Override
public User delete(User login, Long id) {
User one = userRepository.findOne(id);
one.setModifyTime(new Date());
one.setModifyAccount(login.getId());
one.setDelFlag(true);
return userRepository.save(one);
}
@Override
public User updateName(User login, Long id, String name) {
User one = userRepository.findOne(id);
one.setName(name);
one.setModifyTime(new Date());
one.setModifyAccount(login.getId());
return userRepository.save(one);
}
@Override
public User updatePwd(User login, Long id, String pwd) {
User one = userRepository.findOne(id);
one.setPassword(CipherUtil.generatePassword(pwd));
one.setModifyTime(new Date());
one.setModifyAccount(login.getId());
return userRepository.save(one);
}
@Override
public User updatePwd(String email, String pwd) {
User user = userRepository.login(email);
user.setPassword(CipherUtil.generatePassword(pwd));
user.setModifyTime(new Date());
user.setModifyAccount(user.getId());
return userRepository.save(user);
}
@Override
public Boolean sendCode(String email) {
String code = CharacterUtils.getRandomString(4);
List<String> list = new ArrayList<>();
list.add(email);
try {
MailUtils.sendSimpleEmail("验证码", code,list);
} catch (Exception e) {
e.printStackTrace();
return false;
}
Code c = new Code();
c.setCreateTime(new Date());
c.setCode(code);
c.setEmail(email);
codeRepository.save(c);
return true;
}
@Override
public String validCode(String email, String code) {
Code valid = codeRepository.findValid(email, new Date());
if(null != valid){
boolean b = valid.getCode().equals(code);
if(b){
return "true";
}
return "false";
} }
return null; return "invalid";
} }
} }
package common; package dic;
/** /**
* Created by sunhao on 17/8/1. * Created by sunhao on 17/8/1.
......
package dic;
/**
* Created by sunhao on 17/8/1.
* desc:app平台类型
*/
public enum RoleTypeEnum {
MANAGER(1L,"主管账户"),
COMMON(2L,"普通账户");
private Long key;
private String value;
RoleTypeEnum(Long key, String value) {
this.key = key;
this.value = value;
}
public Long getKey() {
return key;
}
public String getValue() {
return value;
}
}
package util;
import java.util.Random;
public class CharacterUtils {
public static String getRandomString(int length){
String str="abcdefABCDEF0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for(int i = 0 ; i < length; ++i){
int number = random.nextInt(22);//[0,62)
sb.append(str.charAt(number));
}
return sb.toString();
}
public static void main(String[] args){
System.out.println(getRandomString(4));
}
}
package util;
import org.apache.commons.codec.binary.Hex;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class CipherUtil {
// 十六进制下数字到字符的映射数组
private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
/** * 把inputString加密 */
public static String generatePassword(String inputString) {
return encodeByMD5(inputString);
}
/**
* 验证输入的密码是否正确
*
* @param password
* 加密后的密码
* @param inputString
* 输入的字符串
* @return 验证结果,TRUE:正确 FALSE:错误
*/
public static boolean validatePassword(String password, String inputString) {
if (password.equals(encodeByMD5(inputString))) {
return true;
} else {
return false;
}
}
/** 对字符串进行MD5加密 */
private static String encodeByMD5(String originString) {
if (originString != null) {
try {
// 创建具有指定算法名称的信息摘要
MessageDigest md = MessageDigest.getInstance("MD5");
// 使用指定的字节数组对摘要进行最后更新,然后完成摘要计算
byte[] results = md.digest(originString.getBytes());
// 将得到的字节数组变成字符串返回
String resultString = byteArrayToHexString(results);
return resultString.toUpperCase();
} catch (Exception ex) {
ex.printStackTrace();
}
}
return null;
}
/**
* 转换字节数组为十六进制字符串
*
* @param b 字节数组
* @return 十六进制字符串
*/
private static String byteArrayToHexString(byte[] b) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++) {
resultSb.append(byteToHexString(b[i]));
}
return resultSb.toString();
}
/** 将一个字节转化成十六进制形式的字符串 */
private static String byteToHexString(byte b) {
int n = b;
if (n < 0)
n = 256 + n;
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
/**
* 生成签名数据
*
* @param message
* 待加密的数据
* @param key
* 加密使用的key
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
*/
public static String hmacMd5Encode(String key, String message)
throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacMD5");
Mac mac = Mac.getInstance("HmacMD5");
mac.init(keySpec);
byte[] rawHmac = mac.doFinal(message.getBytes());
return Hex.encodeHexString(rawHmac);
}
public static void main(String[] args) {
// String str = generatePassword("123");
//account.getEmail()
// + resource.getName() + resource.getPlatform() + dateStr
/* System.out.println(generatePassword("demo@reyun.com金融产品iOS"+DateUtil
.getCurrentDateStr(DateUtil.C_TIME_PATTON_DEFAULT)).toLowerCase());*/
}
}
package util;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.ResourceBundle;
public class Constant {
public static String CURRENT_ACCOUNT = "$CURRENT_ACCOUNT$";
public static ResourceBundle mailBundle = ResourceBundle.getBundle("mail");
public static String mailHost = mailBundle.getString("mail.host");
public static String mailUsername = mailBundle.getString("mail.username");
public static String mailPassword = mailBundle.getString("mail.password");
public static String mailContentType = mailBundle.getString("mail.content_type");
public static String mailList = mailBundle.getString("mail.list");
public static List<String> mlist = Arrays.asList(mailList.split(","));
public static String mailValidTime = mailBundle.getString("mail.valid_time");
}
package util;
import common.model.Email;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.MultiPartEmail;
import org.apache.commons.mail.SimpleEmail;
import org.apache.commons.net.smtp.SMTPClient;
import org.apache.commons.net.smtp.SMTPReply;
import org.xbill.DNS.Lookup;
import org.xbill.DNS.Record;
import org.xbill.DNS.Type;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class MailUtils {
public static final String CONTENT_TYPE = Constant.mailContentType;
public static final String FROM_EMAIL_ADDRESS = Constant.mailUsername;
/**
* 简单的发邮件方式 邮件内容只有标题和邮件内容 支持多个用户批量发送
*
* @param subject
* 邮件标题
* @param contents
* 邮件内容
* @param userEmailAddress
* 收入人的邮件地址 为List形式
* @throws Exception
*/
public static void sendSimpleEmail(String subject, String contents, List<String> userEmailAddress) throws Exception {
SimpleEmail email = new SimpleEmail();
email.setHostName(Constant.mailHost);
email.setAuthentication(FROM_EMAIL_ADDRESS,Constant.mailPassword);
// 发送给多个人
for (int i = 0; i < userEmailAddress.size(); i++) {
email.addTo(userEmailAddress.get(i), userEmailAddress.get(i));
}
email.setFrom(FROM_EMAIL_ADDRESS, FROM_EMAIL_ADDRESS);
email.setSubject(subject);
email.setContent(contents, CONTENT_TYPE);
email.send();
}
/**
* 发送带附件的邮件方式 邮件内容有标题和邮件内容和附件,附件可以是本地机器上的文本,也可以是web上的一个URL 文件,
* 当为web上的一个URL文件时,此方法可以将WEB中的URL文件先下载到本地,再发送给收入用户
*
* @param subject
* 邮件标题
* @param contents
* 邮件内容
* @param userEmailAddress
* 收入人的邮件地址 为List形式
* @param multiPaths
* 附件地址 为数组形式
* @throws Exception
* @throws Exception
*/
public static void sendMultiPartEmail(String subject, String contents, List<String> userEmailAddress, String[] multiPaths) throws Exception {
// MimeUtility.encodeText(filename); 测试中文乱码用的
// EmailAttachment attachment = new EmailAttachment();
// attachment.setPath("D:/aaa.ppt");
// attachment.setDisposition(EmailAttachment.ATTACHMENT);
// attachment.setDescription("Picture of John");
List list = new ArrayList();
// EmailAttachment [] attachmentArray = new
// EmailAttachment[multiPaths.length];
for (int j = 0; j < multiPaths.length; j++) {
EmailAttachment attachment = new EmailAttachment();
if (multiPaths[j].indexOf("http") == -1) // 判断当前这个文件路径是否在本地
// 如果是:setPath 否则
// setURL;
{
attachment.setPath(multiPaths[j]);
} else {
attachment.setURL(new URL(multiPaths[j]));
}
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("");
list.add(attachment);
}
// 发送邮件信息
MultiPartEmail email = new MultiPartEmail();
email.setHostName(Constant.mailHost);
email.setAuthentication(Constant.mailUsername,Constant.mailPassword);
// 发送给多个人
for (int i = 0; i < userEmailAddress.size(); i++) {
email.addTo(userEmailAddress.get(i), userEmailAddress.get(i));
}
email.setFrom(FROM_EMAIL_ADDRESS, FROM_EMAIL_ADDRESS);
email.setSubject("The picture");
email.setMsg(contents); // 注意这个不要使用setContent这个方法 setMsg不会出现乱码
for (int a = 0; a < list.size(); a++) // 添加多个附件
{
email.attach((EmailAttachment) list.get(a));
}
// email.attach(attachment);
email.send();
}
/**
* 发送Html格式的邮件
*
* @param subject
* 邮件标题
* @param contents
* 邮件内容
* @param userEmailAddress
* 接收用户的邮箱地址
* @param fromEmailAddress
* 发送人的邮箱地址
*
* @throws Exception
*/
public static void sendHtmlEmail(String subject, String contents, List<String> userEmailAddress)
throws Exception {
HtmlEmail email = new HtmlEmail();
email.setHostName(Constant.mailHost);
email.setAuthentication(Constant.mailUsername,Constant.mailPassword);
// 发送给多个人
for (int i = 0; i < userEmailAddress.size(); i++) {
email.addTo(userEmailAddress.get(i), userEmailAddress.get(i));
}
email.setFrom(FROM_EMAIL_ADDRESS, FROM_EMAIL_ADDRESS);
email.setSubject(subject);
email.setCharset("UTF-8");
email.setHtmlMsg(contents);
email.setTextMsg(contents);
email.send();
}
/**
* 统一的发送邮件的方法 调用时一定要实例化EmailBean对象
*
* @throws Exception
*
*/
public static void sendEmail(Email email) throws Exception {
if (email.isHaveMultPaths()) {
sendMultiPartEmail(email.getSubject(), email.getContents(), email.getUserEmailAddress(), email.getMultiPaths());
} else {
sendSimpleEmail(email.getSubject(), email.getContents(), email.getUserEmailAddress());
}
}
public static boolean checkEmail(String email) {
if (!email.matches("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+")) {
return false;
}
String host = "";
String hostName = email.split("@")[1];
Record[] result = null;
SMTPClient client = new SMTPClient();
try {
// 查找MX记录
Lookup lookup = new Lookup(hostName, Type.MX);
lookup.run();
if (lookup.getResult() != Lookup.SUCCESSFUL) {
return false;
} else {
result = lookup.getAnswers();
}
// 连接到邮箱服务器
for (int i = 0; i < result.length; i++) {
host = result[i].getAdditionalName().toString();
client.connect(host);
if (!SMTPReply.isPositiveCompletion(client.getReplyCode())) {
client.disconnect();
continue;
} else {
break;
}
}
//以下2项自己填写快速的,有效的邮箱
client.login("163.com");
client.setSender("sxgkwei@163.com");
client.addRecipient(email);
if (250 == client.getReplyCode()) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
client.disconnect();
} catch (IOException e) {
}
}
return false;
}
public static void main(String[] args) {
Email email = new Email();
List<String> mailList = new ArrayList<String>();
mailList.add("zhangxiaoyan@reyun.com");
email.setSubject("mail test");
email.setContents("what's the fuck mail");
email.setUserEmailAddress(mailList);
StringBuffer content = new StringBuffer();
content.append("Company: test").append("<br>");
content.append("Email: test@reyun.com").append("<br>");
content.append("Name: test").append("<br>");
content.append("Phone: test").append("<br>");
content.append("手机归属地:test").append("<br>");
content.append("IP归属地:test").append("<br>");
content.append("微信: test").append("<br>");
content.append("同意请点击--><a href=\"https://www.baidu.com\">https://www.baidu.com</a>");
try {
sendHtmlEmail("mail test", content.toString(), mailList);
} catch (Exception e) {
e.printStackTrace();
}
}
}
...@@ -44,6 +44,11 @@ ...@@ -44,6 +44,11 @@
<property name="username" value="${default.dataSource.username}"/> <property name="username" value="${default.dataSource.username}"/>
<property name="password" value="${default.dataSource.password}"/> <property name="password" value="${default.dataSource.password}"/>
</bean> </bean>
<bean id="officeDataSource" parent="parentDataSource">
<property name="url" value="${office.url}"/>
<property name="username" value="${office.username}"/>
<property name="password" value="${office.password}"/>
</bean>
<!-- JPA实体管理工厂的配置 --> <!-- JPA实体管理工厂的配置 -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
...@@ -55,17 +60,33 @@ ...@@ -55,17 +60,33 @@
<property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/> <property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/>
<property name="jpaProperties"> <property name="jpaProperties">
<props> <props>
<prop key="hibernate.physical_naming_strategy">com.reyun.framework.strategy.ImprovedNamingStrategy <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
</prop>
<prop key="hibernate.show_sql">false</prop> <prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop><!-- none --> <prop key="hibernate.hbm2ddl.auto">update</prop><!-- none -->
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.use_sql_comments">true</prop> <prop key="hibernate.connection.CharSet">utf8</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.connection.characterEncoding">utf8</prop>
<prop key="hibernate.connection.useUnicode">true</prop>
</props> </props>
</property> </property>
</bean> </bean>
<bean id="officeEntityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="officeDataSource"/>
<property name="packagesToScan" value="office.model"></property>
<property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop><!-- none -->
<prop key="hibernate.connection.CharSet">utf8</prop>
<prop key="hibernate.connection.characterEncoding">utf8</prop>
<prop key="hibernate.connection.useUnicode">true</prop>
</props>
</property>
</bean>
<!--指定实现JPA的适配器 --> <!--指定实现JPA的适配器 -->
<bean id="hibernateJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <bean id="hibernateJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/> <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>
...@@ -75,16 +96,20 @@ ...@@ -75,16 +96,20 @@
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/> <property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean> </bean>
<bean id="officeTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="officeEntityManagerFactory"/>
</bean>
<!-- Spring Data Jpa配置 --> <!-- Spring Data Jpa配置 -->
<jpa:repositories base-package="common.repository" <jpa:repositories base-package="common.repository"
repository-impl-postfix="Impl" transaction-manager-ref="transactionManager" repository-impl-postfix="Impl" transaction-manager-ref="transactionManager"
entity-manager-factory-ref="entityManagerFactory"/> entity-manager-factory-ref="entityManagerFactory"/>
<jpa:repositories base-package="office.repository"
repository-impl-postfix="Impl" transaction-manager-ref="officeTransactionManager"
entity-manager-factory-ref="officeEntityManagerFactory"/>
<!-- 使用annotation定义事务 --> <!-- 使用annotation定义事务 -->
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
<tx:annotation-driven transaction-manager="officeTransactionManager" proxy-target-class="true"/>
<tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes> <tx:attributes>
...@@ -96,7 +121,7 @@ ...@@ -96,7 +121,7 @@
</tx:attributes> </tx:attributes>
</tx:advice> </tx:advice>
<tx:advice id="monitorTxAdvice" transaction-manager="monitorTransactionManager"> <tx:advice id="officeTxAdvice" transaction-manager="officeTransactionManager">
<tx:attributes> <tx:attributes>
<tx:method name="report*" propagation="SUPPORTS" read-only="true"/> <tx:method name="report*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="list*" propagation="SUPPORTS" read-only="true"/> <tx:method name="list*" propagation="SUPPORTS" read-only="true"/>
...@@ -110,7 +135,10 @@ ...@@ -110,7 +135,10 @@
<aop:pointcut id="txPointcut" expression="execution(* common.service.*.*(..))"/> <aop:pointcut id="txPointcut" expression="execution(* common.service.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config> </aop:config>
<aop:config expose-proxy="true">
<aop:pointcut id="officetxPointcut" expression="execution(* office.service.*.*(..))"/>
<aop:advisor advice-ref="officeTxAdvice" pointcut-ref="officetxPointcut"/>
</aop:config>
<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 --> <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
......
mail.host=${mail.host}
mail.username=${mail.username}
mail.password=${mail.password}
mail.content_type=${mail.content_type}
mail.list=${mail.list}
mail.valid_time=${mail.valid_time}
\ No newline at end of file
...@@ -3,3 +3,8 @@ dataSource.driverClassName=${datasource.driver} ...@@ -3,3 +3,8 @@ dataSource.driverClassName=${datasource.driver}
default.dataSource.url=${default.datasource.url} default.dataSource.url=${default.datasource.url}
default.dataSource.username=${default.datasource.username} default.dataSource.username=${default.datasource.username}
default.dataSource.password=${default.datasource.password} default.dataSource.password=${default.datasource.password}
office.url=${office.url}
office.username=${office.username}
office.password=${office.password}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment