Commit 9407336e by 丁伟

1、取消qq邮箱无法注册的问题。

2、增加“是否购买CDCS/CSDG考前培训”
parent a37736f7
...@@ -44,10 +44,10 @@ public class BaseDao<T> implements IDao<T> { ...@@ -44,10 +44,10 @@ public class BaseDao<T> implements IDao<T> {
boolean success; boolean success;
try { try {
hibernateTemplate.saveOrUpdate(t); hibernateTemplate.saveOrUpdate(t);
success=true; success = true;
}catch (Exception e){ } catch (Exception e) {
success=false; success = false;
throw new RuntimeException("save failed",e); throw new RuntimeException("save failed", e);
} }
return success; return success;
} }
...@@ -103,10 +103,10 @@ public class BaseDao<T> implements IDao<T> { ...@@ -103,10 +103,10 @@ public class BaseDao<T> implements IDao<T> {
boolean success; boolean success;
try { try {
hibernateTemplate.delete(t); hibernateTemplate.delete(t);
success=true; success = true;
}catch (Exception e){ } catch (Exception e) {
success=false; success = false;
throw new RuntimeException("save failed",e); throw new RuntimeException("save failed", e);
} }
return success; return success;
} }
...@@ -121,13 +121,13 @@ public class BaseDao<T> implements IDao<T> { ...@@ -121,13 +121,13 @@ public class BaseDao<T> implements IDao<T> {
boolean success = false; boolean success = false;
try { try {
T t = queryById(id); T t = queryById(id);
if (t!=null){ if (t != null) {
hibernateTemplate.delete(t); hibernateTemplate.delete(t);
success=true; success = true;
} }
}catch (Exception e){ } catch (Exception e) {
success=false; success = false;
throw new RuntimeException("save failed",e); throw new RuntimeException("save failed", e);
} }
return success; return success;
} }
...@@ -146,10 +146,10 @@ public class BaseDao<T> implements IDao<T> { ...@@ -146,10 +146,10 @@ public class BaseDao<T> implements IDao<T> {
for (int i = 0; i < ts.size(); i++) { for (int i = 0; i < ts.size(); i++) {
hibernateTemplate.saveOrUpdate(ts.get(i)); hibernateTemplate.saveOrUpdate(ts.get(i));
} }
success=true; success = true;
}catch (Exception e){ } catch (Exception e) {
success=false; success = false;
throw new RuntimeException("save failed",e); throw new RuntimeException("save failed", e);
} }
return success; return success;
} }
...@@ -168,10 +168,10 @@ public class BaseDao<T> implements IDao<T> { ...@@ -168,10 +168,10 @@ public class BaseDao<T> implements IDao<T> {
for (int i = 0; i < ts.size(); i++) { for (int i = 0; i < ts.size(); i++) {
hibernateTemplate.delete(ts.get(i)); hibernateTemplate.delete(ts.get(i));
} }
success=true; success = true;
}catch (Exception e){ } catch (Exception e) {
success=false; success = false;
throw new RuntimeException("save failed",e); throw new RuntimeException("save failed", e);
} }
return success; return success;
......
...@@ -11,51 +11,66 @@ import java.util.List; ...@@ -11,51 +11,66 @@ import java.util.List;
public interface IDao<T> { public interface IDao<T> {
/** /**
* 实例化一个实体 * 实例化一个实体
*
* @param t * @param t
*/ */
public boolean save(T t); public boolean save(T t);
/** /**
* 实例化所有实体 * 实例化所有实体
*
* @param t * @param t
*/ */
public boolean saveAll(List<T> list); public boolean saveAll(List<T> list);
/** /**
* 删除一个实体 * 删除一个实体
*
* @param t * @param t
*/ */
public boolean delete(T t); public boolean delete(T t);
/** /**
* 删除一个实体 * 删除一个实体
*
* @param id * @param id
*/ */
public boolean deleteById(long id); public boolean deleteById(long id);
/** /**
* 删除所有实体 * 删除所有实体
*
* @param t * @param t
*/ */
public boolean deleteAll(List<T> list); public boolean deleteAll(List<T> list);
/** /**
* 查询实体 * 查询实体
*
* @param t * @param t
*/ */
public List<T> query(final String hql, final Object... params); public List<T> query(final String hql, final Object... params);
/** /**
* 查询所有 * 查询所有
*
* @param t * @param t
*/ */
public List<T> queryAll(); public List<T> queryAll();
/** /**
* 分页查询 * 分页查询
*
* @param pageRequest * @param pageRequest
* @param hql * @param hql
* @param values * @param values
* @return * @return
*/ */
public Page findPage(PageRequest pageRequest, String hql, Object[] values); public Page findPage(PageRequest pageRequest, String hql, Object[] values);
/** /**
* 获取实体的Class * 获取实体的Class
*
* @param t * @param t
*/ */
public Class getEntityClass(); public Class getEntityClass();
......
package org.ccpit.base.modol; package org.ccpit.base.modol;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.io.Serializable; import java.io.Serializable;
import java.lang.annotation.Inherited;
/** /**
* Created by Administrator on 2015/8/13. * Created by Administrator on 2015/8/13.
*/ */
public class BaseEntity implements IEntity,Serializable { public class BaseEntity implements IEntity, Serializable {
/** /**
* Serializable ID * Serializable ID
*/ */
......
...@@ -7,7 +7,9 @@ import java.util.List; ...@@ -7,7 +7,9 @@ import java.util.List;
*/ */
public interface IRole { public interface IRole {
public String getRoleName(); public String getRoleName();
public List<RoleUrl> getUrlPerfixs(); public List<RoleUrl> getUrlPerfixs();
public long getId(); public long getId();
} }
package org.ccpit.base.role; package org.ccpit.base.role;
import org.ccpit.base.modol.BaseEntity; import org.ccpit.base.modol.BaseEntity;
import org.hibernate.annotations.*; import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*; import javax.persistence.*;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
...@@ -25,18 +23,18 @@ public class Role extends BaseEntity implements IRole { ...@@ -25,18 +23,18 @@ public class Role extends BaseEntity implements IRole {
public long getId() { public long getId() {
return super.getId(); return super.getId();
} }
@Override @Override
public String getRoleName() { public String getRoleName() {
return roleName; return roleName;
} }
public void setRoleName(String roleName) { public void setRoleName(String roleName) {
this.roleName = roleName; this.roleName = roleName;
} }
@Override @Override
@OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER) @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
public List<RoleUrl> getUrlPerfixs() { public List<RoleUrl> getUrlPerfixs() {
return urlPerfixs; return urlPerfixs;
} }
...@@ -55,19 +53,19 @@ public class Role extends BaseEntity implements IRole { ...@@ -55,19 +53,19 @@ public class Role extends BaseEntity implements IRole {
@Override @Override
public int hashCode() { public int hashCode() {
return ("role"+getId()).hashCode(); return ("role" + getId()).hashCode();
} }
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if(o == null){ if (o == null) {
return false; return false;
} }
if(o == this){ if (o == this) {
return true; return true;
} }
if(o.getClass() == Role.class){ if (o.getClass() == Role.class) {
return o.hashCode()==this.hashCode(); return o.hashCode() == this.hashCode();
} }
return false; return false;
} }
......
package org.ccpit.base.role; package org.ccpit.base.role;
import java.io.IOException;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray; import net.sf.json.JSONArray;
import org.ccpit.base.controller.BaseController; import org.ccpit.base.controller.BaseController;
import org.ccpit.base.controller.Page;
import org.ccpit.base.controller.PageRequest; import org.ccpit.base.controller.PageRequest;
import org.ccpit.base.user.User; import org.ccpit.base.user.User;
import org.ccpit.base.user.UserService; import org.ccpit.base.user.UserService;
...@@ -20,91 +12,99 @@ import org.springframework.web.bind.annotation.RequestMapping; ...@@ -20,91 +12,99 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** /**
* Created by Administrator on 2015/9/6. * Created by Administrator on 2015/9/6.
*/ */
@Controller @Controller
@RequestMapping("/admin/role") @RequestMapping("/admin/role")
public class RoleController extends BaseController{ public class RoleController extends BaseController {
@Autowired @Autowired
private RoleService roleService; private RoleService roleService;
@Autowired @Autowired
private UserService userService; private UserService userService;
@RequestMapping("/goinRoleListPage") @RequestMapping("/goinRoleListPage")
public Object manage(){ public Object manage() {
return new ModelAndView("admin/role/roleListPage"); return new ModelAndView("admin/role/roleListPage");
} }
@RequestMapping("/addRole") @RequestMapping("/addRole")
public void addRole(String roleName,String urlPerfixs,String description,HttpServletResponse response){ public void addRole(String roleName, String urlPerfixs, String description, HttpServletResponse response) {
String result = ""; String result = "";
boolean flag = roleService.addRole(roleName,urlPerfixs,description); boolean flag = roleService.addRole(roleName, urlPerfixs, description);
if(flag){ if (flag) {
result = "{ \"flag\": "+ flag +", \"info\": \"数据保存成功!\" }"; result = "{ \"flag\": " + flag + ", \"info\": \"数据保存成功!\" }";
}else { } else {
result = "{ \"flag\": "+ flag +", \"info\": \"数据保存失败!\" }"; result = "{ \"flag\": " + flag + ", \"info\": \"数据保存失败!\" }";
} }
try { try {
response.setContentType("text/html"); response.setContentType("text/html");
response.getWriter().write(result); response.getWriter().write(result);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
/** /**
*
* addRolePri:(添加角色操作权限). <br/> * addRolePri:(添加角色操作权限). <br/>
* TODO(这里描述这个方法适用条件 – 可选).<br/> * TODO(这里描述这个方法适用条件 – 可选).<br/>
* TODO(这里描述这个方法的执行流程 – 可选).<br/> * TODO(这里描述这个方法的执行流程 – 可选).<br/>
* TODO(这里描述这个方法的使用方法 – 可选).<br/> * TODO(这里描述这个方法的使用方法 – 可选).<br/>
* TODO(这里描述这个方法的注意事项 – 可选).<br/> * TODO(这里描述这个方法的注意事项 – 可选).<br/>
* *
* @author dingwei
* @return * @return
* @author dingwei
* @since JDK 1.6 * @since JDK 1.6
*/ */
@RequestMapping("/addRolePri") @RequestMapping("/addRolePri")
public void addRolePri(HttpServletRequest request,HttpServletResponse response){ public void addRolePri(HttpServletRequest request, HttpServletResponse response) {
String result = ""; String result = "";
String roleId = request.getParameter("roleId"); String roleId = request.getParameter("roleId");
String urlPrefixs = request.getParameter("priIds"); String urlPrefixs = request.getParameter("priIds");
boolean flag = roleService.editRole(Long.valueOf(roleId), "", urlPrefixs, ""); boolean flag = roleService.editRole(Long.valueOf(roleId), "", urlPrefixs, "");
if(flag){ if (flag) {
result = "{ \"flag\": "+ flag +", \"info\": \"数据保存成功!\" }"; result = "{ \"flag\": " + flag + ", \"info\": \"数据保存成功!\" }";
}else { } else {
result = "{ \"flag\": "+ flag +", \"info\": \"数据保存失败!\" }"; result = "{ \"flag\": " + flag + ", \"info\": \"数据保存失败!\" }";
} }
try { try {
response.setContentType("text/html"); response.setContentType("text/html");
response.getWriter().write(result); response.getWriter().write(result);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@RequestMapping("/editRole/{id}") @RequestMapping("/editRole/{id}")
public void editRole(@PathVariable long id,String roleName,String urlPerfixs,String description,HttpServletResponse response){ public void editRole(@PathVariable long id, String roleName, String urlPerfixs, String description, HttpServletResponse response) {
String result = ""; String result = "";
boolean flag = roleService.editRole(id, roleName, urlPerfixs,description); boolean flag = roleService.editRole(id, roleName, urlPerfixs, description);
if(flag){ if (flag) {
result = "{ \"flag\": "+ flag +", \"info\": \"数据保存成功!\" }"; result = "{ \"flag\": " + flag + ", \"info\": \"数据保存成功!\" }";
}else { } else {
result = "{ \"flag\": "+ flag +", \"info\": \"数据保存失败!\" }"; result = "{ \"flag\": " + flag + ", \"info\": \"数据保存失败!\" }";
} }
try { try {
response.setContentType("text/html"); response.setContentType("text/html");
response.getWriter().write(result); response.getWriter().write(result);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@RequestMapping("/userRoles/{id}") @RequestMapping("/userRoles/{id}")
@ResponseBody @ResponseBody
public Object userRoles(@PathVariable long id){ public Object userRoles(@PathVariable long id) {
User user = userService.getUser(id); User user = userService.getUser(id);
if (user!=null){ if (user != null) {
return userService.getUserRoles(user); return userService.getUserRoles(user);
} }
return "false"; return "false";
...@@ -112,22 +112,22 @@ public class RoleController extends BaseController{ ...@@ -112,22 +112,22 @@ public class RoleController extends BaseController{
@RequestMapping("/delRoles") @RequestMapping("/delRoles")
@ResponseBody @ResponseBody
public Object delRoles(HttpServletRequest request){ public Object delRoles(HttpServletRequest request) {
Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> map = new HashMap<String, Object>();
String jsonIds = request.getParameter("ids"); String jsonIds = request.getParameter("ids");
JSONArray jsonArray = JSONArray.fromObject(jsonIds); JSONArray jsonArray = JSONArray.fromObject(jsonIds);
Object[] ids = jsonArray.toArray(); Object[] ids = jsonArray.toArray();
for(Object str : ids){ for (Object str : ids) {
boolean flag = roleService.deleteRole((Integer) str); boolean flag = roleService.deleteRole((Integer) str);
} }
map.put("flag", true); map.put("flag", true);
map.put("info", "数据删除成功!"); map.put("info", "数据删除成功!");
return map; return map;
} }
@RequestMapping("/saveUserRoles/{id}") @RequestMapping("/saveUserRoles/{id}")
@ResponseBody @ResponseBody
public Object saveUserRoles(@PathVariable long id,HttpServletRequest request,String[] ids){ public Object saveUserRoles(@PathVariable long id, HttpServletRequest request, String[] ids) {
System.out.println(ids); System.out.println(ids);
User user = userService.getUser(id); User user = userService.getUser(id);
//todo save //todo save
...@@ -135,14 +135,14 @@ public class RoleController extends BaseController{ ...@@ -135,14 +135,14 @@ public class RoleController extends BaseController{
JSONArray jsonArray = JSONArray.fromObject(ids); JSONArray jsonArray = JSONArray.fromObject(ids);
Object[] arr = jsonArray.toArray(); Object[] arr = jsonArray.toArray();
Long[] longs = new Long[arr.length]; Long[] longs = new Long[arr.length];
for (int i=0;i<arr.length;i++){ for (int i = 0; i < arr.length; i++) {
longs[i] = Long.parseLong(arr[i].toString()); longs[i] = Long.parseLong(arr[i].toString());
} }
boolean flag = userService.saveUserRoles(user,longs); boolean flag = userService.saveUserRoles(user, longs);
if (flag){ if (flag) {
map.put("flag", true); map.put("flag", true);
map.put("info", "数据删除成功!"); map.put("info", "数据删除成功!");
}else{ } else {
map.put("flag", false); map.put("flag", false);
map.put("info", "保存失败!"); map.put("info", "保存失败!");
} }
...@@ -152,45 +152,45 @@ public class RoleController extends BaseController{ ...@@ -152,45 +152,45 @@ public class RoleController extends BaseController{
@RequestMapping("/getAllRoles") @RequestMapping("/getAllRoles")
@ResponseBody @ResponseBody
public Object getAllRoles(HttpServletRequest request){ public Object getAllRoles(HttpServletRequest request) {
PageRequest pageRequest = getPage(request); PageRequest pageRequest = getPage(request);
String roleName = request.getParameter("roleName"); String roleName = request.getParameter("roleName");
StringBuffer hql = new StringBuffer("from Role where 1=1"); StringBuffer hql = new StringBuffer("from Role where 1=1");
if(null == roleName){ if (null == roleName) {
}else { } else {
if(null != roleName){ if (null != roleName) {
hql.append(" and roleName like '%" + roleName +"%'"); hql.append(" and roleName like '%" + roleName + "%'");
} }
} }
List<Role> pageRole = roleService.getAll(hql.toString()); List<Role> pageRole = roleService.getAll(hql.toString());
return pageRole; return pageRole;
} }
@RequestMapping("/getRoleByID") @RequestMapping("/getRoleByID")
@ResponseBody @ResponseBody
public Role getRoleByID(HttpServletRequest request){ public Role getRoleByID(HttpServletRequest request) {
String roleId = request.getParameter("roleId"); String roleId = request.getParameter("roleId");
Role role = null; Role role = null;
if(null != roleId){ if (null != roleId) {
role = roleService.get(Long.valueOf(roleId)); role = roleService.get(Long.valueOf(roleId));
} }
return role; return role;
} }
@RequestMapping("/getRolesList") @RequestMapping("/getRolesList")
@ResponseBody @ResponseBody
public Object getRolesList(HttpServletRequest request){ public Object getRolesList(HttpServletRequest request) {
List<Role> listBo = roleService.getAllRoles(); List<Role> listBo = roleService.getAllRoles();
List list = new ArrayList(); List list = new ArrayList();
if(null != listBo){ if (null != listBo) {
for(int i=0;i<listBo.size();i++){ for (int i = 0; i < listBo.size(); i++) {
Map result = new HashMap(); Map result = new HashMap();
result.put("id", listBo.get(i).getId()); result.put("id", listBo.get(i).getId());
result.put("text", listBo.get(i).getRoleName()); result.put("text", listBo.get(i).getRoleName());
list.add(result); list.add(result);
} }
} }
return list; return list;
} }
} }
...@@ -9,8 +9,8 @@ import org.springframework.stereotype.Repository; ...@@ -9,8 +9,8 @@ import org.springframework.stereotype.Repository;
*/ */
@Repository @Repository
public class RoleDao extends BaseDao<Role> { public class RoleDao extends BaseDao<Role> {
public Role getRoleByUrl(String url){ public Role getRoleByUrl(String url) {
Role role = findUnique("select r from "+Role.class.getName()+" as r left join r.urlPerfixs as p where p.url = ?",new String[]{url}); Role role = findUnique("select r from " + Role.class.getName() + " as r left join r.urlPerfixs as p where p.url = ?", new String[]{url});
return role; return role;
} }
} }
...@@ -5,14 +5,15 @@ import org.ccpit.base.controller.Convert; ...@@ -5,14 +5,15 @@ import org.ccpit.base.controller.Convert;
import org.ccpit.base.controller.Page; import org.ccpit.base.controller.Page;
import org.ccpit.base.controller.PageBo; import org.ccpit.base.controller.PageBo;
import org.ccpit.base.controller.PageRequest; import org.ccpit.base.controller.PageRequest;
import org.ccpit.base.user.UserDao;
import org.ccpit.base.utils.UrlRolesMapper; import org.ccpit.base.utils.UrlRolesMapper;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import javax.transaction.Transactional; import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.*; import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** /**
* Created by Administrator on 2015/9/6. * Created by Administrator on 2015/9/6.
...@@ -25,7 +26,7 @@ public class RoleService { ...@@ -25,7 +26,7 @@ public class RoleService {
@Autowired @Autowired
private UrlRolesMapper mapper; private UrlRolesMapper mapper;
public boolean addRole(String roleName, String url,String description) { public boolean addRole(String roleName, String url, String description) {
Role role = new Role(); Role role = new Role();
role.setRoleName(roleName); role.setRoleName(roleName);
role.setDescription(description); role.setDescription(description);
...@@ -46,16 +47,16 @@ public class RoleService { ...@@ -46,16 +47,16 @@ public class RoleService {
return result; return result;
} }
public boolean editRole(long id,String roleName,String urlPrefixs,String description) { public boolean editRole(long id, String roleName, String urlPrefixs, String description) {
Role role = roleDao.queryById(id); Role role = roleDao.queryById(id);
urlPrefixs = getPriId(urlPrefixs); urlPrefixs = getPriId(urlPrefixs);
if (role!=null){ if (role != null) {
if(null != roleName && !"".equals(roleName)){ if (null != roleName && !"".equals(roleName)) {
role.setRoleName(roleName); role.setRoleName(roleName);
} }
if(null != roleName && !"".equals(description)){ if (null != roleName && !"".equals(description)) {
role.setDescription(description); role.setDescription(description);
} }
List<RoleUrl> urlList = new ArrayList<RoleUrl>(); List<RoleUrl> urlList = new ArrayList<RoleUrl>();
for (String u : urlPrefixs.split(",")) { for (String u : urlPrefixs.split(",")) {
RoleUrl ru = new RoleUrl(); RoleUrl ru = new RoleUrl();
...@@ -85,8 +86,8 @@ public class RoleService { ...@@ -85,8 +86,8 @@ public class RoleService {
public Page<Role> getAll(PageRequest pr) { public Page<Role> getAll(PageRequest pr) {
return roleDao.findPage(pr, "from " + Role.class.getName(), null); return roleDao.findPage(pr, "from " + Role.class.getName(), null);
} }
public Page<Role> getAll(PageRequest pr,String hql) { public Page<Role> getAll(PageRequest pr, String hql) {
return roleDao.findPage(pr, hql, null); return roleDao.findPage(pr, hql, null);
} }
...@@ -95,27 +96,27 @@ public class RoleService { ...@@ -95,27 +96,27 @@ public class RoleService {
} }
public List<Role> getAllRoles(){ public List<Role> getAllRoles() {
return roleDao.queryAll(); return roleDao.queryAll();
} }
public Map<String,Object> convertToMap(Role role){ public Map<String, Object> convertToMap(Role role) {
Map<String,Object> map = new HashMap<String, Object>(); Map<String, Object> map = new HashMap<String, Object>();
if (role==null) if (role == null)
return map; return map;
List<String> urls = new ArrayList<String>(); List<String> urls = new ArrayList<String>();
for (RoleUrl roleUrl:role.getUrlPerfixs()){ for (RoleUrl roleUrl : role.getUrlPerfixs()) {
urls.add(roleUrl.getUrl()); urls.add(roleUrl.getUrl());
} }
map.put("urlPrefixs", StringUtils.join(urls,",")); map.put("urlPrefixs", StringUtils.join(urls, ","));
map.put("roleName",role.getRoleName()); map.put("roleName", role.getRoleName());
map.put("id",role.getId()); map.put("id", role.getId());
map.put("urlPerfixs",urls); map.put("urlPerfixs", urls);
map.put("description",role.getDescription()); map.put("description", role.getDescription());
return map; return map;
} }
public PageBo<Role> convert(Page<Role> page){ public PageBo<Role> convert(Page<Role> page) {
return new PageBo<Role>(page, new Convert<Role>() { return new PageBo<Role>(page, new Convert<Role>() {
@Override @Override
public Map<String, Object> convert(Role obj) { public Map<String, Object> convert(Role obj) {
...@@ -126,31 +127,32 @@ public class RoleService { ...@@ -126,31 +127,32 @@ public class RoleService {
/** /**
* 根据url查找role * 根据url查找role
*
* @param url * @param url
* @return * @return
*/ */
public Role findRoleByUrl(String url){ public Role findRoleByUrl(String url) {
return roleDao.getRoleByUrl(url); return roleDao.getRoleByUrl(url);
} }
//去掉重复priId //去掉重复priId
private String getPriId(String priIds){ private String getPriId(String priIds) {
List list = new ArrayList(); List list = new ArrayList();
String[] str = priIds.split(","); String[] str = priIds.split(",");
if(null != str && !"".equals(str)){ if (null != str && !"".equals(str)) {
for(int i=0; i<str.length;i++){ for (int i = 0; i < str.length; i++) {
if(!list.contains(str[i])){ if (!list.contains(str[i])) {
list.add(str[i]); list.add(str[i]);
} }
} }
} }
String priId = ""; String priId = "";
if(null != list && list.size()>0){ if (null != list && list.size() > 0) {
for(int j=0;j<list.size();j++){ for (int j = 0; j < list.size(); j++) {
String id = (String) list.get(j); String id = (String) list.get(j);
priId += id + ","; priId += id + ",";
} }
} }
return priId.substring(0, priId.length()-1); return priId.substring(0, priId.length() - 1);
} }
} }
package org.ccpit.base.role; package org.ccpit.base.role;
import org.ccpit.base.modol.BaseEntity; import org.ccpit.base.modol.BaseEntity;
import org.hibernate.annotations.*; import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*; import javax.persistence.*;
import javax.persistence.Entity;
/** /**
* 角色 地址 映射表 * 角色 地址 映射表
......
...@@ -2,12 +2,9 @@ package org.ccpit.base.security; ...@@ -2,12 +2,9 @@ package org.ccpit.base.security;
import org.ccpit.base.controller.BaseController; import org.ccpit.base.controller.BaseController;
import org.ccpit.base.user.User; import org.ccpit.base.user.User;
import org.ccpit.base.user.UserService;
import org.springframework.beans.BeansException; import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationContextAware;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspException;
...@@ -16,14 +13,14 @@ import javax.servlet.jsp.tagext.TagSupport; ...@@ -16,14 +13,14 @@ import javax.servlet.jsp.tagext.TagSupport;
/** /**
* Created by Administrator on 2015/9/8. * Created by Administrator on 2015/9/8.
*/ */
public class CmsTagSupport extends TagSupport implements ApplicationContextAware{ public class CmsTagSupport extends TagSupport implements ApplicationContextAware {
static String SPLIT = ","; static String SPLIT = ",";
static ApplicationContext ac; static ApplicationContext ac;
public User getUser(){ public User getUser() {
HttpServletRequest req = (HttpServletRequest) pageContext.getRequest(); HttpServletRequest req = (HttpServletRequest) pageContext.getRequest();
Object obj = req.getSession().getAttribute(BaseController.USER_IN_SESSION); Object obj = req.getSession().getAttribute(BaseController.USER_IN_SESSION);
if (obj==null) if (obj == null)
return null; return null;
return (User) obj; return (User) obj;
// UserService userService = ac.getBean(UserService.class); // UserService userService = ac.getBean(UserService.class);
...@@ -33,21 +30,24 @@ public class CmsTagSupport extends TagSupport implements ApplicationContextAware ...@@ -33,21 +30,24 @@ public class CmsTagSupport extends TagSupport implements ApplicationContextAware
@Override @Override
public int doStartTag() throws JspException { public int doStartTag() throws JspException {
if (getUser()==null) if (getUser() == null)
return SKIP_BODY; return SKIP_BODY;
return validate()?EVAL_PAGE:SKIP_BODY; return validate() ? EVAL_PAGE : SKIP_BODY;
} }
/** /**
* validate the security return the result * validate the security return the result
*
* @return * @return
*/ */
public boolean validate(){ public boolean validate() {
return false; return false;
}; }
;
@Override @Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ac=applicationContext; ac = applicationContext;
} }
} }
...@@ -3,15 +3,10 @@ package org.ccpit.base.security; ...@@ -3,15 +3,10 @@ package org.ccpit.base.security;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.ccpit.base.controller.BaseController; import org.ccpit.base.controller.BaseController;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.*; import javax.servlet.*;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.jstl.sql.Result;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
...@@ -19,7 +14,7 @@ import java.util.List; ...@@ -19,7 +14,7 @@ import java.util.List;
/** /**
* 用户登录Filter 拦截后台所有请求 * 用户登录Filter 拦截后台所有请求
* * <p>
* Created by sqp on 2015/9/30. * Created by sqp on 2015/9/30.
*/ */
public class LoginFilter implements Filter { public class LoginFilter implements Filter {
...@@ -27,6 +22,7 @@ public class LoginFilter implements Filter { ...@@ -27,6 +22,7 @@ public class LoginFilter implements Filter {
private List<String> exceptPaths = new ArrayList<String>(); private List<String> exceptPaths = new ArrayList<String>();
//拦截之后重定向的url //拦截之后重定向的url
private String redirectPath = ""; private String redirectPath = "";
@Override @Override
public void init(FilterConfig filterConfig) throws ServletException { public void init(FilterConfig filterConfig) throws ServletException {
...@@ -43,16 +39,16 @@ public class LoginFilter implements Filter { ...@@ -43,16 +39,16 @@ public class LoginFilter implements Filter {
HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse; HttpServletResponse response = (HttpServletResponse) servletResponse;
if (exceptPaths.contains(request.getRequestURI())){ if (exceptPaths.contains(request.getRequestURI())) {
filterChain.doFilter(request,servletResponse); filterChain.doFilter(request, servletResponse);
return; return;
} }
if (request.getSession().getAttribute(BaseController.USER_IN_SESSION) == null&&request.getSession().getAttribute("registerInfo")==null) { if (request.getSession().getAttribute(BaseController.USER_IN_SESSION) == null && request.getSession().getAttribute("registerInfo") == null) {
response.sendRedirect(redirectPath); response.sendRedirect(redirectPath);
return; return;
} }
filterChain.doFilter(request,servletResponse); filterChain.doFilter(request, servletResponse);
} }
@Override @Override
......
package org.ccpit.base.security; package org.ccpit.base.security;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.ccpit.base.role.Role; import org.ccpit.base.role.Role;
import org.ccpit.base.user.UserService; import org.ccpit.base.user.UserService;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
...@@ -19,21 +16,21 @@ public class SecurityAllRoleTag extends CmsTagSupport { ...@@ -19,21 +16,21 @@ public class SecurityAllRoleTag extends CmsTagSupport {
@Override @Override
public boolean validate() { public boolean validate() {
if (roles==null||roles.isEmpty()) if (roles == null || roles.isEmpty())
return true; return true;
String[] roles = getRoles().split(SPLIT); String[] roles = getRoles().split(SPLIT);
List<Role> tagRoles = new ArrayList<Role>(); List<Role> tagRoles = new ArrayList<Role>();
for (String roleId:roles){ for (String roleId : roles) {
Role r =new Role(); Role r = new Role();
if (StringUtils.isNumeric(roleId)) if (StringUtils.isNumeric(roleId))
r.setId(Long.parseLong(roleId)); r.setId(Long.parseLong(roleId));
tagRoles.add(r); tagRoles.add(r);
} }
Set<Role> userRoles = ac.getBean(UserService.class).getUserRolesIncludeGroup(getUser()); Set<Role> userRoles = ac.getBean(UserService.class).getUserRolesIncludeGroup(getUser());
boolean can = true; boolean can = true;
for (Role r:tagRoles){ for (Role r : tagRoles) {
if (!userRoles.contains(r)){ if (!userRoles.contains(r)) {
can = false; can = false;
break; break;
} }
......
...@@ -16,23 +16,23 @@ import java.util.Set; ...@@ -16,23 +16,23 @@ import java.util.Set;
* Created by Administrator on 2015/9/7. * Created by Administrator on 2015/9/7.
*/ */
public class SecurityAnyRoleTag extends CmsTagSupport { public class SecurityAnyRoleTag extends CmsTagSupport {
private String roles; private String roles;
@Override @Override
public boolean validate() { public boolean validate() {
if (roles==null||roles.isEmpty()) if (roles == null || roles.isEmpty())
return true; return true;
String[] roles = getRoles().split(SPLIT); String[] roles = getRoles().split(SPLIT);
List<Role> tagRoles = new ArrayList<Role>(); List<Role> tagRoles = new ArrayList<Role>();
for (String roleId:roles){ for (String roleId : roles) {
Role r =new Role(); Role r = new Role();
if (StringUtils.isNumeric(roleId)) if (StringUtils.isNumeric(roleId))
r.setId(Long.parseLong(roleId)); r.setId(Long.parseLong(roleId));
tagRoles.add(r); tagRoles.add(r);
} }
Set<Role> userRoles = ac.getBean(UserService.class).getUserRolesIncludeGroup(getUser()); Set<Role> userRoles = ac.getBean(UserService.class).getUserRolesIncludeGroup(getUser());
return CollectionUtils.containsAny(tagRoles,userRoles); return CollectionUtils.containsAny(tagRoles, userRoles);
} }
public String getRoles() { public String getRoles() {
......
package org.ccpit.base.security; package org.ccpit.base.security;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.CollectionUtils;
import org.ccpit.base.role.Role; import org.ccpit.base.role.Role;
import org.ccpit.base.utils.UrlRolesMapper; import org.ccpit.base.utils.UrlRolesMapper;
import org.ccpit.base.utils.UserRolesUtil; import org.ccpit.base.utils.UserRolesUtil;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.util.Set;
/** /**
* 自定义标签 判断用户权限 * 自定义标签 判断用户权限
* Created by Administrator on 2015/9/7. * Created by Administrator on 2015/9/7.
*/ */
@Component @Component
public class SecurityUriTag extends CmsTagSupport{ public class SecurityUriTag extends CmsTagSupport {
/** Uri to check */ /**
* Uri to check
*/
private String uri; private String uri;
@Override @Override
public boolean validate() { public boolean validate() {
Set<Role> roles = ac.getBean(UrlRolesMapper.class).getRoles(getUri()); Set<Role> roles = ac.getBean(UrlRolesMapper.class).getRoles(getUri());
if (roles==null || roles.isEmpty()){ if (roles == null || roles.isEmpty()) {
return false; return false;
} }
UserRolesUtil userRolesUtil = ac.getBean(UserRolesUtil.class); UserRolesUtil userRolesUtil = ac.getBean(UserRolesUtil.class);
Set<Role> roleSet = userRolesUtil.getAllRoles((HttpServletRequest) pageContext.getRequest()); Set<Role> roleSet = userRolesUtil.getAllRoles((HttpServletRequest) pageContext.getRequest());
if (roleSet.isEmpty()){ if (roleSet.isEmpty()) {
return false; return false;
} }
return CollectionUtils.containsAny(roles,roleSet); return CollectionUtils.containsAny(roles, roleSet);
} }
public String getUri() { public String getUri() {
......
...@@ -5,6 +5,8 @@ package org.ccpit.base.user; ...@@ -5,6 +5,8 @@ package org.ccpit.base.user;
*/ */
public interface IUser { public interface IUser {
public String getUsername(); public String getUsername();
public String getLoginName(); public String getLoginName();
public long getId(); public long getId();
} }
package org.ccpit.base.user; package org.ccpit.base.user;
import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.*;
import org.ccpit.base.modol.BaseEntity; import org.ccpit.base.modol.BaseEntity;
import org.ccpit.base.role.Role; import org.ccpit.base.role.Role;
import org.hibernate.annotations.Cache; import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
/** /**
* Created by Administrator on 2015/9/2. * Created by Administrator on 2015/9/2.
*/ */
@Entity @Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class User extends BaseEntity implements IUser,Serializable{ public class User extends BaseEntity implements IUser, Serializable {
/** /**
* serialVersionUID:TODO(用一句话描述这个变量表示什么). * serialVersionUID:TODO(用一句话描述这个变量表示什么).
* @since JDK 1.6 *
*/ * @since JDK 1.6
private static final long serialVersionUID = 1L; */
/** private static final long serialVersionUID = 1L;
* 用户名 /**
*/ * 用户名
*/
private String username; private String username;
/** /**
* 密码 * 密码
...@@ -61,26 +61,26 @@ public class User extends BaseEntity implements IUser,Serializable{ ...@@ -61,26 +61,26 @@ public class User extends BaseEntity implements IUser,Serializable{
*/ */
private String telphone; private String telphone;
/** /**
* 创建人 * 创建人
*/ */
private String creator; private String creator;
/** /**
* 创建人Id * 创建人Id
*/ */
private long creatorId; private long creatorId;
/** /**
* 创建时间 * 创建时间
*/ */
private Date createTime; private Date createTime;
/** /**
* 登录次数 * 登录次数
*/ */
private Integer loginCount; private Integer loginCount;
/** /**
* 用户类型 (back | front) * 用户类型 (back | front)
*/ */
private String userType; private String userType;
private Set<Role> roles = new HashSet<Role>(); private Set<Role> roles = new HashSet<Role>();
@Override @Override
...@@ -89,16 +89,17 @@ public class User extends BaseEntity implements IUser,Serializable{ ...@@ -89,16 +89,17 @@ public class User extends BaseEntity implements IUser,Serializable{
public long getId() { public long getId() {
return super.getId(); return super.getId();
} }
@Override @Override
public String getUsername() { public String getUsername() {
return username; return username;
} }
public void setUsername(String username) { public void setUsername(String username) {
this.username = username; this.username = username;
} }
public String getPassword() { public String getPassword() {
return password; return password;
} }
...@@ -117,26 +118,27 @@ public class User extends BaseEntity implements IUser,Serializable{ ...@@ -117,26 +118,27 @@ public class User extends BaseEntity implements IUser,Serializable{
@Override @Override
public int hashCode() { public int hashCode() {
return ("user"+getId()).hashCode(); return ("user" + getId()).hashCode();
} }
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if(o == null){ if (o == null) {
return false; return false;
} }
if(o == this){ if (o == this) {
return true; return true;
} }
if(o.getClass() == User.class){ if (o.getClass() == User.class) {
return o.hashCode()==this.hashCode(); return o.hashCode() == this.hashCode();
} }
return false; return false;
} }
@ManyToMany(fetch = FetchType.EAGER,cascade = CascadeType.ALL) @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "user_Roles", @JoinTable(name = "user_Roles",
joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")}, joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "role_id", referencedColumnName ="id")}) inverseJoinColumns = {@JoinColumn(name = "role_id", referencedColumnName = "id")})
public Set<Role> getRoles() { public Set<Role> getRoles() {
return roles; return roles;
} }
...@@ -144,71 +146,93 @@ public class User extends BaseEntity implements IUser,Serializable{ ...@@ -144,71 +146,93 @@ public class User extends BaseEntity implements IUser,Serializable{
public void setRoles(Set<Role> roles) { public void setRoles(Set<Role> roles) {
this.roles = roles; this.roles = roles;
} }
public String getUserType() {
return userType; public String getUserType() {
} return userType;
public void setUserType(String userType) { }
this.userType = userType;
} public void setUserType(String userType) {
public Integer getAge() { this.userType = userType;
return age; }
}
public void setAge(Integer age) { public Integer getAge() {
this.age = age; return age;
} }
public String getSex() {
return sex; public void setAge(Integer age) {
} this.age = age;
public void setSex(String sex) { }
this.sex = sex;
} public String getSex() {
public String getCompany() { return sex;
return company; }
}
public void setCompany(String company) { public void setSex(String sex) {
this.company = company; this.sex = sex;
} }
public String getEmail() {
return email; public String getCompany() {
} return company;
public void setEmail(String email) { }
this.email = email;
} public void setCompany(String company) {
public Integer getCountStatus() { this.company = company;
return countStatus; }
}
public void setCountStatus(Integer countStatus) { public String getEmail() {
this.countStatus = countStatus; return email;
} }
public String getTelphone() {
return telphone; public void setEmail(String email) {
} this.email = email;
public void setTelphone(String telphone) { }
this.telphone = telphone;
} public Integer getCountStatus() {
public String getCreator() { return countStatus;
return creator; }
}
public void setCreator(String creator) { public void setCountStatus(Integer countStatus) {
this.creator = creator; this.countStatus = countStatus;
} }
public long getCreatorId() {
return creatorId; public String getTelphone() {
} return telphone;
public void setCreatorId(long creatorId) { }
this.creatorId = creatorId;
} public void setTelphone(String telphone) {
public Date getCreateTime() { this.telphone = telphone;
return createTime; }
}
public void setCreateTime(Date createTime) { public String getCreator() {
this.createTime = createTime; return creator;
} }
public Integer getLoginCount() {
return loginCount; public void setCreator(String creator) {
} this.creator = creator;
public void setLoginCount(Integer loginCount) { }
this.loginCount = loginCount;
} public long getCreatorId() {
return creatorId;
}
public void setCreatorId(long creatorId) {
this.creatorId = creatorId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Integer getLoginCount() {
return loginCount;
}
public void setLoginCount(Integer loginCount) {
this.loginCount = loginCount;
}
} }
package org.ccpit.base.user; package org.ccpit.base.user;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray; import net.sf.json.JSONArray;
import org.ccpit.base.controller.BaseController; import org.ccpit.base.controller.BaseController;
import org.ccpit.base.controller.Page; import org.ccpit.base.controller.Page;
import org.ccpit.base.controller.PageRequest; import org.ccpit.base.controller.PageRequest;
...@@ -22,7 +9,6 @@ import org.ccpit.base.role.RoleDao; ...@@ -22,7 +9,6 @@ import org.ccpit.base.role.RoleDao;
import org.ccpit.base.usergroup.UserGroup; import org.ccpit.base.usergroup.UserGroup;
import org.ccpit.base.usergroup.UserGroupDao; import org.ccpit.base.usergroup.UserGroupDao;
import org.ccpit.base.usergroup.UserGroupService; import org.ccpit.base.usergroup.UserGroupService;
import org.ccpit.base.utils.CryptUtil;
import org.ccpit.base.utils.PasswordHash; import org.ccpit.base.utils.PasswordHash;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
...@@ -33,6 +19,11 @@ import org.springframework.web.bind.annotation.RequestMapping; ...@@ -33,6 +19,11 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
/** /**
* Created by sqp on 2015/9/5. * Created by sqp on 2015/9/5.
*/ */
...@@ -40,246 +31,246 @@ import org.springframework.web.servlet.ModelAndView; ...@@ -40,246 +31,246 @@ import org.springframework.web.servlet.ModelAndView;
@RequestMapping("/admin/user") @RequestMapping("/admin/user")
public class UserController extends BaseController { public class UserController extends BaseController {
private static final Logger log = LoggerFactory.getLogger(UserController.class); private static final Logger log = LoggerFactory.getLogger(UserController.class);
@Autowired @Autowired
private UserService userService; private UserService userService;
@Autowired @Autowired
private UserGroupService orgService; private UserGroupService orgService;
@Autowired @Autowired
private RoleDao roleDao; private RoleDao roleDao;
@Autowired @Autowired
private UserDao userDao; private UserDao userDao;
@Autowired @Autowired
private UserGroupDao orgDao; private UserGroupDao orgDao;
@RequestMapping("/isExistUser")
@ResponseBody
public Object isExistUser(HttpServletRequest request) {
Map<String, Object> map = new HashMap<String, Object>();
String loginName = request.getParameter("loginName");
User user = userService.getUserByLoginName(loginName);
if (null == user) {
map.put("flag", false);
} else {
map.put("flag", true);
}
return map;
}
@RequestMapping("/addUser")
public void addUser(HttpServletRequest request, HttpServletResponse response, User user) {
String result = "";
User user_in_session = (User) request.getSession().getAttribute("user_in_session");
try {
//新增用户初始化密码
user.setPassword(PasswordHash.createHash("111111"));
} catch (Exception e) {
throw new RuntimeException("新增用户初始化密码加密失败....", e);
}
user.setCreatorId(user_in_session.getId());
user.setCreator(user_in_session.getUsername());
user.setCreateTime(new Date());
if (null == user.getUserType()) {
user.setUserType("back");
}
if (null == user.getCountStatus()) {
user.setCountStatus(1);
}
boolean flag = userService.addUser(user);
if (flag) {
result = "{ \"flag\": " + flag + ", \"info\": \"数据保存成功!\" }";
} else {
result = "{ \"flag\": " + flag + ", \"info\": \"数据保存失败!\" }";
}
try {
response.setContentType("text/html");
response.getWriter().write(result);
} catch (IOException e) {
e.printStackTrace();
}
}
@RequestMapping("/edit/{id}")
@ResponseBody
public Object editUser(@PathVariable long id, User user) {
Map<String, Object> map = new HashMap<String, Object>();
User user1 = userService.getUser(id);
boolean flag = false;
if (null != user.getAge()) {
user1.setAge(user.getAge());
}
if (null != user.getCountStatus()) {
user1.setCountStatus(user.getCountStatus());
}
if (null != user.getCompany()) {
user1.setCompany(user.getCompany());
}
if (null != user.getEmail()) {
user1.setEmail(user.getEmail());
}
if (null != user.getLoginName()) {
user1.setLoginName(user.getLoginName());
}
if (null != user.getSex()) {
user1.setSex(user.getSex());
}
if (null != user.getTelphone()) {
user1.setTelphone(user.getTelphone());
}
if (null != user.getUsername()) {
user1.setUsername(user.getUsername());
}
if (null != user.getUserType()) {
user1.setUserType(user.getUserType());
}
flag = userService.updateUser(user1);
if (flag) {
map.put("success", flag);
map.put("info", "修改用户数据成功!");
} else {
map.put("info", "修改用户数据失败...");
}
return map;
}
@RequestMapping("/getUserById/{id}")
@ResponseBody
public User getUserById(@PathVariable long id) {
User user = userService.getUser(id);
return user;
}
@RequestMapping("/isExistUser") @RequestMapping("/deleteUser")
@ResponseBody @ResponseBody
public Object isExistUser(HttpServletRequest request) { public Object deleteUser(HttpServletRequest request) {
Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> map = new HashMap<String, Object>();
String loginName = request.getParameter("loginName"); String jsonIds = request.getParameter("ids");
User user = userService.getUserByLoginName(loginName); JSONArray jsonArray = JSONArray.fromObject(jsonIds);
if (null == user) { Object[] ids = jsonArray.toArray();
map.put("flag", false); boolean flag = false;
} else { for (Object str : ids) {
map.put("flag", true); flag = userService.deleteUser((Integer) str);
} }
return map; if (flag) {
} map.put("flag", flag);
map.put("info", "数据删除成功!");
} else {
map.put("info", "数据删除失败!");
}
return map;
}
@RequestMapping("/addUser") @RequestMapping("/queryAllUser")
public void addUser(HttpServletRequest request,HttpServletResponse response,User user) { public Object queryAllUser() {
String result = ""; ModelAndView mv = new ModelAndView("admin/user/manage");
User user_in_session = (User) request.getSession().getAttribute("user_in_session"); return mv;
try { }
//新增用户初始化密码
user.setPassword(PasswordHash.createHash("111111"));
} catch (Exception e) {
throw new RuntimeException("新增用户初始化密码加密失败....", e);
}
user.setCreatorId(user_in_session.getId());
user.setCreator(user_in_session.getUsername());
user.setCreateTime(new Date());
if(null == user.getUserType()){
user.setUserType("back");
}
if(null == user.getCountStatus()){
user.setCountStatus(1);
}
boolean flag = userService.addUser(user);
if(flag){
result = "{ \"flag\": "+ flag +", \"info\": \"数据保存成功!\" }";
}else {
result = "{ \"flag\": "+ flag +", \"info\": \"数据保存失败!\" }";
}
try {
response.setContentType("text/html");
response.getWriter().write(result);
} catch (IOException e) {
e.printStackTrace();
}
}
@RequestMapping("/edit/{id}") @RequestMapping("/getAllUsers")
@ResponseBody @ResponseBody
public Object editUser(@PathVariable long id, User user) { public Object getAllUsers(HttpServletRequest request) {
Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> map = new HashMap<String, Object>();
User user1 = userService.getUser(id); PageRequest pageRequest = this.getPage(request);
boolean flag = false; String userName = request.getParameter("userName");
if(null != user.getAge()){ String userType = request.getParameter("userType");
user1.setAge(user.getAge()); StringBuffer hql = new StringBuffer("from User where 1=1");
} if (null == userName && null == userType) {
if(null != user.getCountStatus()){ hql.append(" order by createTime desc");
user1.setCountStatus(user.getCountStatus()); } else {
} if (null != userName && !"".equals(userName)) {
if(null != user.getCompany()){ hql.append(" and userName like '%" + userName + "%'");
user1.setCompany(user.getCompany()); }
} if (null != userType && !"".equals(userType)) {
if(null != user.getEmail()){ hql.append(" and userType ='" + userType + "'");
user1.setEmail(user.getEmail()); }
} hql.append(" order by createTime desc");
if(null != user.getLoginName()){ }
user1.setLoginName(user.getLoginName()); Page<User> users = userService.queryPage(pageRequest, hql.toString());
} return userService.convert(users);
if(null != user.getSex()){ }
user1.setSex(user.getSex());
}
if(null != user.getTelphone()){
user1.setTelphone(user.getTelphone());
}
if(null != user.getUsername()){
user1.setUsername(user.getUsername());
}
if(null != user.getUserType()){
user1.setUserType(user.getUserType());
}
flag = userService.updateUser(user1);
if (flag) {
map.put("success", flag);
map.put("info", "修改用户数据成功!");
} else {
map.put("info", "修改用户数据失败...");
}
return map;
}
@RequestMapping("/getUserById/{id}") @RequestMapping("/get/{id}")
@ResponseBody @ResponseBody
public User getUserById(@PathVariable long id) { public Object get(@PathVariable long id) {
User user = userService.getUser(id); if (id != 0) {
return user;
}
@RequestMapping("/deleteUser")
@ResponseBody
public Object deleteUser(HttpServletRequest request) {
Map<String, Object> map = new HashMap<String, Object>();
String jsonIds = request.getParameter("ids");
JSONArray jsonArray = JSONArray.fromObject(jsonIds);
Object[] ids = jsonArray.toArray();
boolean flag = false;
for(Object str : ids){
flag = userService.deleteUser((Integer) str);
}
if(flag){
map.put("flag", flag);
map.put("info", "数据删除成功!");
}else {
map.put("info", "数据删除失败!");
}
return map;
}
@RequestMapping("/queryAllUser") UserGroup usergroup = new UserGroup();
public Object queryAllUser() { Set<Role> roles = new HashSet<Role>();
ModelAndView mv = new ModelAndView("admin/user/manage"); Set<User> users = new HashSet<User>();
return mv; roles.add(roleDao.queryById(2L));
} users.add(userDao.queryById(1L));
usergroup.setRoles(roles);
usergroup.setUsers(users);
usergroup.setName("test usergroup 1");
orgService.save(usergroup);
@RequestMapping("/getAllUsers") UserGroup org = orgDao.queryById(2L);
@ResponseBody System.out.println(org);
public Object getAllUsers(HttpServletRequest request) { User user = userService.getUser(id);
Map<String, Object> map = new HashMap<String, Object>(); return user;
PageRequest pageRequest = this.getPage(request); }
String userName = request.getParameter("userName"); return "";
String userType = request.getParameter("userType"); }
StringBuffer hql = new StringBuffer("from User where 1=1");
if(null == userName && null == userType){
hql.append(" order by createTime desc");
}else {
if(null != userName && !"".equals(userName)){
hql.append(" and userName like '%" + userName + "%'");
}
if(null != userType && !"".equals(userType)){
hql.append(" and userType ='"+ userType +"'");
}
hql.append(" order by createTime desc");
}
Page<User> users = userService.queryPage(pageRequest,hql.toString());
return userService.convert(users);
}
@RequestMapping("/get/{id}") /**
@ResponseBody * 用户密码重置
public Object get(@PathVariable long id) { */
if (id != 0) { @RequestMapping("/resetPass")
@ResponseBody
public Object resetPass(HttpServletRequest request, HttpServletResponse response) {
Map result = new HashMap();
String id = request.getParameter("userId");
User user = userService.getUser(Long.valueOf(id));
try {
user.setPassword(PasswordHash.createHash("111111"));
} catch (Exception e) {
throw new RuntimeException("重置用户密码加密失败....", e);
}
boolean b = userService.updateUser(user);
if (b) {
result.put("flag", true);
} else {
result.put("flag", false);
}
return result;
}
UserGroup usergroup = new UserGroup(); /**
Set<Role> roles = new HashSet<Role>(); * 用户密码修改
Set<User> users = new HashSet<User>(); */
roles.add(roleDao.queryById(2L)); @RequestMapping("/changePass/{rePass}")
users.add(userDao.queryById(1L)); @ResponseBody
usergroup.setRoles(roles); public Object changePass(HttpServletRequest request, @PathVariable String rePass) {
usergroup.setUsers(users); Map result = new HashMap();
usergroup.setName("test usergroup 1"); User user = (User) request.getSession().getAttribute("user_in_session");
orgService.save(usergroup); try {
user.setPassword(PasswordHash.createHash(rePass));
} catch (Exception e) {
throw new RuntimeException("修改用户密码加密失败....", e);
}
boolean b = userService.updateUser(user);
if (b) {
result.put("flag", true);
result.put("info", "密码修改成功!");
} else {
result.put("flag", false);
}
return result;
}
UserGroup org = orgDao.queryById(2L); @RequestMapping("/getUsersList")
System.out.println(org); @ResponseBody
User user = userService.getUser(id); public Object getUsersList(HttpServletRequest request) {
return user; List<User> listBo = userService.getAllUsers();
} List list = new ArrayList();
return ""; if (null != listBo) {
} for (int i = 0; i < listBo.size(); i++) {
Map result = new HashMap();
/** result.put("id", listBo.get(i).getId());
* 用户密码重置 result.put("text", listBo.get(i).getUsername());
*/ list.add(result);
@RequestMapping("/resetPass") }
@ResponseBody }
public Object resetPass(HttpServletRequest request, HttpServletResponse response){ return list;
Map result = new HashMap(); }
String id = request.getParameter("userId");
User user = userService.getUser(Long.valueOf(id));
try {
user.setPassword(PasswordHash.createHash("111111"));
} catch (Exception e) {
throw new RuntimeException("重置用户密码加密失败....", e);
}
boolean b = userService.updateUser(user);
if(b){
result.put("flag", true);
}else {
result.put("flag", false);
}
return result;
}
/**
* 用户密码修改
*/
@RequestMapping("/changePass/{rePass}")
@ResponseBody
public Object changePass(HttpServletRequest request,@PathVariable String rePass){
Map result = new HashMap();
User user = (User) request.getSession().getAttribute("user_in_session");
try {
user.setPassword(PasswordHash.createHash(rePass));
} catch (Exception e) {
throw new RuntimeException("修改用户密码加密失败....", e);
}
boolean b = userService.updateUser(user);
if(b){
result.put("flag", true);
result.put("info", "密码修改成功!");
}else {
result.put("flag", false);
}
return result;
}
@RequestMapping("/getUsersList")
@ResponseBody
public Object getUsersList(HttpServletRequest request){
List<User> listBo = userService.getAllUsers();
List list = new ArrayList();
if(null != listBo){
for(int i=0;i<listBo.size();i++){
Map result = new HashMap();
result.put("id", listBo.get(i).getId());
result.put("text", listBo.get(i).getUsername());
list.add(result);
}
}
return list;
}
} }
package org.ccpit.base.user; package org.ccpit.base.user;
import java.util.Set;
import org.ccpit.base.dao.BaseDao; import org.ccpit.base.dao.BaseDao;
import org.ccpit.base.role.Role; import org.ccpit.base.role.Role;
import org.ccpit.base.usergroup.UserGroupDao; import org.ccpit.base.usergroup.UserGroupDao;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import java.util.Set;
/** /**
* 用户实体操作类 * 用户实体操作类
* Created by sqp on 2015/9/5. * Created by sqp on 2015/9/5.
*/ */
@Repository @Repository
public class UserDao extends BaseDao<User>{ public class UserDao extends BaseDao<User> {
@Autowired @Autowired
private UserGroupDao userGroupDao; private UserGroupDao userGroupDao;
public User getUserByLoginName(String loginName){ public User getUserByLoginName(String loginName) {
String hql = "from User where loginName = ?"; String hql = "from User where loginName = ?";
User user = super.findUnique(hql, new String[]{loginName}); User user = super.findUnique(hql, new String[]{loginName});
return user; return user;
} }
/** /**
...@@ -30,20 +30,21 @@ public class UserDao extends BaseDao<User>{ ...@@ -30,20 +30,21 @@ public class UserDao extends BaseDao<User>{
* @param role * @param role
* @return * @return
*/ */
public boolean canUserOrInGroup(User user,Role role){ public boolean canUserOrInGroup(User user, Role role) {
boolean can = canUser(user, role); boolean can = canUser(user, role);
if (!can){ if (!can) {
can = userGroupDao.canUserInGroup(user,role); can = userGroupDao.canUserInGroup(user, role);
} }
return can; return can;
} }
/** /**
* 获取一个用户所拥有的所有角色,包括用户所在的组拥有的角色 * 获取一个用户所拥有的所有角色,包括用户所在的组拥有的角色
*
* @param user * @param user
* @return * @return
*/ */
public Set<Role> getUserRolesIncludeGroup(User user){ public Set<Role> getUserRolesIncludeGroup(User user) {
Set<Role> roles = user.getRoles(); Set<Role> roles = user.getRoles();
Set<Role> rolesInGroup = userGroupDao.getRolesForUser(user); Set<Role> rolesInGroup = userGroupDao.getRolesForUser(user);
roles.addAll(rolesInGroup); roles.addAll(rolesInGroup);
...@@ -52,11 +53,12 @@ public class UserDao extends BaseDao<User>{ ...@@ -52,11 +53,12 @@ public class UserDao extends BaseDao<User>{
/** /**
* 判断用户是否具有某个角色 * 判断用户是否具有某个角色
*
* @param user * @param user
* @param role * @param role
* @return * @return
*/ */
public boolean canUser(User user,Role role){ public boolean canUser(User user, Role role) {
return user.getRoles().contains(role); return user.getRoles().contains(role);
} }
......
package org.ccpit.base.user; package org.ccpit.base.user;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.transaction.Transactional;
import org.ccpit.base.controller.Convert; import org.ccpit.base.controller.Convert;
import org.ccpit.base.controller.Page; import org.ccpit.base.controller.Page;
import org.ccpit.base.controller.PageBo; import org.ccpit.base.controller.PageBo;
...@@ -18,49 +9,54 @@ import org.ccpit.base.role.RoleDao; ...@@ -18,49 +9,54 @@ import org.ccpit.base.role.RoleDao;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import javax.transaction.Transactional;
import java.text.SimpleDateFormat;
import java.util.*;
/** /**
* Created by sqp on 2015/9/5. * Created by sqp on 2015/9/5.
*/ */
@Repository @Repository
@Transactional @Transactional
public class UserService { public class UserService {
private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd MM:hh:ss"); private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd MM:hh:ss");
@Autowired @Autowired
private UserDao userDao; private UserDao userDao;
@Autowired @Autowired
private RoleDao roleDao; private RoleDao roleDao;
public List<User> getAllUsers(){ public List<User> getAllUsers() {
return userDao.queryAll(); return userDao.queryAll();
} }
public User getUserByLoginName(String loginName){ public User getUserByLoginName(String loginName) {
return userDao.getUserByLoginName(loginName); return userDao.getUserByLoginName(loginName);
} }
public boolean addUser(User user){ public boolean addUser(User user) {
return userDao.save(user); return userDao.save(user);
} }
public boolean updateUser(User user){ public boolean updateUser(User user) {
return userDao.update(user); return userDao.update(user);
} }
public boolean deleteUser(long id){ public boolean deleteUser(long id) {
return userDao.deleteById(id); return userDao.deleteById(id);
} }
public Page<User> queryPage(PageRequest pr){ public Page<User> queryPage(PageRequest pr) {
Page<User> page = userDao.findPage(pr, "from " + User.class.getName(), new String[]{}); Page<User> page = userDao.findPage(pr, "from " + User.class.getName(), new String[]{});
return page; return page;
} }
public Page<User> queryPage(PageRequest pr,String hql){ public Page<User> queryPage(PageRequest pr, String hql) {
Page<User> page = userDao.findPage(pr, hql, new String[]{}); Page<User> page = userDao.findPage(pr, hql, new String[]{});
return page; return page;
} }
public User getUser(long id){
public User getUser(long id) {
return userDao.queryById(id); return userDao.queryById(id);
} }
...@@ -71,80 +67,84 @@ public class UserService { ...@@ -71,80 +67,84 @@ public class UserService {
* @param role * @param role
* @return * @return
*/ */
public boolean canUserOrInGroup(User user,Role role){ public boolean canUserOrInGroup(User user, Role role) {
return userDao.canUserOrInGroup(user, role); return userDao.canUserOrInGroup(user, role);
} }
/** /**
* 获取一个用户的所有角色 * 获取一个用户的所有角色
*
* @param user * @param user
* @return * @return
*/ */
public Set<Role> getUserRoles(User user){ public Set<Role> getUserRoles(User user) {
User user1 = userDao.queryById(user.getId()); User user1 = userDao.queryById(user.getId());
return user1.getRoles(); return user1.getRoles();
} }
/** /**
* 获取一个用户所拥有的所有角色,包括用户所在的组拥有的角色 * 获取一个用户所拥有的所有角色,包括用户所在的组拥有的角色
*
* @param user * @param user
* @return * @return
*/ */
public Set<Role> getUserRolesIncludeGroup(User user){ public Set<Role> getUserRolesIncludeGroup(User user) {
return userDao.getUserRolesIncludeGroup(user); return userDao.getUserRolesIncludeGroup(user);
} }
public boolean saveUserRoles(User user,Long[] ids){ public boolean saveUserRoles(User user, Long[] ids) {
Set<Role> roles = new HashSet<Role>(); Set<Role> roles = new HashSet<Role>();
for (long id:ids){ for (long id : ids) {
roles.add(roleDao.queryById(id)); roles.add(roleDao.queryById(id));
} }
return saveUserRoles(user, roles); return saveUserRoles(user, roles);
} }
public boolean saveUserRoles(User user,Set<Role> roleSet){
public boolean saveUserRoles(User user, Set<Role> roleSet) {
boolean success = false; boolean success = false;
try { try {
user.getRoles().clear(); user.getRoles().clear();
boolean b = userDao.update(user); boolean b = userDao.update(user);
if(b){ if (b) {
User user1 = userDao.queryById(user.getId()); User user1 = userDao.queryById(user.getId());
user1.setRoles(roleSet); user1.setRoles(roleSet);
success = userDao.save(user1); success = userDao.save(user1);
} }
}catch (Exception e){ } catch (Exception e) {
success = false; success = false;
} }
return success; return success;
} }
public Map<String,Object> convertToMap(User User){ public Map<String, Object> convertToMap(User User) {
Map<String,Object> map = new HashMap<String, Object>(); Map<String, Object> map = new HashMap<String, Object>();
if (User==null){ if (User == null) {
return map; return map;
} }
Set<Role> roleSet = User.getRoles(); Set<Role> roleSet = User.getRoles();
String roles = ""; String roles = "";
if(null != roleSet){ if (null != roleSet) {
if(roleSet.size()>0){ if (roleSet.size() > 0) {
for(Role role : roleSet){ for (Role role : roleSet) {
roles += role.getRoleName()+","; roles += role.getRoleName() + ",";
} }
roles = roles.substring(0, roles.length()-1); roles = roles.substring(0, roles.length() - 1);
} }
} }
map.put("id",User.getId()); map.put("id", User.getId());
map.put("createTime",null == User.getCreateTime()? "": sdf.format(User.getCreateTime())); map.put("createTime", null == User.getCreateTime() ? "" : sdf.format(User.getCreateTime()));
map.put("creator", User.getCreator()); map.put("creator", User.getCreator());
map.put("username",User.getUsername()); map.put("username", User.getUsername());
map.put("loginName",User.getLoginName()); map.put("loginName", User.getLoginName());
map.put("countStatus", 1 == User.getCountStatus()?"有效":"无效"); map.put("countStatus", 1 == User.getCountStatus() ? "有效" : "无效");
map.put("loginCount", User.getLoginCount()); map.put("loginCount", User.getLoginCount());
map.put("company", User.getCompany()); map.put("company", User.getCompany());
map.put("userType","back".equals(User.getUserType())?"后台用户":"非后台用户"); map.put("userType", "back".equals(User.getUserType()) ? "后台用户" : "非后台用户");
map.put("roles", roles); map.put("roles", roles);
return map; return map;
} }
public PageBo<User> convert(Page<User> page){ public PageBo<User> convert(Page<User> page) {
return new PageBo<User>(page, new Convert<User>() { return new PageBo<User>(page, new Convert<User>() {
@Override @Override
public Map<String, Object> convert(User obj) { public Map<String, Object> convert(User obj) {
......
package org.ccpit.base.utils; package org.ccpit.base.utils;
import java.security.MessageDigest;
import javax.crypto.Cipher; import javax.crypto.Cipher;
import javax.crypto.KeyGenerator; import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey; import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec; import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
/** /**
* @Description �����㷨 * @Description �����㷨
* @Version V0.1 * @Version V0.1
* @Author zmc * @Author zmc
* @Date 2015��4��3�� ����3:07:18 JDK�汾��sun jdk 1.6 * @Date 2015��4��3�� ����3:07:18 JDK�汾��sun jdk 1.6
* ���¼�¼****************************** �汾�� <�汾��> �޸����ڣ� <����> �޸��ˣ� <�޸�������> * ���¼�¼****************************** �汾�� <�汾��> �޸����ڣ� <����> �޸��ˣ� <�޸�������>
* �޸����ݣ� <�޸���������> * �޸����ݣ� <�޸���������>
********************************************************************** * *********************************************************************
*
*/ */
public class CryptUtil { public class CryptUtil {
private static String DES_Algorithm = "DESede"; private static String DES_Algorithm = "DESede";
private static String MD5_Algorithm = "MD5"; private static String MD5_Algorithm = "MD5";
private static KeyGenerator keygen; private static KeyGenerator keygen;
private static SecretKey deskey; private static SecretKey deskey;
public static SecretKey genDESKey(byte[] keyByte) throws Exception { public static SecretKey genDESKey(byte[] keyByte) throws Exception {
SecretKey k = null; SecretKey k = null;
k = new SecretKeySpec(keyByte, DES_Algorithm); k = new SecretKeySpec(keyByte, DES_Algorithm);
return k; return k;
} }
public static SecretKey genDESKey(String keyStr) throws Exception { public static SecretKey genDESKey(String keyStr) throws Exception {
SecretKey k = null; SecretKey k = null;
k = new SecretKeySpec(keyStr.getBytes(), DES_Algorithm); k = new SecretKeySpec(keyStr.getBytes(), DES_Algorithm);
return k; return k;
} }
public static SecretKey genDESKey() throws Exception { public static SecretKey genDESKey() throws Exception {
if (keygen == null) { if (keygen == null) {
keygen = KeyGenerator.getInstance(DES_Algorithm); keygen = KeyGenerator.getInstance(DES_Algorithm);
deskey = keygen.generateKey(); deskey = keygen.generateKey();
} }
return deskey; return deskey;
} }
public static byte[] desEncrypt(SecretKey key, byte[] src) throws Exception { public static byte[] desEncrypt(SecretKey key, byte[] src) throws Exception {
Cipher cipher = Cipher.getInstance("DESede"); Cipher cipher = Cipher.getInstance("DESede");
cipher.init(1, key); cipher.init(1, key);
return cipher.doFinal(src); return cipher.doFinal(src);
} }
public static String desEncrypt(SecretKey key, String src) throws Exception { public static String desEncrypt(SecretKey key, String src) throws Exception {
return new String(desEncrypt(key, src.getBytes())); return new String(desEncrypt(key, src.getBytes()));
} }
public static byte[] desEncrypt(byte[] src) throws Exception { public static byte[] desEncrypt(byte[] src) throws Exception {
if (keygen == null) { if (keygen == null) {
keygen = KeyGenerator.getInstance(DES_Algorithm); keygen = KeyGenerator.getInstance(DES_Algorithm);
deskey = keygen.generateKey(); deskey = keygen.generateKey();
} }
Cipher cipher = Cipher.getInstance(DES_Algorithm); Cipher cipher = Cipher.getInstance(DES_Algorithm);
cipher.init(1, deskey); cipher.init(1, deskey);
return cipher.doFinal(src); return cipher.doFinal(src);
} }
public static String desEncrypt(String src) throws Exception { public static String desEncrypt(String src) throws Exception {
return new String(desEncrypt(src.getBytes())); return new String(desEncrypt(src.getBytes()));
} }
public static byte[] desDecrypt(SecretKey key, byte[] crypt) public static byte[] desDecrypt(SecretKey key, byte[] crypt)
throws Exception { throws Exception {
Cipher cipher = Cipher.getInstance(DES_Algorithm); Cipher cipher = Cipher.getInstance(DES_Algorithm);
cipher.init(2, key); cipher.init(2, key);
return cipher.doFinal(crypt); return cipher.doFinal(crypt);
} }
public static String desDecrypt(SecretKey key, String crypt) public static String desDecrypt(SecretKey key, String crypt)
throws Exception { throws Exception {
return new String(desDecrypt(key, crypt.getBytes())); return new String(desDecrypt(key, crypt.getBytes()));
} }
public static byte[] desDecrypt(byte[] crypt) throws Exception { public static byte[] desDecrypt(byte[] crypt) throws Exception {
if (keygen == null) { if (keygen == null) {
keygen = KeyGenerator.getInstance(DES_Algorithm); keygen = KeyGenerator.getInstance(DES_Algorithm);
deskey = keygen.generateKey(); deskey = keygen.generateKey();
} }
Cipher cipher = Cipher.getInstance(DES_Algorithm); Cipher cipher = Cipher.getInstance(DES_Algorithm);
cipher.init(2, deskey); cipher.init(2, deskey);
return cipher.doFinal(crypt); return cipher.doFinal(crypt);
} }
public static String desDecrypt(String crypt) throws Exception { public static String desDecrypt(String crypt) throws Exception {
return new String(desDecrypt(crypt.getBytes())); return new String(desDecrypt(crypt.getBytes()));
} }
public static String md5Encrypt(String src) throws Exception { public static String md5Encrypt(String src) throws Exception {
byte[] md5 = md5Digest(src.getBytes("utf-8")); byte[] md5 = md5Digest(src.getBytes("utf-8"));
return encodeHex(md5); return encodeHex(md5);
} }
private static String md5Digest(String src) throws Exception { private static String md5Digest(String src) throws Exception {
return new String(md5Digest(src.getBytes("utf-8"))); return new String(md5Digest(src.getBytes("utf-8")));
} }
private static byte[] md5Digest(byte[] src) throws Exception { private static byte[] md5Digest(byte[] src) throws Exception {
MessageDigest alg = MessageDigest.getInstance(MD5_Algorithm); MessageDigest alg = MessageDigest.getInstance(MD5_Algorithm);
return alg.digest(src); return alg.digest(src);
} }
private static byte[] md5Digest(byte[] src, byte[] key) throws Exception { private static byte[] md5Digest(byte[] src, byte[] key) throws Exception {
MessageDigest alg = MessageDigest.getInstance(MD5_Algorithm); MessageDigest alg = MessageDigest.getInstance(MD5_Algorithm);
alg.update(key); alg.update(key);
return alg.digest(src); return alg.digest(src);
} }
private static String encodeHex(byte[] bytes) { private static String encodeHex(byte[] bytes) {
StringBuffer buf = new StringBuffer(bytes.length * 2); StringBuffer buf = new StringBuffer(bytes.length * 2);
for (int i = 0; i < bytes.length; i++) { for (int i = 0; i < bytes.length; i++) {
if ((bytes[i] & 0xFF) < 16) { if ((bytes[i] & 0xFF) < 16) {
buf.append("0"); buf.append("0");
} }
buf.append(Long.toString(bytes[i] & 0xFF, 16)); buf.append(Long.toString(bytes[i] & 0xFF, 16));
} }
return buf.toString(); return buf.toString();
} }
/*public static String base64Encode(String src) { /*public static String base64Encode(String src) {
BASE64Encoder encoder = new BASE64Encoder(); BASE64Encoder encoder = new BASE64Encoder();
......
...@@ -6,7 +6,6 @@ package org.ccpit.base.utils; ...@@ -6,7 +6,6 @@ package org.ccpit.base.utils;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.ccpit.base.modol.EscapeHTML; import org.ccpit.base.modol.EscapeHTML;
import org.ccpit.base.modol.EscapeSql;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Method; import java.lang.reflect.Method;
...@@ -65,12 +64,13 @@ public class HtmlEscapeUtil<T> { ...@@ -65,12 +64,13 @@ public class HtmlEscapeUtil<T> {
/** /**
* Escape the Sql with the annotation * Escape the Sql with the annotation
*
* @param t * @param t
* @return * @return
*/ */
public T escape(T t){ public T escape(T t) {
EscapeHTML annotation = t.getClass().getAnnotation(EscapeHTML.class); EscapeHTML annotation = t.getClass().getAnnotation(EscapeHTML.class);
if (annotation!=null){ if (annotation != null) {
encode(t); encode(t);
except(annotation.except()); except(annotation.except());
execute(); execute();
......
This source diff could not be displayed because it is too large. You can view the blob instead.
package org.ccpit.base.utils; package org.ccpit.base.utils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.ccpit.base.user.User;
import javax.mail.*; import javax.mail.*;
import javax.mail.internet.InternetAddress; import javax.mail.internet.InternetAddress;
...@@ -26,8 +24,8 @@ public class MailSender { ...@@ -26,8 +24,8 @@ public class MailSender {
public static String HOST; public static String HOST;
private static final Logger logger = Logger.getLogger(MailSender.class); private static final Logger logger = Logger.getLogger(MailSender.class);
static{ static {
Map<String,String> configMap = ReadConfigUtil.getPlatformConfig(); Map<String, String> configMap = ReadConfigUtil.getPlatformConfig();
USERNAME = configMap.get("email.name"); USERNAME = configMap.get("email.name");
PASSWORD = configMap.get("email.password"); PASSWORD = configMap.get("email.password");
HOST = configMap.get("email.host"); HOST = configMap.get("email.host");
...@@ -35,18 +33,20 @@ public class MailSender { ...@@ -35,18 +33,20 @@ public class MailSender {
/** /**
* 发送邮件 * 发送邮件
*
* @param targetAddress 收件人 * @param targetAddress 收件人
* @param subject 主题 * @param subject 主题
* @param body 内容 * @param body 内容
* @return 发送成功 * @return 发送成功
*/ */
public static boolean send(String targetAddress,String subject,String body){ public static boolean send(String targetAddress, String subject, String body) {
EmailBody emailBody = new EmailBody(); EmailBody emailBody = new EmailBody();
emailBody.setContent(body); emailBody.setContent(body);
emailBody.setSubject(subject); emailBody.setSubject(subject);
emailBody.setSentDate(new Date()); emailBody.setSentDate(new Date());
return send(targetAddress,emailBody); return send(targetAddress, emailBody);
} }
/** /**
* 发送邮件 * 发送邮件
* *
...@@ -56,7 +56,7 @@ public class MailSender { ...@@ -56,7 +56,7 @@ public class MailSender {
* @param: @param mimeDTO 邮件部分参数 * @param: @param mimeDTO 邮件部分参数
* @return: boolean * @return: boolean
*/ */
public static boolean send(String targetAddress, EmailBody body){ public static boolean send(String targetAddress, EmailBody body) {
Properties props = new Properties(); Properties props = new Properties();
props.put("mail.pop.host", HOST); props.put("mail.pop.host", HOST);
props.setProperty("mail.pop.auth", "true"); props.setProperty("mail.pop.auth", "true");
...@@ -64,7 +64,7 @@ public class MailSender { ...@@ -64,7 +64,7 @@ public class MailSender {
props.put("mail.pop.password", PASSWORD); props.put("mail.pop.password", PASSWORD);
props.put("mail.pop.starttls.enable", "true"); props.put("mail.pop.starttls.enable", "true");
props.put("mail.transport.protocol", "POP3"); props.put("mail.transport.protocol", "POP3");
props.put("mail.pop.port",465); props.put("mail.pop.port", 465);
Session session = Session.getInstance(props, new PopupAuthenticator(USERNAME, PASSWORD)); Session session = Session.getInstance(props, new PopupAuthenticator(USERNAME, PASSWORD));
boolean success = false; boolean success = false;
...@@ -87,7 +87,7 @@ public class MailSender { ...@@ -87,7 +87,7 @@ public class MailSender {
logger.info("成功发送了邮件到" + targetAddress + " 主题:[" + body.getSubject() + "] 内容[" + body.getContent() + "]"); logger.info("成功发送了邮件到" + targetAddress + " 主题:[" + body.getSubject() + "] 内容[" + body.getContent() + "]");
} catch (Exception e) { } catch (Exception e) {
success = false; success = false;
logger.warn("到"+targetAddress+"的邮件发送失败,"+e); logger.warn("到" + targetAddress + "的邮件发送失败," + e);
// throw new RuntimeException("email send error",e); // throw new RuntimeException("email send error",e);
} }
return success; return success;
......
...@@ -5,25 +5,23 @@ ...@@ -5,25 +5,23 @@
* Package Name:org.ccpit.base.utils * Package Name:org.ccpit.base.utils
* Date:2015年10月23日下午2:10:48 * Date:2015年10月23日下午2:10:48
* Copyright (c) 2015, dingwei@ccpit.org All Rights Reserved. * Copyright (c) 2015, dingwei@ccpit.org All Rights Reserved.
*
*/ */
package org.ccpit.base.utils; package org.ccpit.base.utils;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.math.BigInteger; import java.math.BigInteger;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException; import java.security.spec.InvalidKeySpecException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
/** /**
* ClassName:PasswordHash <br/> * ClassName:PasswordHash <br/>
* Function: TODO ADD FUNCTION. <br/> * Function: TODO ADD FUNCTION. <br/>
* Reason: TODO ADD REASON. <br/> * Reason: TODO ADD REASON. <br/>
* Date: 2015年10月23日 下午2:10:48 <br/> * Date: 2015年10月23日 下午2:10:48 <br/>
* *
* @author dingwei * @author dingwei
* @version * @version
* @since JDK 1.6 * @since JDK 1.6
...@@ -31,198 +29,198 @@ import javax.crypto.spec.PBEKeySpec; ...@@ -31,198 +29,198 @@ import javax.crypto.spec.PBEKeySpec;
*/ */
public class PasswordHash { public class PasswordHash {
public static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA1"; public static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA1";
// The following constants may be changed without breaking existing hashes. // The following constants may be changed without breaking existing hashes.
public static final int SALT_BYTE_SIZE = 24; public static final int SALT_BYTE_SIZE = 24;
public static final int HASH_BYTE_SIZE = 24; public static final int HASH_BYTE_SIZE = 24;
public static final int PBKDF2_ITERATIONS = 1000; public static final int PBKDF2_ITERATIONS = 1000;
public static final int ITERATION_INDEX = 0; public static final int ITERATION_INDEX = 0;
public static final int SALT_INDEX = 1; public static final int SALT_INDEX = 1;
public static final int PBKDF2_INDEX = 2; public static final int PBKDF2_INDEX = 2;
/** /**
* Returns a salted PBKDF2 hash of the password. * Returns a salted PBKDF2 hash of the password.
* *
* @param password * @param password
* the password to hash * the password to hash
* @return a salted PBKDF2 hash of the password * @return a salted PBKDF2 hash of the password
*/ */
public static String createHash(String password) throws NoSuchAlgorithmException, InvalidKeySpecException { public static String createHash(String password) throws NoSuchAlgorithmException, InvalidKeySpecException {
return createHash(password.toCharArray()); return createHash(password.toCharArray());
} }
/** /**
* Returns a salted PBKDF2 hash of the password. * Returns a salted PBKDF2 hash of the password.
* *
* @param password * @param password
* the password to hash * the password to hash
* @return a salted PBKDF2 hash of the password * @return a salted PBKDF2 hash of the password
*/ */
public static String createHash(char[] password) throws NoSuchAlgorithmException, InvalidKeySpecException { public static String createHash(char[] password) throws NoSuchAlgorithmException, InvalidKeySpecException {
// Generate a random salt // Generate a random salt
SecureRandom random = new SecureRandom(); SecureRandom random = new SecureRandom();
byte[] salt = new byte[SALT_BYTE_SIZE]; byte[] salt = new byte[SALT_BYTE_SIZE];
random.nextBytes(salt); random.nextBytes(salt);
// Hash the password // Hash the password
byte[] hash = pbkdf2(password, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE); byte[] hash = pbkdf2(password, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE);
// format iterations:salt:hash // format iterations:salt:hash
return PBKDF2_ITERATIONS + ":" + toHex(salt) + ":" + toHex(hash); return PBKDF2_ITERATIONS + ":" + toHex(salt) + ":" + toHex(hash);
} }
/** /**
* Validates a password using a hash. * Validates a password using a hash.
* *
* @param password * @param password
* the password to check * the password to check
* @param correctHash * @param correctHash
* the hash of the valid password * the hash of the valid password
* @return true if the password is correct, false if not * @return true if the password is correct, false if not
*/ */
public static boolean validatePassword(String password, String correctHash) public static boolean validatePassword(String password, String correctHash)
throws NoSuchAlgorithmException, InvalidKeySpecException { throws NoSuchAlgorithmException, InvalidKeySpecException {
return validatePassword(password.toCharArray(), correctHash); return validatePassword(password.toCharArray(), correctHash);
} }
/** /**
* Validates a password using a hash. * Validates a password using a hash.
* *
* @param password * @param password
* the password to check * the password to check
* @param correctHash * @param correctHash
* the hash of the valid password * the hash of the valid password
* @return true if the password is correct, false if not * @return true if the password is correct, false if not
*/ */
public static boolean validatePassword(char[] password, String correctHash) public static boolean validatePassword(char[] password, String correctHash)
throws NoSuchAlgorithmException, InvalidKeySpecException { throws NoSuchAlgorithmException, InvalidKeySpecException {
// Decode the hash into its parameters // Decode the hash into its parameters
String[] params = correctHash.split(":"); String[] params = correctHash.split(":");
if (params.length <= 1) { if (params.length <= 1) {
return false; return false;
} }
int iterations = Integer.parseInt(params[ITERATION_INDEX]); int iterations = Integer.parseInt(params[ITERATION_INDEX]);
byte[] salt = fromHex(params[SALT_INDEX]); byte[] salt = fromHex(params[SALT_INDEX]);
byte[] hash = fromHex(params[PBKDF2_INDEX]); byte[] hash = fromHex(params[PBKDF2_INDEX]);
// Compute the hash of the provided password, using the same salt, // Compute the hash of the provided password, using the same salt,
// iteration count, and hash length // iteration count, and hash length
byte[] testHash = pbkdf2(password, salt, iterations, hash.length); byte[] testHash = pbkdf2(password, salt, iterations, hash.length);
// Compare the hashes in constant time. The password is correct if // Compare the hashes in constant time. The password is correct if
// both hashes match. // both hashes match.
return slowEquals(hash, testHash); return slowEquals(hash, testHash);
} }
/** /**
* Compares two byte arrays in length-constant time. This comparison method * Compares two byte arrays in length-constant time. This comparison method
* is used so that password hashes cannot be extracted from an on-line * is used so that password hashes cannot be extracted from an on-line
* system using a timing attack and then attacked off-line. * system using a timing attack and then attacked off-line.
* *
* @param a * @param a
* the first byte array * the first byte array
* @param b * @param b
* the second byte array * the second byte array
* @return true if both byte arrays are the same, false if not * @return true if both byte arrays are the same, false if not
*/ */
private static boolean slowEquals(byte[] a, byte[] b) { private static boolean slowEquals(byte[] a, byte[] b) {
int diff = a.length ^ b.length; int diff = a.length ^ b.length;
for (int i = 0; i < a.length && i < b.length; i++) for (int i = 0; i < a.length && i < b.length; i++)
diff |= a[i] ^ b[i]; diff |= a[i] ^ b[i];
return diff == 0; return diff == 0;
} }
/** /**
* Computes the PBKDF2 hash of a password. * Computes the PBKDF2 hash of a password.
* *
* @param password * @param password
* the password to hash. * the password to hash.
* @param salt * @param salt
* the salt * the salt
* @param iterations * @param iterations
* the iteration count (slowness factor) * the iteration count (slowness factor)
* @param bytes * @param bytes
* the length of the hash to compute in bytes * the length of the hash to compute in bytes
* @return the PBDKF2 hash of the password * @return the PBDKF2 hash of the password
*/ */
private static byte[] pbkdf2(char[] password, byte[] salt, int iterations, private static byte[] pbkdf2(char[] password, byte[] salt, int iterations,
int bytes) throws NoSuchAlgorithmException, InvalidKeySpecException { int bytes) throws NoSuchAlgorithmException, InvalidKeySpecException {
PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8); PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8);
SecretKeyFactory skf = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM); SecretKeyFactory skf = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM);
return skf.generateSecret(spec).getEncoded(); return skf.generateSecret(spec).getEncoded();
} }
/** /**
* Converts a string of hexadecimal characters into a byte array. * Converts a string of hexadecimal characters into a byte array.
* *
* @param hex * @param hex
* the hex string * the hex string
* @return the hex string decoded into a byte array * @return the hex string decoded into a byte array
*/ */
private static byte[] fromHex(String hex) { private static byte[] fromHex(String hex) {
byte[] binary = new byte[hex.length() / 2]; byte[] binary = new byte[hex.length() / 2];
for (int i = 0; i < binary.length; i++) { for (int i = 0; i < binary.length; i++) {
binary[i] = (byte) Integer.parseInt( binary[i] = (byte) Integer.parseInt(
hex.substring(2 * i, 2 * i + 2), 16); hex.substring(2 * i, 2 * i + 2), 16);
} }
return binary; return binary;
} }
/** /**
* Converts a byte array into a hexadecimal string. * Converts a byte array into a hexadecimal string.
* *
* @param array * @param array
* the byte array to convert * the byte array to convert
* @return a length*2 character string encoding the byte array * @return a length*2 character string encoding the byte array
*/ */
private static String toHex(byte[] array) { private static String toHex(byte[] array) {
BigInteger bi = new BigInteger(1, array); BigInteger bi = new BigInteger(1, array);
String hex = bi.toString(16); String hex = bi.toString(16);
int paddingLength = (array.length * 2) - hex.length(); int paddingLength = (array.length * 2) - hex.length();
if (paddingLength > 0) if (paddingLength > 0)
return String.format("%0" + paddingLength + "d", 0) + hex; return String.format("%0" + paddingLength + "d", 0) + hex;
else else
return hex; return hex;
} }
/** /**
* Tests the basic functionality of the PasswordHash class * Tests the basic functionality of the PasswordHash class
* *
* @param args * @param args
* ignored * ignored
*/ */
public static void main(String[] args) { public static void main(String[] args) {
try { try {
// Print out 10 hashes // Print out 10 hashes
for (int i = 0; i < 10; i++) for (int i = 0; i < 10; i++)
System.out.println(PasswordHash.createHash("p\r\nassw0Rd!")); System.out.println(PasswordHash.createHash("p\r\nassw0Rd!"));
// Test password validation // Test password validation
boolean failure = false; boolean failure = false;
System.out.println("Running tests..."); System.out.println("Running tests...");
for (int i = 0; i < 100; i++) { for (int i = 0; i < 100; i++) {
String password = "" + i; String password = "" + i;
String hash = createHash(password); String hash = createHash(password);
String secondHash = createHash(password); String secondHash = createHash(password);
if (hash.equals(secondHash)) { if (hash.equals(secondHash)) {
System.out.println("FAILURE: TWO HASHES ARE EQUAL!"); System.out.println("FAILURE: TWO HASHES ARE EQUAL!");
failure = true; failure = true;
} }
String wrongPassword = "" + (i + 1); String wrongPassword = "" + (i + 1);
if (validatePassword(wrongPassword, hash)) { if (validatePassword(wrongPassword, hash)) {
System.out.println("FAILURE: WRONG PASSWORD ACCEPTED!"); System.out.println("FAILURE: WRONG PASSWORD ACCEPTED!");
failure = true; failure = true;
} }
if (!validatePassword(password, hash)) { if (!validatePassword(password, hash)) {
System.out.println("FAILURE: GOOD PASSWORD NOT ACCEPTED!"); System.out.println("FAILURE: GOOD PASSWORD NOT ACCEPTED!");
failure = true; failure = true;
} }
} }
if (failure) if (failure)
System.out.println("TESTS FAILED!"); System.out.println("TESTS FAILED!");
else else
System.out.println("TESTS PASSED!"); System.out.println("TESTS PASSED!");
} catch (Exception ex) { } catch (Exception ex) {
System.out.println("ERROR: " + ex); System.out.println("ERROR: " + ex);
} }
} }
} }
...@@ -17,6 +17,7 @@ public class PopupAuthenticator extends Authenticator { ...@@ -17,6 +17,7 @@ public class PopupAuthenticator extends Authenticator {
this.username = user; this.username = user;
this.password = pass; this.password = pass;
} }
protected PasswordAuthentication getPasswordAuthentication() { protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password); return new PasswordAuthentication(username, password);
} }
......
package org.ccpit.base.utils; package org.ccpit.base.utils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InputStream; import java.io.InputStream;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Properties; import java.util.Properties;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* @Description TODO【用一句话描述该文件做什么】 * @Description TODO【用一句话描述该文件做什么】
* @Author dingwei * @Author dingwei
...@@ -42,7 +42,7 @@ public class ReadConfigUtil { ...@@ -42,7 +42,7 @@ public class ReadConfigUtil {
} }
if (properties != null) if (properties != null)
for (Enumeration en = properties.propertyNames(); en for (Enumeration en = properties.propertyNames(); en
.hasMoreElements();) { .hasMoreElements(); ) {
String key = (String) en.nextElement(); String key = (String) en.nextElement();
String value = properties.getProperty(key); String value = properties.getProperty(key);
......
...@@ -8,7 +8,6 @@ import org.apache.commons.lang.StringEscapeUtils; ...@@ -8,7 +8,6 @@ import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.ccpit.base.modol.EscapeSql; import org.ccpit.base.modol.EscapeSql;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.ArrayList; import java.util.ArrayList;
...@@ -103,18 +102,20 @@ public class SqlEscapeUtil<T> { ...@@ -103,18 +102,20 @@ public class SqlEscapeUtil<T> {
/** /**
* Escape the Sql with the annotation * Escape the Sql with the annotation
*
* @param t * @param t
* @return * @return
*/ */
public T escape(T t){ public T escape(T t) {
EscapeSql annotation = t.getClass().getAnnotation(EscapeSql.class); EscapeSql annotation = t.getClass().getAnnotation(EscapeSql.class);
if (annotation!=null){ if (annotation != null) {
encode(t); encode(t);
except(annotation.except()); except(annotation.except());
execute(); execute();
} }
return t; return t;
} }
/** /**
* 过滤方法 * 过滤方法
* *
......
...@@ -11,7 +11,6 @@ import org.springframework.context.ApplicationContextAware; ...@@ -11,7 +11,6 @@ import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
...@@ -68,7 +67,7 @@ public class UserRolesUtil implements ApplicationContextAware { ...@@ -68,7 +67,7 @@ public class UserRolesUtil implements ApplicationContextAware {
public Set<Role> getRoles(HttpServletRequest request, String scope) { public Set<Role> getRoles(HttpServletRequest request, String scope) {
Set<Role> roles = new HashSet<Role>(); Set<Role> roles = new HashSet<Role>();
Object object = request.getSession().getAttribute(scope); Object object = request.getSession().getAttribute(scope);
if(object==null) { if (object == null) {
initOrReload(request); initOrReload(request);
object = request.getSession().getAttribute(scope); object = request.getSession().getAttribute(scope);
} }
......
package org.ccpit.base.utils; package org.ccpit.base.utils;
import java.awt.Color;
import java.awt.Font; import javax.imageio.ImageIO;
import java.awt.Graphics2D; import java.awt.*;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.Random; import java.util.Random;
import javax.imageio.ImageIO;
/** /**
* 验证码生成器 * 验证码生成器
* @author dsna
* *
* @author dsna
*/ */
public class ValidateCode { public class ValidateCode {
// 图片的宽度。 // 图片的宽度。
private int width = 160; private int width = 160;
// 图片的高度。 // 图片的高度。
private int height = 40; private int height = 40;
// 验证码字符个数 // 验证码字符个数
private int codeCount = 4; private int codeCount = 4;
// 验证码干扰线数 // 验证码干扰线数
private int lineCount = 80; private int lineCount = 80;
// 验证码 // 验证码
private String code = null; private String code = null;
// 验证码图片Buffer // 验证码图片Buffer
private BufferedImage buffImg=null; private BufferedImage buffImg = null;
private char[] codeSequence = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'M', 'N', 'P', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8'};
public ValidateCode() {
this.createCode();
}
/**
* @param width 图片宽
* @param height 图片高
*/
public ValidateCode(int width, int height) {
this.width = width;
this.height = height;
this.createCode();
}
/**
* @param width 图片宽
* @param height 图片高
* @param codeCount 字符个数
* @param lineCount 干扰线条数
*/
public ValidateCode(int width, int height, int codeCount, int lineCount) {
this.width = width;
this.height = height;
this.codeCount = codeCount;
this.lineCount = lineCount;
this.createCode();
}
public void createCode() {
int x = 0, fontHeight = 0, codeY = 0;
int red = 0, green = 0, blue = 0;
x = width / (codeCount + 2);//每个字符的宽度
fontHeight = height - 2;//字体的高度
codeY = height - 4;
// 图像buffer
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffImg.createGraphics();
// 生成随机数
Random random = new Random();
// 将图像填充为白色
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
// 创建字体
ImgFontByte imgFont = new ImgFontByte();
Font font = imgFont.getFont(fontHeight);
g.setFont(font);
for (int i = 0; i < lineCount; i++) {
int xs = random.nextInt(width);
int ys = random.nextInt(height);
int xe = xs + random.nextInt(width / 8);
int ye = ys + random.nextInt(height / 8);
red = random.nextInt(255);
green = random.nextInt(255);
blue = random.nextInt(255);
g.setColor(Color.white);
g.drawLine(xs, ys, xe, ye);
}
// randomCode记录随机产生的验证码
StringBuffer randomCode = new StringBuffer();
// 随机产生codeCount个字符的验证码。
for (int i = 0; i < codeCount; i++) {
String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
// 产生随机的颜色值,让输出的每个字符的颜色值都将不同。
red = random.nextInt(255);
green = random.nextInt(255);
blue = random.nextInt(255);
g.setColor(Color.black);
g.drawString(strRand, (i + 1) * x, codeY);
// 将产生的四个随机数组合在一起。
randomCode.append(strRand);
}
// 将四位数字的验证码保存到Session中。
code = randomCode.toString();
}
public void write(String path) throws IOException {
OutputStream sos = new FileOutputStream(path);
this.write(sos);
}
private char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', public void write(OutputStream sos) throws IOException {
'K', 'M', 'N', 'P', 'R', 'S', 'T', 'U', 'V', 'W', ImageIO.write(buffImg, "png", sos);
'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8' }; sos.close();
}
public ValidateCode() { public BufferedImage getBuffImg() {
this.createCode(); return buffImg;
} }
/** public String getCode() {
* return code;
* @param width 图片宽 }
* @param height 图片高
*/
public ValidateCode(int width,int height) {
this.width=width;
this.height=height;
this.createCode();
}
/**
*
* @param width 图片宽
* @param height 图片高
* @param codeCount 字符个数
* @param lineCount 干扰线条数
*/
public ValidateCode(int width,int height,int codeCount,int lineCount) {
this.width=width;
this.height=height;
this.codeCount=codeCount;
this.lineCount=lineCount;
this.createCode();
}
public void createCode() {
int x = 0,fontHeight=0,codeY=0;
int red = 0, green = 0, blue = 0;
x = width / (codeCount +2);//每个字符的宽度
fontHeight = height - 2;//字体的高度
codeY = height - 4;
// 图像buffer
buffImg = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffImg.createGraphics();
// 生成随机数
Random random = new Random();
// 将图像填充为白色
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
// 创建字体
ImgFontByte imgFont=new ImgFontByte();
Font font =imgFont.getFont(fontHeight);
g.setFont(font);
for (int i = 0; i < lineCount; i++) {
int xs = random.nextInt(width);
int ys = random.nextInt(height);
int xe = xs+random.nextInt(width/8);
int ye = ys+random.nextInt(height/8);
red = random.nextInt(255);
green = random.nextInt(255);
blue = random.nextInt(255);
g.setColor(Color.white);
g.drawLine(xs, ys, xe, ye);
}
// randomCode记录随机产生的验证码
StringBuffer randomCode = new StringBuffer();
// 随机产生codeCount个字符的验证码。
for (int i = 0; i < codeCount; i++) {
String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
// 产生随机的颜色值,让输出的每个字符的颜色值都将不同。
red = random.nextInt(255);
green = random.nextInt(255);
blue = random.nextInt(255);
g.setColor(Color.black);
g.drawString(strRand, (i + 1) * x, codeY);
// 将产生的四个随机数组合在一起。
randomCode.append(strRand);
}
// 将四位数字的验证码保存到Session中。
code=randomCode.toString();
}
public void write(String path) throws IOException {
OutputStream sos = new FileOutputStream(path);
this.write(sos);
}
public void write(OutputStream sos) throws IOException {
ImageIO.write(buffImg, "png", sos);
sos.close();
}
public BufferedImage getBuffImg() {
return buffImg;
}
public String getCode() {
return code;
}
} }
...@@ -5,8 +5,7 @@ ...@@ -5,8 +5,7 @@
* Package Name:org.ccpit.base.utils.mailUtil * Package Name:org.ccpit.base.utils.mailUtil
* Date:2015年11月19日上午10:50:34 * Date:2015年11月19日上午10:50:34
* Copyright (c) 2015, dingwei@ccpit.org All Rights Reserved. * Copyright (c) 2015, dingwei@ccpit.org All Rights Reserved.
* */
*/
package org.ccpit.base.utils.mailUtil; package org.ccpit.base.utils.mailUtil;
...@@ -17,131 +16,151 @@ import java.io.Serializable; ...@@ -17,131 +16,151 @@ import java.io.Serializable;
* Function: 邮件信息属性实体类. <br/> * Function: 邮件信息属性实体类. <br/>
* Reason: TODO ADD REASON. <br/> * Reason: TODO ADD REASON. <br/>
* Date: 2015年11月19日 上午10:50:34 <br/> * Date: 2015年11月19日 上午10:50:34 <br/>
* @author dingwei * @author dingwei
* @version * @version
* @since JDK 1.6 * @since JDK 1.6
* @see * @see
*/ */
public class Mail implements Serializable{ public class Mail implements Serializable {
/** /**
* serialVersionUID:TODO(用一句话描述这个变量表示什么). * serialVersionUID:TODO(用一句话描述这个变量表示什么).
* @since JDK 1.6 * @since JDK 1.6
*/ */
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public static final String ENCODEING = "utf-8"; public static final String ENCODEING = "utf-8";
/** /**
* 邮件服务器地址 * 邮件服务器地址
*/ */
private String host; private String host;
/** /**
* 协议 * 协议
*/ */
private String protocol; private String protocol;
/** /**
* 发件人地址 * 发件人地址
*/ */
private String sender; private String sender;
/** /**
* 收件人地址 * 收件人地址
*/ */
private String receiver; private String receiver;
/** /**
* 抄送人 * 抄送人
*/ */
private String copyTo; private String copyTo;
/** /**
* 发件人昵称 * 发件人昵称
*/ */
private String name; private String name;
/** /**
* 发件人邮箱账号 * 发件人邮箱账号
*/ */
private String emailCount; private String emailCount;
/** /**
* 发件人邮箱账号密码 * 发件人邮箱账号密码
*/ */
private String emailPassword; private String emailPassword;
/** /**
* 邮件主题 * 邮件主题
*/ */
private String mailTitle; private String mailTitle;
/** /**
* 邮件内容 * 邮件内容
*/ */
private String mailMessage; private String mailMessage;
//附件 //附件
private String affix; private String affix;
public String getHost() { public String getHost() {
return host; return host;
} }
public void setHost(String host) {
this.host = host; public void setHost(String host) {
} this.host = host;
public String getSender() { }
return sender;
} public String getSender() {
public void setSender(String sender) { return sender;
this.sender = sender; }
}
public String getReceiver() { public void setSender(String sender) {
return receiver; this.sender = sender;
} }
public void setReceiver(String receiver) {
this.receiver = receiver; public String getReceiver() {
} return receiver;
public String getName() { }
return name;
} public void setReceiver(String receiver) {
public void setName(String name) { this.receiver = receiver;
this.name = name; }
}
public String getEmailCount() { public String getName() {
return emailCount; return name;
} }
public void setEmailCount(String emailCount) {
this.emailCount = emailCount; public void setName(String name) {
} this.name = name;
public String getEmailPassword() { }
return emailPassword;
} public String getEmailCount() {
public void setEmailPassword(String emailPassword) { return emailCount;
this.emailPassword = emailPassword; }
}
public String getMailTitle() { public void setEmailCount(String emailCount) {
return mailTitle; this.emailCount = emailCount;
} }
public void setMailTitle(String mailTitle) {
this.mailTitle = mailTitle; public String getEmailPassword() {
} return emailPassword;
public String getMailMessage() { }
return mailMessage;
} public void setEmailPassword(String emailPassword) {
public void setMailMessage(String mailMessage) { this.emailPassword = emailPassword;
this.mailMessage = mailMessage; }
}
public String getProtocol() { public String getMailTitle() {
return protocol; return mailTitle;
} }
public void setProtocol(String protocol) {
this.protocol = protocol; public void setMailTitle(String mailTitle) {
} this.mailTitle = mailTitle;
public String getCopyTo() { }
return copyTo;
} public String getMailMessage() {
public void setCopyTo(String copyTo) { return mailMessage;
this.copyTo = copyTo; }
}
public String getAffix() { public void setMailMessage(String mailMessage) {
return affix; this.mailMessage = mailMessage;
} }
public void setAffix(String affix) {
this.affix = affix; public String getProtocol() {
} return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public String getCopyTo() {
return copyTo;
}
public void setCopyTo(String copyTo) {
this.copyTo = copyTo;
}
public String getAffix() {
return affix;
}
public void setAffix(String affix) {
this.affix = affix;
}
} }
...@@ -5,153 +5,142 @@ ...@@ -5,153 +5,142 @@
* Package Name:org.ccpit.base.utils.mailUtil * Package Name:org.ccpit.base.utils.mailUtil
* Date:2015年11月19日上午11:15:36 * Date:2015年11月19日上午11:15:36
* Copyright (c) 2015, dingwei@ccpit.org All Rights Reserved. * Copyright (c) 2015, dingwei@ccpit.org All Rights Reserved.
* */
*/
package org.ccpit.base.utils.mailUtil; package org.ccpit.base.utils.mailUtil;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File; import java.io.File;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.util.HashSet; import java.util.HashSet;
import java.util.Properties; import java.util.Properties;
import java.util.Set; import java.util.Set;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
/** /**
* ClassName:MailUtil <br/> * ClassName:MailUtil <br/>
* Function: 邮件发送工具类. <br/> * Function: 邮件发送工具类. <br/>
* Reason: TODO ADD REASON. <br/> * Reason: TODO ADD REASON. <br/>
* Date: 2015年11月19日 上午11:15:36 <br/> * Date: 2015年11月19日 上午11:15:36 <br/>
* @author dingwei * @author dingwei
* @version * @version
* @since JDK 1.6 * @since JDK 1.6
* @see * @see
*/ */
public class MailUtil { public class MailUtil {
public static boolean sendMail(Mail mail){ public static boolean sendMail(Mail mail) {
Properties properties = new Properties(); Properties properties = new Properties();
properties.setProperty("mail.host", mail.getHost()); properties.setProperty("mail.host", mail.getHost());
properties.setProperty("mail.transport.protocol", mail.getProtocol()); properties.setProperty("mail.transport.protocol", mail.getProtocol());
properties.setProperty("mail.smtp.auth", "true"); properties.setProperty("mail.smtp.auth", "true");
properties.put("mail.smtp.ssl.enable",true); properties.put("mail.smtp.ssl.enable", true);
//使用JavaMail发送邮件的5个步骤 //使用JavaMail发送邮件的5个步骤
//1、创建session //1、创建session
Session session = Session.getInstance(properties); Session session = Session.getInstance(properties);
//开启Session的debug模式,这样就可以查看到程序发送Email的运行状态 //开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
session.setDebug(true); session.setDebug(true);
boolean flag = false; boolean flag = false;
try { try {
//2、通过session得到transport对象 //2、通过session得到transport对象
final Transport transport = session.getTransport(); final Transport transport = session.getTransport();
//3、连上邮件服务器 //3、连上邮件服务器
transport.connect(mail.getHost(), mail.getEmailCount(), mail.getEmailPassword()); transport.connect(mail.getHost(), mail.getEmailCount(), mail.getEmailPassword());
//4、创建邮件 //4、创建邮件
final Message message = createMail(session,mail); final Message message = createMail(session, mail);
//5、发送邮件 //5、发送邮件
new Thread(){ new Thread() {
@Override @Override
public void run(){ public void run() {
for(int i=0;i<5;i++){ for (int i = 0; i < 5; i++) {
try { try {
transport.sendMessage(message, message.getAllRecipients()); transport.sendMessage(message, message.getAllRecipients());
transport.close(); transport.close();
break; break;
} catch (MessagingException e) { } catch (MessagingException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
}.start(); }.start();
flag = true; flag = true;
} catch (NoSuchProviderException e) { } catch (NoSuchProviderException e) {
e.printStackTrace(); e.printStackTrace();
flag = false; flag = false;
} catch (MessagingException e) { } catch (MessagingException e) {
flag = false; flag = false;
e.printStackTrace(); e.printStackTrace();
} }
return flag; return flag;
} }
public static MimeMessage createMail(Session session,Mail mail){ public static MimeMessage createMail(Session session, Mail mail) {
MimeMessage mimeMessage = new MimeMessage(session);//构建邮件体 MimeMessage mimeMessage = new MimeMessage(session);//构建邮件体
try { try {
if(null != mail.getSender()){ if (null != mail.getSender()) {
//设置发件人 //设置发件人
mimeMessage.setFrom(new InternetAddress(mail.getSender())); mimeMessage.setFrom(new InternetAddress(mail.getSender()));
} }
if(null != mail.getReceiver()){ if (null != mail.getReceiver()) {
String[] address = mail.getReceiver().split(";"); String[] address = mail.getReceiver().split(";");
InternetAddress[] addresses = new InternetAddress[address.length]; InternetAddress[] addresses = new InternetAddress[address.length];
for(int i=0; i<address.length;i++){ for (int i = 0; i < address.length; i++) {
addresses[i] = new InternetAddress(address[i]); addresses[i] = new InternetAddress(address[i]);
} }
//设置收件人 群发 //设置收件人 群发
mimeMessage.setRecipients(Message.RecipientType.TO, addresses); mimeMessage.setRecipients(Message.RecipientType.TO, addresses);
} }
if(null != mail.getCopyTo()){ if (null != mail.getCopyTo()) {
String[] address = mail.getReceiver().split(";"); String[] address = mail.getReceiver().split(";");
InternetAddress[] addresses = new InternetAddress[address.length]; InternetAddress[] addresses = new InternetAddress[address.length];
for(int i=0; i<address.length;i++){ for (int i = 0; i < address.length; i++) {
addresses[i] = new InternetAddress(address[i]); addresses[i] = new InternetAddress(address[i]);
} }
//抄送人 群发 //抄送人 群发
mimeMessage.setRecipients(Message.RecipientType.CC, addresses); mimeMessage.setRecipients(Message.RecipientType.CC, addresses);
} }
//邮件主题 //邮件主题
mimeMessage.setSubject(mail.getMailTitle()==null?"":mail.getMailTitle()); mimeMessage.setSubject(mail.getMailTitle() == null ? "" : mail.getMailTitle());
//创建邮件正文 为了避免邮件正文中文乱码问题,需要使用charset=UTF-8指明字符编码 //创建邮件正文 为了避免邮件正文中文乱码问题,需要使用charset=UTF-8指明字符编码
MimeBodyPart mimeBodyPart = new MimeBodyPart(); MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(mail.getMailMessage(), "text/html;charset=UTF-8"); mimeBodyPart.setContent(mail.getMailMessage(), "text/html;charset=UTF-8");
Set<MimeBodyPart> mimeBodyPartSet = new HashSet<MimeBodyPart>(); Set<MimeBodyPart> mimeBodyPartSet = new HashSet<MimeBodyPart>();
//创建邮件附件 //创建邮件附件
if(null != mail.getAffix()&&!"".equals(mail.getAffix())){ if (null != mail.getAffix() && !"".equals(mail.getAffix())) {
//多附件,附件地址之间以";"分隔 //多附件,附件地址之间以";"分隔
String[] affixs = mail.getAffix().split(";"); String[] affixs = mail.getAffix().split(";");
for(int i=0; i<affixs.length;i++){ for (int i = 0; i < affixs.length; i++) {
File file = new File(affixs[i]); File file = new File(affixs[i]);
MimeBodyPart mbp = new MimeBodyPart(); MimeBodyPart mbp = new MimeBodyPart();
DataHandler dh = new DataHandler(new FileDataSource(file)); DataHandler dh = new DataHandler(new FileDataSource(file));
mbp.setDataHandler(dh); mbp.setDataHandler(dh);
mbp.setFileName(MimeUtility.encodeText(dh.getName())); mbp.setFileName(MimeUtility.encodeText(dh.getName()));
mimeBodyPartSet.add(mbp); mimeBodyPartSet.add(mbp);
} }
} }
//创建容器描述数据关系 //创建容器描述数据关系
MimeMultipart mimeMultipart = new MimeMultipart(); MimeMultipart mimeMultipart = new MimeMultipart();
mimeMultipart.addBodyPart(mimeBodyPart); mimeMultipart.addBodyPart(mimeBodyPart);
if(null != mimeBodyPartSet && mimeBodyPartSet.size()>0){ if (null != mimeBodyPartSet && mimeBodyPartSet.size() > 0) {
for(MimeBodyPart mbp : mimeBodyPartSet){ for (MimeBodyPart mbp : mimeBodyPartSet) {
mimeMultipart.addBodyPart(mbp); mimeMultipart.addBodyPart(mbp);
} }
} }
mimeMultipart.setSubType("mixed"); mimeMultipart.setSubType("mixed");
mimeMessage.setContent(mimeMultipart); mimeMessage.setContent(mimeMultipart);
mimeMessage.saveChanges(); mimeMessage.saveChanges();
} catch (MessagingException e) { } catch (MessagingException e) {
e.printStackTrace(); e.printStackTrace();
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
e.printStackTrace(); e.printStackTrace();
} }
return mimeMessage; return mimeMessage;
} }
} }
...@@ -102,6 +102,7 @@ public class ExcelHelper { ...@@ -102,6 +102,7 @@ public class ExcelHelper {
cell22.setCellType(XSSFCell.CELL_TYPE_STRING); cell22.setCellType(XSSFCell.CELL_TYPE_STRING);
cell23.setCellType(XSSFCell.CELL_TYPE_STRING); cell23.setCellType(XSSFCell.CELL_TYPE_STRING);
cell24.setCellType(XSSFCell.CELL_TYPE_STRING); cell24.setCellType(XSSFCell.CELL_TYPE_STRING);
cell25.setCellType(XSSFCell.CELL_TYPE_STRING);
//在单元格中输入数据 //在单元格中输入数据
cell0.setCellValue("提交时间"); cell0.setCellValue("提交时间");
...@@ -129,6 +130,7 @@ public class ExcelHelper { ...@@ -129,6 +130,7 @@ public class ExcelHelper {
cell22.setCellValue("考试科目"); cell22.setCellValue("考试科目");
cell23.setCellValue("报名类型"); cell23.setCellValue("报名类型");
cell24.setCellValue("报名状态"); cell24.setCellValue("报名状态");
cell25.setCellValue("是否购买CDCS/CSDG考前培训");
cell0.setCellStyle(style); cell0.setCellStyle(style);
//循环导出数据到excel中 //循环导出数据到excel中
for (int i = 0; i < newsInfoList.size(); i++) { for (int i = 0; i < newsInfoList.size(); i++) {
...@@ -159,6 +161,9 @@ public class ExcelHelper { ...@@ -159,6 +161,9 @@ public class ExcelHelper {
rowi.createCell(21).setCellValue(registerInfo.getCity_en()); //CITY SELECT rowi.createCell(21).setCellValue(registerInfo.getCity_en()); //CITY SELECT
rowi.createCell(22).setCellValue(registerInfo.getSubject()); //考试科目 rowi.createCell(22).setCellValue(registerInfo.getSubject()); //考试科目
rowi.createCell(24).setCellValue(registerInfo.getRegisterStatus()); //报名状态 rowi.createCell(24).setCellValue(registerInfo.getRegisterStatus()); //报名状态
if(null != registerInfo.getIfBuyFee()){
rowi.createCell(25).setCellValue(1 == registerInfo.getIfBuyFee() ? "是":"否"); //是否购买CDCS/CSDG靠前培训
}
} }
try { try {
book.write(os); book.write(os);
......
...@@ -25,9 +25,7 @@ import org.ccpit.base.user.User; ...@@ -25,9 +25,7 @@ import org.ccpit.base.user.User;
import org.ccpit.business.phase.Phase; import org.ccpit.business.phase.Phase;
import org.ccpit.business.phase.PhaseService; import org.ccpit.business.phase.PhaseService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
......
...@@ -26,7 +26,7 @@ import org.springframework.format.annotation.DateTimeFormat; ...@@ -26,7 +26,7 @@ import org.springframework.format.annotation.DateTimeFormat;
* Reason: TODO ADD REASON. <br/> * Reason: TODO ADD REASON. <br/>
* Date: 2015年11月9日 下午5:33:37 <br/> * Date: 2015年11月9日 下午5:33:37 <br/>
* *
* @author sunqipeng * @author dingwei
* @see * @see
* @since JDK 1.6 * @since JDK 1.6
*/ */
...@@ -95,6 +95,10 @@ public class RegisterInfo implements Serializable { ...@@ -95,6 +95,10 @@ public class RegisterInfo implements Serializable {
*/ */
private Integer invoiceType; private Integer invoiceType;
/** /**
* 是否购买CDCS/CSDG考前培训 1 表示 是 | 2 表示否
*/
private Integer ifBuyFee;
/**
* 省 * 省
*/ */
private String province; private String province;
...@@ -721,5 +725,13 @@ public class RegisterInfo implements Serializable { ...@@ -721,5 +725,13 @@ public class RegisterInfo implements Serializable {
public void setDistrict(String district) { public void setDistrict(String district) {
this.district = district; this.district = district;
} }
public Integer getIfBuyFee() {
return ifBuyFee;
}
public void setIfBuyFee(Integer ifBuyFee) {
this.ifBuyFee = ifBuyFee;
}
} }
# jdbc.X # jdbc.X
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.driverClassName=com.mysql.jdbc.Driver
# 生产环境 docker 环境下一定要注意 将localhost 换成mysql # 生产环境 docker 环境下一定要注意 将localhost 换成mysql
jdbc.url=jdbc:mysql://mysql:3306/registration?createDatabaseIfNotExist=true&characterEncoding=utf-8 #jdbc.url=jdbc:mysql://mysql:3306/registration?createDatabaseIfNotExist=true&characterEncoding=utf-8
jdbc.user=root #jdbc.user=root
jdbc.pass=root #jdbc.pass=root
# 开发环境 # 开发环境
#jdbc.url=jdbc:mysql://localhost:3306/registration_0611?createDatabaseIfNotExist=true&characterEncoding=utf-8 jdbc.url=jdbc:mysql://localhost:3306/registration_0611?createDatabaseIfNotExist=true&characterEncoding=utf-8
#jdbc.user=ccpit jdbc.user=ccpit
#jdbc.pass=ccpit1516 jdbc.pass=ccpit1516
# hibernate.X # hibernate.X
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
......
/* create by dingwei 20211212 start */ /* create by dingwei 20211212 start */
alter table reg_subjectinfo add province varchar(100) Null; alter table reg_subjectinfo
alter table reg_subjectinfo add chengshi varchar(100) Null; add province varchar(100) Null;
alter table reg_subjectinfo add district varchar(100) Null; alter table reg_subjectinfo
add chengshi varchar(100) Null;
alter table reg_subjectinfo
add district varchar(100) Null;
/* create by dingwei 20211212 end */ /* create by dingwei 20211212 end */
/* create by dingwei 20210611 start */ /* create by dingwei 20210611 start */
delete from reg_subjectinfo where registerInfo_id = 12978; delete
delete from reg_subjectinfo where registerInfo_id = 12977; from reg_subjectinfo
delete from reg_subjectinfo where registerInfo_id = 12976; where registerInfo_id = 12978;
delete from reg_subjectinfo where registerInfo_id = 12975; delete
delete from reg_subjectinfo where registerInfo_id = 12969; from reg_subjectinfo
delete from reg_subjectinfo where registerInfo_id = 12974; where registerInfo_id = 12977;
delete from reg_subjectinfo where registerInfo_id = 12971; delete
delete from reg_subjectinfo where registerInfo_id = 12970; from reg_subjectinfo
delete from reg_subjectinfo where registerInfo_id = 12968; where registerInfo_id = 12976;
delete from reg_subjectinfo where registerInfo_id = 12967; delete
delete from reg_subjectinfo where registerInfo_id = 12964; from reg_subjectinfo
delete from reg_subjectinfo where registerInfo_id = 12956; where registerInfo_id = 12975;
delete from reg_subjectinfo where registerInfo_id = 12955; delete
delete from reg_subjectinfo where registerInfo_id = 12954; from reg_subjectinfo
delete from reg_subjectinfo where registerInfo_id = 12953; where registerInfo_id = 12969;
delete
from reg_subjectinfo
where registerInfo_id = 12974;
delete
from reg_subjectinfo
where registerInfo_id = 12971;
delete
from reg_subjectinfo
where registerInfo_id = 12970;
delete
from reg_subjectinfo
where registerInfo_id = 12968;
delete
from reg_subjectinfo
where registerInfo_id = 12967;
delete
from reg_subjectinfo
where registerInfo_id = 12964;
delete
from reg_subjectinfo
where registerInfo_id = 12956;
delete
from reg_subjectinfo
where registerInfo_id = 12955;
delete
from reg_subjectinfo
where registerInfo_id = 12954;
delete
from reg_subjectinfo
where registerInfo_id = 12953;
/* create by dingwei 20210611 end */ /* create by dingwei 20210611 end */
/* create by dingwei 20210617 start */ /* create by dingwei 20210617 start */
set character set utf8; set
update reg_subjectinfo set registerName = '邓默' where registerInfo_id = 12983; character set utf8;
update reg_subjectinfo set registerName = '丁伟' where registerInfo_id = 12979; update reg_subjectinfo
update reg_subjectinfo set registerName = '丁伟' where registerInfo_id = 12979; set registerName = '邓默'
where registerInfo_id = 12983;
update reg_subjectinfo
set registerName = '丁伟'
where registerInfo_id = 12979;
update reg_subjectinfo
set registerName = '丁伟'
where registerInfo_id = 12979;
/* create by dingwei 20210617 end */ /* create by dingwei 20210617 end */
/* create by dingwei 20210702 start */ /* create by dingwei 20210702 start */
alter table reg_registerinfo modify taxIssue Integer; alter table reg_registerinfo modify taxIssue Integer;
alter table reg_subjectinfo modify taxIssue Integer; alter table reg_subjectinfo modify taxIssue Integer;
/* create by dingwei 20210702 end */ /* create by dingwei 20210702 end */
select id,name,whetherDelete from reg_registerinfo where taxpayerNum = '9142'; select id, name, whetherDelete
\ No newline at end of file from reg_registerinfo
where taxpayerNum = '9142';
\ No newline at end of file
...@@ -270,6 +270,15 @@ ...@@ -270,6 +270,15 @@
</c:if> </c:if>
</c:if> </c:if>
<tr> <tr>
<td class="name">是否购买CDCS/CSDG</br>考前培训:</td>
<c:if test="${registerInfo.ifBuyFee == 1}">
<td></td>
</c:if>
<c:if test="${registerInfo.ifBuyFee == 2}">
<td></td>
</c:if>
</tr>
<tr>
<td class="name">Family Name:</td> <td class="name">Family Name:</td>
<td>${registerInfo.name_en}</td> <td>${registerInfo.name_en}</td>
...@@ -312,11 +321,11 @@ ...@@ -312,11 +321,11 @@
<td class="name">COUNTRY:</td> <td class="name">COUNTRY:</td>
<td>中国</td> <td>中国</td>
</tr> </tr>
<tr> <%-- <tr>--%>
<td class="title" background="/resource/front/img/dh.gif" height="24" colspan="3"> <%-- <td class="title" background="/resource/front/img/dh.gif" height="24" colspan="3">--%>
上传考生名片 <%-- 上传考生名片--%>
</td> <%-- </td>--%>
</tr> <%-- </tr>--%>
<%-- <tr>--%> <%-- <tr>--%>
<%-- <td class="name">选择科目</td>--%> <%-- <td class="name">选择科目</td>--%>
<%-- <td align="left" width="30%">--%> <%-- <td align="left" width="30%">--%>
...@@ -331,34 +340,34 @@ ...@@ -331,34 +340,34 @@
<%-- </select>--%> <%-- </select>--%>
<%-- </td>--%> <%-- </td>--%>
<%-- </tr>--%> <%-- </tr>--%>
<tr> <%-- <tr>--%>
<td class="name">考生名片:</td> <%-- <td class="name">考生名片:</td>--%>
<td align="left" width="30%"> <%-- <td align="left" width="30%">--%>
<input id="imageUrlId1" class="PhotoUpload" type="file" name='file'/> <%-- <input id="imageUrlId1" class="PhotoUpload" type="file" name='file'/>--%>
</td> <%-- </td>--%>
<td align="left"> <%-- <td align="left">--%>
<input data-target="imageUrlId1" class="PhotoUploadButton" type="button" value="上传" <%-- <input data-target="imageUrlId1" class="PhotoUploadButton" type="button" value="上传"--%>
name="upload" style="width:80px;height:20px"> <%-- name="upload" style="width:80px;height:20px">--%>
</td> <%-- </td>--%>
</tr> <%-- </tr>--%>
<tr> <%-- <tr>--%>
<td></td> <%-- <td></td>--%>
<td> <%-- <td>--%>
<div><img data-target="imageUrlId1" id="img1" src="${registerInfo.img1}" <%-- <div><img data-target="imageUrlId1" id="img1" src="${registerInfo.img1}"--%>
style="width:150px;height:100px"></div> <%-- style="width:150px;height:100px"></div>--%>
</td> <%-- </td>--%>
<td align="left" valign="top"> <%-- <td align="left" valign="top">--%>
<p style="color: #000000">图片支持式为:bmp、gif、jpeg、jpg、png,图片大小不要超过1M</p> <%-- <p style="color: #000000">图片支持式为:bmp、gif、jpeg、jpg、png,图片大小不要超过1M</p>--%>
<p style="color: red;font-size:16px">如开具增值税专用发票,请考生上传个人名片,</p> <%-- <p style="color: red;font-size:16px">如开具增值税专用发票,请考生上传个人名片,</p>--%>
<p style="color: red;font-size:16px">或其他可证明考生供职于发票抬头所在单位的证明文件,如工牌、入职证明书(拍照即可)等</p> <%-- <p style="color: red;font-size:16px">或其他可证明考生供职于发票抬头所在单位的证明文件,如工牌、入职证明书(拍照即可)等</p>--%>
</td> <%-- </td>--%>
</tr> <%-- </tr>--%>
<tr> <%-- <tr>--%>
<td></td> <%-- <td></td>--%>
<td> <%-- <td>--%>
<Button id="saveCertificateId" style="width:80px;height:20px">保存照片</Button> <%-- <Button id="saveCertificateId" style="width:80px;height:20px">保存照片</Button>--%>
</td> <%-- </td>--%>
</tr> <%-- </tr>--%>
<tr> <tr>
<td class="title" background="/resource/front/img/dh.gif" height="24" colspan="3">My LIBF 登录 <td class="title" background="/resource/front/img/dh.gif" height="24" colspan="3">My LIBF 登录
......
...@@ -46,7 +46,7 @@ ...@@ -46,7 +46,7 @@
<tr id="trEmial" name="email33"> <tr id="trEmial" name="email33">
<td class="name" width="15%"><span style="color: red;">*</span><yh:yh id="1_Info_Email" english="E-mail:" isnotnull="1">邮箱:</yh:yh></td> <td class="name" width="15%"><span style="color: red;">*</span><yh:yh id="1_Info_Email" english="E-mail:" isnotnull="1">邮箱:</yh:yh></td>
<td width="25%"><input name="email" value="" style="width:220px" onblur="this.value=this.value.toLowerCase().replace(/(^\s*)|(\s*$)/g,&quot;&quot;); " type="text"><input name="A_MAINID" type="hidden"><input name="A_LINK_ID" type="hidden"><input name="A_ROLEID" type="hidden"><input name="A_LANGID" type="hidden"><input name="A_CON_CNF_ID" type="hidden"><input name="A_STAT_ID" type="hidden"><input name="A_AUDITSTATE" type="hidden"><input name="D_LINK_ID" type="hidden"><input name="D_MAINID" type="hidden"></td> <td width="25%"><input name="email" value="" style="width:220px" onblur="this.value=this.value.toLowerCase().replace(/(^\s*)|(\s*$)/g,&quot;&quot;); " type="text"><input name="A_MAINID" type="hidden"><input name="A_LINK_ID" type="hidden"><input name="A_ROLEID" type="hidden"><input name="A_LANGID" type="hidden"><input name="A_CON_CNF_ID" type="hidden"><input name="A_STAT_ID" type="hidden"><input name="A_AUDITSTATE" type="hidden"><input name="D_LINK_ID" type="hidden"><input name="D_MAINID" type="hidden"></td>
<td width="50%"><span class="reg_body">必填:请勿使用QQ邮箱,邮箱会作为登录名,请如实填写</span></td> <td width="50%"><span class="reg_body">必填:邮箱会作为登录名,请如实填写</span></td>
</tr> </tr>
<tr id="trPassWord" name="password33"> <tr id="trPassWord" name="password33">
<td class="name"><span style="color: red;">*</span><yh:yh id="1_Info_Password" english="Password:" isnotnull="1">密码:</yh:yh></td> <td class="name"><span style="color: red;">*</span><yh:yh id="1_Info_Password" english="Password:" isnotnull="1">密码:</yh:yh></td>
...@@ -122,7 +122,14 @@ ...@@ -122,7 +122,14 @@
type="text"></textarea></td> type="text"></textarea></td>
<td><span class="reg_body">必填:可以安全收到邮寄材料的地址</span></td> <td><span class="reg_body">必填:可以安全收到邮寄材料的地址</span></td>
</tr> </tr>
<tr id="trIfBuyFee" name="trIfBuyFee">
<td class="name"><span style="color: red;">*</span>是否购买CDCS/CSDG</br>考前培训:</td>
<td >
<input class="required" checked="checked" type="radio" name="ifBuyFee" value="1" width="40%"></input>&emsp;&emsp;
<input class="required" type="radio" name="ifBuyFee" value="2" width="40%"></input>
</td>
<td><span class="reg_body">必选</span></td>
</tr>
<tr> <tr>
<td class="name"><span style="color: red;">*</span><yh:yh id="1_customitem6" english="Custom Item6:" isnotnull="0">增值税发票:</yh:yh></td> <td class="name"><span style="color: red;">*</span><yh:yh id="1_customitem6" english="Custom Item6:" isnotnull="0">增值税发票:</yh:yh></td>
<td><select class="required" id="appreciationTaxTypeId" name="appreciationTaxType" style="width:225px"> <td><select class="required" id="appreciationTaxTypeId" name="appreciationTaxType" style="width:225px">
......
...@@ -67,7 +67,7 @@ ...@@ -67,7 +67,7 @@
<tr id="trEmial" name="email33"> <tr id="trEmial" name="email33">
<td class="name" width="15%"><span style="color: red;">*</span><yh:yh id="1_Info_Email" english="E-mail:" isnotnull="1">邮箱:</yh:yh></td> <td class="name" width="15%"><span style="color: red;">*</span><yh:yh id="1_Info_Email" english="E-mail:" isnotnull="1">邮箱:</yh:yh></td>
<td width="25%"><input name="email" value="" style="width:220px" onblur="this.value=this.value.toLowerCase().replace(/(^\s*)|(\s*$)/g,&quot;&quot;); " type="text"><input name="A_MAINID" type="hidden"><input name="A_LINK_ID" type="hidden"><input name="A_ROLEID" type="hidden"><input name="A_LANGID" type="hidden"><input name="A_CON_CNF_ID" type="hidden"><input name="A_STAT_ID" type="hidden"><input name="A_AUDITSTATE" type="hidden"><input name="D_LINK_ID" type="hidden"><input name="D_MAINID" type="hidden"></td> <td width="25%"><input name="email" value="" style="width:220px" onblur="this.value=this.value.toLowerCase().replace(/(^\s*)|(\s*$)/g,&quot;&quot;); " type="text"><input name="A_MAINID" type="hidden"><input name="A_LINK_ID" type="hidden"><input name="A_ROLEID" type="hidden"><input name="A_LANGID" type="hidden"><input name="A_CON_CNF_ID" type="hidden"><input name="A_STAT_ID" type="hidden"><input name="A_AUDITSTATE" type="hidden"><input name="D_LINK_ID" type="hidden"><input name="D_MAINID" type="hidden"></td>
<td width="50%"><span class="reg_body">请勿使用QQ邮箱,邮箱会作为登录名,请如实填写</span></td> <td width="50%"><span class="reg_body">邮箱会作为登录名,请如实填写</span></td>
</tr> </tr>
<tr id="trPassWord" name="password33"> <tr id="trPassWord" name="password33">
<td class="name"><span style="color: red;">*</span><yh:yh id="1_Info_Password" english="Password:" isnotnull="1">密码:</yh:yh></td> <td class="name"><span style="color: red;">*</span><yh:yh id="1_Info_Password" english="Password:" isnotnull="1">密码:</yh:yh></td>
......
...@@ -85,10 +85,10 @@ var REG = function () { ...@@ -85,10 +85,10 @@ var REG = function () {
}); });
$("[name=email]").on("blur", function () { $("[name=email]").on("blur", function () {
var e = $("[name=email]").val(); var e = $("[name=email]").val();
if (new RegExp("^\\w+@qq\.com$").test(e)) { // if (new RegExp("^\\w+@qq\.com$").test(e)) {
showWarning($("[name=email]"), "请勿使用QQ邮箱注册!"); // showWarning($("[name=email]"), "请勿使用QQ邮箱注册!");
return; // return;
} // }
var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(e)) { if (!filter.test(e)) {
showWarning($("[name=email]"), "邮箱格式不正确!"); showWarning($("[name=email]"), "邮箱格式不正确!");
......
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