自己代码存放使用!未经本人同意不得转载
1、BaseController
import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.slsale.common.Constants;
import org.slsale.pojo.User;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
public class BaseController {
private Logger logger = Logger.getLogger(BaseController.class);
private User currentUser;
public User getCurrentUser() {
if(null == this.currentUser){
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
HttpSession session = request.getSession(false);
if(null != session){
currentUser = (User)session.getAttribute(Constants.SESSION_USER);
}else {
currentUser = null;
}
}
return currentUser;
}
public void setCurrentUser(User currentUser) {
this.currentUser = currentUser;
}
/**
* 日期国际化
* @param dataBinder
*/
@InitBinder
public void InitBinder(WebDataBinder dataBinder){
dataBinder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
public void setAsText(String value) {
try {
setValue(new SimpleDateFormat("yyyy-MM-dd").parse(value));
} catch(ParseException e) {
setValue(null);
}
}
public String getAsText() {
return new SimpleDateFormat("yyyy-MM-dd").format((Date) getValue());
}
});
}
}
2、LoginController
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.slsale.common.Constants;
import org.slsale.common.RedisAPI;
import org.slsale.pojo.Affiche;
import org.slsale.pojo.Authority;
import org.slsale.pojo.Function;
import org.slsale.pojo.Information;
import org.slsale.pojo.Menu;
import org.slsale.pojo.User;
import org.slsale.service.affiche.AfficheService;
import org.slsale.service.function.FunctionService;
import org.slsale.service.information.InformationService;
import org.slsale.service.user.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class LoginController extends BaseController {
private Logger logger = Logger.getLogger(LoginController.class);
@Resource
private UserService userService;
@Resource
private FunctionService functionService;
@Resource
private RedisAPI redisAPI;
@Resource
private InformationService informationService;
@Resource
private AfficheService afficheService;
@RequestMapping("/main.html")
public ModelAndView main(HttpSession session){
logger.debug("main======================== " );
List<Information> infoList = null;
List<Affiche> afficheList = null;
Information information = new Information();
Affiche affiche = new Affiche();
information.setStarNum(0);
information.setPageSize(5);
information.setState(1);
affiche.setStarNum(0);
affiche.setPageSize(5);
try {
infoList = informationService.getInformationList(information);
afficheList = afficheService.getPortalAfficheList(affiche);
} catch (Exception e) {
infoList = null;
afficheList = null;
}
//menu list
User user = this.getCurrentUser();
List<Menu> mList = null;
if(null != user){
Map<String, Object> model = new HashMap<String, Object>();
model.put("user", user);
/**
* key:menuList+roleID---eg:"menuList2"
* value:mList
*/
//redis里有没有数据
if(!redisAPI.exist("menuList"+user.getRoleId())){//redis没数据
//根据当前用户获取菜单列表mList
mList = getFuncByCurrentUser(user.getRoleId());
//json
if(null != mList){
JSONArray jsonArray = JSONArray.fromObject(mList);
String jsonString = jsonArray.toString();
logger.debug("jsonString : " + jsonString);
model.put("mList", jsonString);
redisAPI.set("menuList"+user.getRoleId(), jsonString);
}
}else{// redis里有数据,直接从redis里取数据
String redisMenuListKeyString = redisAPI.get("menuList"+user.getRoleId());
logger.debug("menuList from redis: " + redisMenuListKeyString);
if(null != redisMenuListKeyString && !"".equals(redisMenuListKeyString)){
model.put("mList", redisMenuListKeyString);
}else {
return new ModelAndView("redirect:/");
}
}
if(!redisAPI.exist("Role"+user.getRoleId()+"UrlList")){
try {
//get all role url list to redis
Authority authority = new Authority();
authority.setRoleId(user.getRoleId());
List<Function> functionList = functionService.getFunctionListByRoleId(authority);
if(functionList != null){
StringBuffer sBuffer = new StringBuffer();
for(Function f:functionList){
sBuffer.append(f.getFuncUrl());
}
redisAPI.set("Role"+user.getRoleId()+"UrlList", sBuffer.toString());
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
model.put("infoList", infoList);
model.put("afficheList", afficheList);
session.setAttribute(Constants.SESSION_BASE_MODEL, model);
return new ModelAndView("main",model);
}
return new ModelAndView("redirect:/");
}
/**
* 根据当前用户角色id获取功能列表(对应的菜单)
* @param roleId
* @return
*/
protected List<Menu> getFuncByCurrentUser(int roleId){
List<Menu> menuList = new ArrayList<Menu>();
Authority authority = new Authority();
authority.setRoleId(roleId);
try {
List<Function> mList = functionService.getMainFunctionList(authority);
if(mList != null){
for(Function function:mList){
Menu menu = new Menu();
menu.setMainMenu(function);
function.setRoleId(roleId);
List<Function> subList = functionService.getSubFunctionList(function);
if(null != subList){
menu.setSubMenus(subList);
}
menuList.add(menu);
}
}
} catch (Exception e) {
// TODO: handle exception
}
return menuList;
}
@RequestMapping("/login.html")
@ResponseBody
public Object login(HttpSession session,@RequestParam String user){
logger.debug("login===================");
if(user == null || "".equals(user)){
return "nodata";
}else{
JSONObject userObject = JSONObject.fromObject(user);
User userObj= (User)userObject.toBean(userObject, User.class);
try {
if(userService.loginCodeIsExit(userObj) == 0){//不存在这个登录账号
return "nologincode";
}else{
User _user = userService.getLoginUser(userObj);
if(null != _user){//登录成功
//当前用户存到session中
session.setAttribute(Constants.SESSION_USER, _user);
//更新当前用户登录的lastLoginTime
User updateLoginTimeUser = new User();
updateLoginTimeUser.setId(_user.getId());
updateLoginTimeUser.setLastLoginTime(new Date());
userService.modifyUser(updateLoginTimeUser);
updateLoginTimeUser = null;
return "success";
}else{//密码错误
return "pwderror";
}
}
} catch (Exception e) {
// TODO: handle exception
return "failed";
}
}
}
/**
* 注销
* @param session
* @return
*/
@RequestMapping("/logout.html")
public String logout(HttpSession session){
session.removeAttribute(Constants.SESSION_USER);
session.invalidate();
this.setCurrentUser(null);
return "index";
}
//没有权限访问
@RequestMapping("/401.html")
public ModelAndView noRole(){
return new ModelAndView("401");
}
}
3、package org.slsale.controller;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.slsale.common.Constants;
import org.slsale.common.JsonDateValueProcessor;
import org.slsale.common.PageSupport;
import org.slsale.common.SQLTools;
import org.slsale.pojo.DataDictionary;
import org.slsale.pojo.Role;
import org.slsale.pojo.User;
import org.slsale.service.datadictionary.DataDictionaryService;
import org.slsale.service.role.RoleService;
import org.slsale.service.user.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.mysql.jdbc.StringUtils;
@Controller
public class UserController extends BaseController {
private Logger logger = Logger.getLogger(UserController.class);
@Resource
private UserService userService;
@Resource
private RoleService roleService;
@Resource
private DataDictionaryService dataDictionaryService;
@RequestMapping("/backend/modifyPwd.html")
@ResponseBody
public Object modifyPwd(@RequestParam String userJson){
logger.debug("modifyPwd ================ ");
User sessionUser = this.getCurrentUser();
if(userJson == null || userJson.equals("")){
return "nodata";
}else{
JSONObject userObject = JSONObject.fromObject(userJson);
User user = (User)JSONObject.toBean(userObject,User.class);
user.setId(sessionUser.getId());
user.setLoginCode(sessionUser.getLoginCode());
try {
if(userService.getLoginUser(user)!=null){
user.setPassword(user.getPassword2());
user.setPassword2(null);
userService.modifyUser(user);
}else{
return "oldpwdwrong";
}
} catch (Exception e) {
// TODO: handle exception
return "failed";
}
}
return "success";
}
/**
* 获取用户列表(分页查询)
* @return
*/
@RequestMapping("/backend/userlist.html")
public ModelAndView userList(HttpSession session,Model model,
@RequestParam(value="currentpage",required=false)Integer currentpage ,
@RequestParam(value="currentPage",required=false) Integer currentPage,
@RequestParam(value="s_referCode",required=false) String s_referCode,
@RequestParam(value="s_loginCode",required=false) String s_loginCode,
@RequestParam(value="s_roleId",required=false) String s_roleId,
@RequestParam(value="s_isStart",required=false) String s_isStart){
Map<String, Object> baseModel = (Map<String, Object>)session.getAttribute(Constants.SESSION_BASE_MODEL);
if(baseModel == null){
return new ModelAndView("redirect:/");
}else{
//获取roleList和cardTypeList
DataDictionary dataDictionary = new DataDictionary();
dataDictionary.setTypeCode("CARD_TYPE");
List<Role> roleList = null;
List<DataDictionary> cardTypeList = null;
try {
roleList = roleService.getRoleIdAndNameList();
cardTypeList = dataDictionaryService.getDataDictionaries(dataDictionary);
} catch (Exception e) {
// TODO: handle exception
}
//设置查询条件-放入user对象中
User user = new User();
if(null != s_loginCode)
user.setLoginCode("%"+SQLTools.transfer(s_loginCode)+"%");
if(null != s_referCode)
user.setReferCode("%"+SQLTools.transfer(s_referCode)+"%");
if(!StringUtils.isNullOrEmpty(s_isStart))
user.setIsStart(Integer.valueOf(s_isStart));
else
user.setIsStart(null);
if(!StringUtils.isNullOrEmpty(s_roleId))
user.setRoleId(Integer.valueOf(s_roleId));
else
user.setRoleId(null);
//pages
PageSupport page = new PageSupport();
try {
page.setTotalCount(userService.count(user));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
page.setTotalCount(0);
}
if(page.getTotalCount() > 0){
if(currentpage != null)
page.setPage(currentpage);
if(page.getPage() <= 0)
page.setPage(1);
if(page.getPage() > page.getPageCount())
page.setPage(page.getPageCount());
user.setStarNum((page.getPage() - 1) * page.getPageSize());
user.setPageSize(page.getPageSize());
List<User> userList = null;
try {
userList = userService.getUserList(user);
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
userList = null;
if(page == null){
page = new PageSupport();
page.setItems(null);
}
}
page.setItems(userList);
}else{
page.setItems(null);
}
model.addAllAttributes(baseModel);
model.addAttribute("page", page);
model.addAttribute("roleList",roleList);
model.addAttribute("cardTypeList",cardTypeList);
model.addAttribute("s_loginCode", s_loginCode);
model.addAttribute("s_referCode", s_referCode);
model.addAttribute("s_isStart", s_isStart);
model.addAttribute("s_roleId", s_roleId);
return new ModelAndView("/backend/userlist");
}
}
@RequestMapping(value = "/backend/adduser.html",method=RequestMethod.POST)
public ModelAndView addUser(HttpSession session,@ModelAttribute("addUser") User addUser){
if(session.getAttribute(Constants.SESSION_BASE_MODEL) == null){
return new ModelAndView("redirect:/");
}else{
try {
String idCard = addUser.getIdCard();
String ps = idCard.substring(idCard.length()-6);
addUser.setPassword(ps);
addUser.setPassword2(ps);
addUser.setCreateTime(new Date());
addUser.setReferId(this.getCurrentUser().getId());
addUser.setReferCode(this.getCurrentUser().getLoginCode());
addUser.setLastUpdateTime(new Date());
userService.addUser(addUser);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new ModelAndView("redirect:/backend/userlist.html");
}
}
@RequestMapping(value = "/backend/upload.html", produces = {"text/html;charset=UTF-8"})
@ResponseBody
public Object upload(@RequestParam(value = "a_fileInputID", required = false) MultipartFile cardFile,
@RequestParam(value = "a_fileInputBank", required = false) MultipartFile bankFile,
@RequestParam(value = "m_fileInputID", required = false) MultipartFile mCardFile,
@RequestParam(value = "m_fileInputBank", required = false) MultipartFile mBankFile,
@RequestParam(value = "loginCode", required = false) String loginCode,
HttpServletRequest request,HttpSession session) {
logger.debug("开始....");
//根据服务器的操作系统,自动获取物理路径,自动适应各个操作系统的路径
String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
logger.debug("hanlu path======== " + path);
List<DataDictionary> list = null;
DataDictionary dataDictionary = new DataDictionary();
dataDictionary.setTypeCode("PERSONALFILE_SIZE");
try {
list = dataDictionaryService.getDataDictionaries(dataDictionary);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
int filesize = 50000;
if(null != list){
if(list.size() == 1){
filesize = Integer.valueOf(list.get(0).getValueName());
}
}
if(cardFile != null){
String oldFileName = cardFile.getOriginalFilename();//获取原文件名
String prefix=FilenameUtils.getExtension(oldFileName);//取文件后缀
logger.debug("hanlu bankFile prefix======== " + prefix);
if(cardFile.getSize() > filesize){//上传大小不得超过 50k
return "1";
}else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
|| prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")){
//给文件重命名:系统毫秒数+100W以内的随机数
String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_IDcard.jpg";
logger.debug("hanlu new fileName======== " + cardFile.getName());
File targetFile = new File(path, fileName);
if(!targetFile.exists()){
targetFile.mkdirs();
}
//保存
try {
cardFile.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
String url = request.getContextPath()+"/statics/uploadfiles/"+fileName;
return url;
}else{
return "2";
}
}
if(bankFile != null){
String oldFileName = bankFile.getOriginalFilename();
logger.debug("hanlu bankFile oldFileName======== " + oldFileName);
String prefix=FilenameUtils.getExtension(oldFileName);
if(bankFile.getSize() > filesize){//上传大小不得超过 50k
return "1";
}else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
|| prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")){
String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_bank.jpg";
logger.debug("hanlu bankFile new fileName======== " + bankFile.getName());
File targetFile = new File(path, fileName);
if(!targetFile.exists()){
targetFile.mkdirs();
}
//保存
try {
bankFile.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
String url = request.getContextPath()+"/statics/uploadfiles/"+fileName;
return url;
}else{//上传图片格式不正确
return "2";
}
}
if(mCardFile != null){
String oldFileName = mCardFile.getOriginalFilename();
String prefix=FilenameUtils.getExtension(oldFileName);
if(mCardFile.getSize() > filesize){//上传大小不得超过 50k
return "1";
}else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
|| prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")){//上传图片格式不正确
String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_IDcard.jpg";
logger.debug("hanlu new fileName======== " + mCardFile.getName());
File targetFile = new File(path, fileName);
if(!targetFile.exists()){
targetFile.mkdirs();
}
//保存
try {
mCardFile.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
String url = request.getContextPath()+"/statics/uploadfiles/"+fileName;
return url;
}else{
return "2";
}
}
if(mBankFile != null){
String oldFileName = mBankFile.getOriginalFilename();
logger.debug("hanlu bankFile oldFileName======== " + oldFileName);
String prefix=FilenameUtils.getExtension(oldFileName);
if(mBankFile.getSize() > filesize){//上传大小不得超过 50k
return "1";
}else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
|| prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")){//上传图片格式不正确
String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_bank.jpg";
logger.debug("hanlu bankFile new fileName======== " + mBankFile.getName());
File targetFile = new File(path, fileName);
if(!targetFile.exists()){
targetFile.mkdirs();
}
//保存
try {
mBankFile.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
String url = request.getContextPath()+"/statics/uploadfiles/"+fileName;
return url;
}else{
return "2";
}
}
return null;
}
@RequestMapping(value = "/backend/delpic.html", produces = {"text/html;charset=UTF-8"})
@ResponseBody
public String delPic(@RequestParam(value="picpath",required=false) String picpath,
@RequestParam(value="id",required=false) String id,
HttpServletRequest request,HttpSession session){
String result= "failed" ;
if(picpath == null || picpath.equals("")){
result = "success";
}else{
//picpath:传过来的网络路径,需要解析成物理路径
String[] paths = picpath.split("/");
String path = request.getSession().getServletContext().getRealPath(paths[1]+File.separator+paths[2]+File.separator+paths[3]);
File file = new File(path);
if(file.exists())
if(file.delete()){
if(id.equals("0")){//添加用户时,删除上传的图片
result = "success";
}else{//修改用户时,删除上传的图片
User _user = new User();
_user.setId(Integer.valueOf(id));
if(picpath.indexOf("_IDcard.jpg") != -1)
_user.setIdCardPicPath(picpath);
else if(picpath.indexOf("_bank.jpg") != -1)
_user.setBankPicPath(picpath);
try {
if(userService.delUserPic(_user) > 0){
logger.debug("hanlu modify----userService.delUserPic======== " );
result = "success";
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return result;
}
}
}
}
return result;
}
@RequestMapping(value = "/backend/deluser.html", produces = {"text/html;charset=UTF-8"})
@ResponseBody
public String delUser(@RequestParam(value="delId",required=false) String delId,
@RequestParam(value="delIdCardPicPath",required=false) String delIdCardPicPath,
@RequestParam(value="delBankPicPath",required=false) String delBankPicPath,
@RequestParam(value="delUserType",required=false) String delUserType,
HttpServletRequest request,HttpSession session){
String result= "false" ;
User delUser = new User();
delUser.setId(Integer.valueOf(delId));
try {
//若被删除的用户为:普通消费会员、VIP会员、加盟店 则不可被删除
if(delUserType.equals("2") || delUserType.equals("3") || delUserType.equals("4")){
result = "noallow";
}else{
if(this.delPic(delIdCardPicPath,delId,request,session).equals("success") && this.delPic(delBankPicPath,delId,request,session).equals("success")){
if(userService.deleteUser(delUser) > 0)
result = "success";
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
@RequestMapping(value = "/backend/logincodeisexit.html", produces = {"text/html;charset=UTF-8"})
@ResponseBody
public String loginCodeIsExit(@RequestParam(value="loginCode",required=false) String loginCode,
@RequestParam(value="id",required=false) String id){
logger.debug("hanlu loginCodeIsExit loginCode===================== "+loginCode);
logger.debug("hanlu loginCodeIsExit id===================== "+id);
String result = "failed";
User _user = new User();
_user.setLoginCode(loginCode);
if(!id.equals("-1"))
_user.setId(Integer.valueOf(id));
try {
if(userService.loginCodeIsExit(_user) == 0)
result = "only";
else
result = "repeat";
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return result;
}
return result;
}
@RequestMapping(value = "/backend/getuser.html", produces = {"text/html;charset=UTF-8"})
@ResponseBody
public Object getUser(@RequestParam(value="id",required=false) String id){
String cjson = "";
if(null == id || "".equals(id)){
return "nodata";
}else{
try {
User user = new User();
user.setId(Integer.valueOf(id));
user = userService.getUserById(user);
//user对象里有日期,所有有日期的属性,都要按照此日期格式进行json转换(对象转json)
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
JSONObject jo = JSONObject.fromObject(user,jsonConfig);
cjson = jo.toString();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "failed";
}
return cjson;
}
}
@RequestMapping(value = "/backend/loadUserTypeList.html", produces = {"text/html;charset=UTF-8"})
@ResponseBody
public Object loadUserTypeList(@RequestParam(value="s_roleId",required=false) String s_roleId){
String cjson = "";
try {
DataDictionary dataDictionary = new DataDictionary();
dataDictionary.setTypeCode("USER_TYPE");
List<DataDictionary> userTypeList = dataDictionaryService.getDataDictionaries(dataDictionary);
JSONArray jo = JSONArray.fromObject(userTypeList);
cjson = jo.toString();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return cjson;
}
@RequestMapping(value = "/backend/modifyuser.html",method=RequestMethod.POST)
public ModelAndView modifyUser(HttpSession session,@ModelAttribute("modifyUser") User modifyUser){
if(session.getAttribute(Constants.SESSION_BASE_MODEL) == null){
return new ModelAndView("redirect:/");
}else{
try {
modifyUser.setLastUpdateTime(new Date());
userService.modifyUser(modifyUser);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new ModelAndView("redirect:/backend/userlist.html");
}
}
}
4、package org.slsale.controller;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.slsale.common.Constants;
import org.slsale.pojo.Role;
import org.slsale.pojo.User;
import org.slsale.service.role.RoleService;
import org.slsale.service.user.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class RoleController extends BaseController {
private Logger logger = Logger.getLogger(RoleController.class);
@Resource
private RoleService roleService;
@Resource
private UserService userService;
@RequestMapping("/backend/delRole.html")
@ResponseBody
public Object delRole(HttpSession session,@RequestParam String role){
if(null == role || "".equals(role)){
return "nodata";
}else{
JSONObject roleObject = JSONObject.fromObject(role);
Role roleObjRole = (Role)JSONObject.toBean(roleObject, Role.class);
try {
User u = new User();
List <User> uList = null;
u.setRoleId(roleObjRole.getId());
uList = userService.getUserListBySearch(u);
if(uList == null || uList.size() == 0){
roleService.deleteRole(roleObjRole);
}else{
String flag = "";
for(int i = 0; i < uList.size(); i++){
flag += uList.get(i).getLoginCode();
flag += ",";
}
return flag;
}
} catch (Exception e) {
// TODO Auto-generated catch block
return "failed";
}
return "success";
}
}
@RequestMapping("/backend/modifyRole.html")
@ResponseBody
public Object modifyRole(HttpSession session,@RequestParam String role){
if(null == role || "".equals(role)){
return "nodata";
}else{
JSONObject roleObject = JSONObject.fromObject(role);
Role roleObjRole = (Role)JSONObject.toBean(roleObject, Role.class);
roleObjRole.setCreateDate(new Date());
//roleObjRole.setIsStart(1);
roleObjRole.setCreatedBy(this.getCurrentUser().getLoginCode());
try {
roleService.hl_modifyRole(roleObjRole);
} catch (Exception e) {
// TODO Auto-generated catch block
return "failed";
}
return "success";
}
}
@RequestMapping("/backend/addRole.html")
@ResponseBody
public Object addRole(HttpSession session,@RequestParam String role){
if(null == role || "".equals(role)){
return "nodata";
}else{
JSONObject roleObject = JSONObject.fromObject(role);
Role roleObjRole = (Role)JSONObject.toBean(roleObject, Role.class);
roleObjRole.setCreateDate(new Date());
roleObjRole.setIsStart(1);
roleObjRole.setCreatedBy(((User)session.getAttribute(Constants.SESSION_USER)).getLoginCode());
try {
if(roleService.getRoleR(roleObjRole) != null){
return "rename";
}else{
roleService.addRole(roleObjRole);
}
} catch (Exception e) {
// TODO Auto-generated catch block
return "failed";
}
return "success";
}
}
@RequestMapping("/backend/rolelist.html")
public ModelAndView roleList(HttpSession session,Model model){
Map<String,Object> baseModel= (Map<String,Object>)session.getAttribute(Constants.SESSION_BASE_MODEL);
if(baseModel == null){
return new ModelAndView("redirect:/");
}else{
List<Role> roleList = null;
Role role = new Role();
try {
roleList = roleService.getRoleList();
} catch (Exception e) {
// TODO Auto-generated catch block
roleList = null;
}
model.addAllAttributes(baseModel);
model.addAttribute(roleList);
return new ModelAndView("/backend/rolelist");
}
}
}
5、package org.slsale.controller;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.slsale.common.Constants;
import org.slsale.common.HtmlEncode;
import org.slsale.common.JsonDateValueProcessor;
import org.slsale.common.PageSupport;
import org.slsale.common.SQLTools;
import org.slsale.pojo.DataDictionary;
import org.slsale.pojo.Function;
import org.slsale.pojo.Information;
import org.slsale.pojo.RoleFunctions;
import org.slsale.pojo.UploadTemp;
import org.slsale.pojo.User;
import org.slsale.service.datadictionary.DataDictionaryService;
import org.slsale.service.information.InformationService;
import org.slsale.service.uploadtemp.UploadTempService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class InformationController extends BaseController {
private Logger logger = Logger.getLogger(InformationController.class);
@Resource
private InformationService informationService;
@Resource
private DataDictionaryService dataDictionaryService;
@Resource
private UploadTempService uploadTempService;
@RequestMapping(value="/informanage/portalInfoDetail.html", produces = {"text/html;charset=UTF-8"})
public ModelAndView viewInfo(HttpSession session,@RequestParam Integer id,Model model){
Map<String,Object> baseModel= (Map<String,Object>)session.getAttribute(Constants.SESSION_BASE_MODEL);
if(baseModel == null){
return new ModelAndView("redirect:/");
}else{
if(null == id || "".equals(id)){
id = 0;
}else{
try {
Information information = new Information();
information.setId(id);
information = informationService.getInformation(information);
if(null != information && information.getTitle() != null){
model.addAttribute("information", information);
}
} catch (Exception e) {
}
}
}
model.addAllAttributes(baseModel);
return new ModelAndView("informanage/portalinfodetail");
}
@RequestMapping(value="/informanage/viewInfo.html", produces = {"text/html;charset=UTF-8"})
@ResponseBody
public Object viewInfo(HttpSession session,@RequestParam Integer id){
String result = "";
if(null == id || "".equals(id)){
result = "nodata";
}else{
try {
Information information = new Information();
information.setId(id);
information = informationService.getInformation(information);
if(null != information && information.getTitle() != null){
information.setTitle(HtmlEncode.htmlDecode(information.getTitle()));
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(Date.class,new JsonDateValueProcessor());
result = JSONObject.fromObject(information,jsonConfig).toString();
}
} catch (Exception e) {
// TODO Auto-generated catch block
result = "failed";
}
}
return result;
}
@RequestMapping("/informanage/delInfo.html")
@ResponseBody
public Object delInfo( HttpServletRequest request,HttpSession session,@RequestParam Integer id){
if(null == id || "".equals(id)){
return "nodata";
}else{
try {
Information information = new Information();
information.setId(id);
Information _information = new Information();
_information = informationService.getInformation(information);
if(null != _information){
String path = request.getSession().getServletContext().getRealPath("/");
_information.setFilePath(_information.getFilePath().replace("/", File.separator+File.separator));
File file = new File(path + _information.getFilePath());
if(file.exists()){
file.delete();
}
informationService.deleteInformation(information);
}
} catch (Exception e) {
// TODO Auto-generated catch block
return "failed";
}
return "success";
}
}
@RequestMapping("/informanage/downloadcenter.html")
public ModelAndView downloadInfoList(HttpSession session,Model model,@RequestParam(value="p",required=false)Integer p,@RequestParam(value="k",required=false)String k){
Map<String,Object> baseModel= (Map<String,Object>)session.getAttribute(Constants.SESSION_BASE_MODEL);
List<Information> informationList = null;
if(baseModel == null){
return new ModelAndView("redirect:/");
}else{
Information information = new Information();
information.setState(1);
//pages
PageSupport page = new PageSupport();
try{
if(null == k || "".equals(k)){
page.setTotalCount(informationService.count(information));
}else{
information.setTitle("%"+SQLTools.transfer(k)+"%");
page.setTotalCount(informationService.count(information));
}
}catch (Exception e1) {
page.setTotalCount(0);
}
if(page.getTotalCount() > 0){
if(p != null)
page.setPage(p);
if(page.getPage() <= 0)
page.setPage(1);
if(page.getPage() > page.getPageCount())
page.setPage(page.getPageCount());
information.setStarNum((page.getPage() - 1) * page.getPageSize());
information.setPageSize(page.getPageSize());
try {
if(null == k || "".equals(k)){
informationList = informationService.getInformationList(information);
}else{
information.setTitle("%"+SQLTools.transfer(k)+"%");
informationList = informationService.getInformationList(information);
}
}catch (Exception e) {
e.printStackTrace();
informationList = null;
if(page == null){
page = new PageSupport();
page.setItems(null);
}
}
page.setItems(informationList);
}else{
page.setItems(null);
}
model.addAllAttributes(baseModel);
model.addAttribute("page", page);
model.addAttribute("k", k);
}
return new ModelAndView("informanage/downloadcenter");
}
@RequestMapping("/informanage/portalinfoList.html")
public ModelAndView infoList(HttpSession session,Model model,@RequestParam(value="p",required=false)Integer p,@RequestParam(value="k",required=false)String k){
Map<String,Object> baseModel= (Map<String,Object>)session.getAttribute(Constants.SESSION_BASE_MODEL);
if(baseModel == null){
return new ModelAndView("redirect:/");
}else{
download(session,model,p,null);
}
return new ModelAndView("informanage/portalinfolist");
}
@RequestMapping("/informanage/download.html")
public ModelAndView download(HttpSession session,Model model,@RequestParam(value="p",required=false)Integer p,@RequestParam(value="k",required=false)String k){
Map<String,Object> baseModel= (Map<String,Object>)session.getAttribute(Constants.SESSION_BASE_MODEL);
List<Information> informationList = null;
if(baseModel == null){
return new ModelAndView("redirect:/");
}else{
Information information = new Information();
information.setState(1);
//pages
PageSupport page = new PageSupport();
try{
if(null == k || "".equals(k)){
page.setTotalCount(informationService.count(information));
}else{
information.setFileName("%"+SQLTools.transfer(k)+"%");
page.setTotalCount(informationService.count(information));
}
}catch (Exception e1) {
page.setTotalCount(0);
}
if(page.getTotalCount() > 0){
if(p != null)
page.setPage(p);
if(page.getPage() <= 0)
page.setPage(1);
if(page.getPage() > page.getPageCount())
page.setPage(page.getPageCount());
information.setStarNum((page.getPage() - 1) * page.getPageSize());
information.setPageSize(page.getPageSize());
try {
if(null == k || "".equals(k)){
informationList = informationService.getInformationList(information);
}else{
information.setFileName("%"+SQLTools.transfer(k)+"%");
informationList = informationService.getInformationList(information);
}
}catch (Exception e) {
e.printStackTrace();
informationList = null;
if(page == null){
page = new PageSupport();
page.setItems(null);
}
}
page.setItems(informationList);
}else{
page.setItems(null);
}
model.addAllAttributes(baseModel);
model.addAttribute("page", page);
model.addAttribute("k", k);
}
return new ModelAndView("informanage/download");
}
@RequestMapping("/informanage/information.html")
public ModelAndView information(HttpSession session,Model model,@RequestParam(value="p",required=false)Integer p){
Map<String,Object> baseModel= (Map<String,Object>)session.getAttribute(Constants.SESSION_BASE_MODEL);
List<Information> informationList = null;
List<DataDictionary> dicList = null;
DataDictionary dataDictionary = new DataDictionary();
dataDictionary.setTypeCode("INFO_TYPE");
if(baseModel == null){
return new ModelAndView("redirect:/");
}else{
Information information = new Information();
//pages
PageSupport page = new PageSupport();
try{
dicList = dataDictionaryService.getDataDictionaries(dataDictionary);
page.setTotalCount(informationService.count(information));
}catch (Exception e1) {
page.setTotalCount(0);
}
logger.debug("+++++++++++++++totalcount++++++++++++++:" + page.getTotalCount());
if(page.getTotalCount() > 0){
if(p != null)
page.setPage(p);
if(page.getPage() <= 0)
page.setPage(1);
if(page.getPage() > page.getPageCount())
page.setPage(page.getPageCount());
information.setStarNum((page.getPage() - 1) * page.getPageSize());
information.setPageSize(page.getPageSize());
try {
information.setState(null);
informationList = informationService.getInformationList(information);
}catch (Exception e) {
e.printStackTrace();
informationList = null;
if(page == null){
page = new PageSupport();
page.setItems(null);
}
}
page.setItems(informationList);
}else{
page.setItems(null);
}
logger.debug("+++++++++++++++++++++++++++++:" + afficheList.size());
model.addAllAttributes(baseModel);
model.addAttribute("page", page);
model.addAttribute("dicList", dicList);
}
return new ModelAndView("informanage/information");
}
@RequestMapping("/informanage/delInfoFile.html")
@ResponseBody
public Object delInfoFile( HttpServletRequest request,HttpSession session,@RequestParam String filePath){
if(null == filePath || "".equals(filePath)){
return "nodata";
}else{
try {
String path = request.getSession().getServletContext().getRealPath("/");
File file = new File(path + filePath);
if(file.exists()){
file.delete();
}
Information information = new Information();
information.setTypeName(filePath);
information.setFileName("");
information.setFilePath("#");
information.setFileSize(0d);
information.setUploadTime(new Date());
informationService.modifyInformationFileInfo(information);
UploadTemp uploadTemp = new UploadTemp();
filePath = filePath.replaceAll("/", File.separator+File.separator);
uploadTemp.setUploadFilePath(filePath);
uploadTempService.delete(uploadTemp);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "failed";
}
return "success";
}
}
public static void main(String[] args) {
String string = "/statics/infofiles/1394419869337_info.dll";
String ssString = File.separator;
System.out.println("111:" + ssString);
string = string.replaceAll("/", File.separator+File.separator);
System.out.println(string);
}
@RequestMapping(value = "/informanage/upload.html", produces = {"text/html;charset=UTF-8"})
@ResponseBody
public Object upload(@RequestParam(value = "uploadInformationFile", required = false) MultipartFile uploadInformationFile,
@RequestParam(value = "uploadInformationFile", required = false) MultipartFile uploadInformationFileM,
HttpServletRequest request,HttpSession session) {
String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"infofiles");
if(uploadInformationFile == null && uploadInformationFileM != null)
uploadInformationFile = uploadInformationFileM;
if(uploadInformationFile != null){
String oldFileName = uploadInformationFile.getOriginalFilename();
String prefix=FilenameUtils.getExtension(oldFileName);
List<DataDictionary> list = null;
DataDictionary dataDictionary = new DataDictionary();
dataDictionary.setTypeCode("INFOFILE_SIZE");
try {
list = dataDictionaryService.getDataDictionaries(dataDictionary);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
int filesize = 500000000;
if(null != list){
if(list.size() == 1){
filesize = Integer.valueOf(list.get(0).getValueName());
}
}
if(uploadInformationFile.getSize() > filesize){//上传大小不得超过 500M
return "1";
}else{//上传图片格式不正确
String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_info."+prefix;
File targetFile = new File(path, fileName);
if(!targetFile.exists()){
targetFile.mkdirs();
}
//保存
try {
uploadInformationFile.transferTo(targetFile);
//add file info to uploadtemp
User sessionUser = ((User)session.getAttribute(Constants.SESSION_USER));
UploadTemp uploadTemp = new UploadTemp();
uploadTemp.setUploader(sessionUser.getLoginCode());
uploadTemp.setUploadType("info");
uploadTemp.setUploadFilePath(File.separator + "statics" + File.separator + "infofiles" + File.separator + fileName );
uploadTempService.add(uploadTemp);
} catch (Exception e) {
e.printStackTrace();
}
String url = oldFileName + "[[[]]]" + request.getContextPath()+"/statics/infofiles/"+fileName + "size:"+uploadInformationFile.getSize();
return url;
}
}
return null;
}
@RequestMapping(value="/informanage/addInformation.html",method=RequestMethod.POST)
public ModelAndView addInformation(@ModelAttribute("addInformation") Information information,HttpSession session){
if(session.getAttribute(Constants.SESSION_BASE_MODEL) == null){
return new ModelAndView("redirect:/");
}else{
try {
User sessionUser = ((User)session.getAttribute(Constants.SESSION_USER));
information.setPublisher(sessionUser.getLoginCode());
information.setPublishTime(new Date(System.currentTimeMillis()));
information.setState(1);
information.setUploadTime(information.getPublishTime());
logger.debug("=======information.getTitle()); ================" + information.getTitle());
if(null != information.getTitle() && !information.getTitle().equals("")){
logger.debug("======= addInformation HtmlEncode.htmlEncode(information.getTitle())================" + HtmlEncode.htmlEncode(information.getTitle()));
information.setTitle(HtmlEncode.htmlEncode(information.getTitle()));
}
UploadTemp uploadTemp = new UploadTemp();
uploadTemp.setUploader(sessionUser.getLoginCode());
uploadTemp.setUploadType("info");
uploadTemp.setUploadFilePath(information.getFilePath().replaceAll("/", File.separator+File.separator));
uploadTempService.delete(uploadTemp);
informationService.addInformation(information);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return new ModelAndView("redirect:/informanage/information.html");
}
@RequestMapping(value="/informanage/modifyinformation.html",method=RequestMethod.POST)
public ModelAndView modifyInformation(@ModelAttribute("modifyInformation") Information information,HttpSession session){
if(session.getAttribute(Constants.SESSION_BASE_MODEL) == null){
return new ModelAndView("redirect:/");
}else{
try {
User sessionUser = ((User)session.getAttribute(Constants.SESSION_USER));
information.setPublisher(sessionUser.getLoginCode());
information.setPublishTime(new Date(System.currentTimeMillis()));
//information.setState(1);
information.setUploadTime(information.getPublishTime());
if(null != information.getTitle() && !information.getTitle().equals("")){
logger.debug("======= modifyInformation HtmlEncode.htmlEncode(information.getTitle())================" + HtmlEncode.htmlEncode(information.getTitle()));
information.setTitle(HtmlEncode.htmlEncode(information.getTitle()));
}
informationService.modifyInformation(information);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return new ModelAndView("redirect:/informanage/information.html");
}
@RequestMapping("/informanage/modifyInfoState.html")
@ResponseBody
public Object modifyRole(HttpSession session,@RequestParam String inforState){
if(null == inforState || "".equals(inforState)){
return "nodata";
}else{
JSONObject informationObject = JSONObject.fromObject(inforState);
Information information = (Information)JSONObject.toBean(informationObject, Information.class);
information.setUploadTime(new Date());
information.setPublisher(((User)session.getAttribute(Constants.SESSION_USER)).getLoginCode());
try {
informationService.modifyInformation(information);
} catch (Exception e) {
// TODO Auto-generated catch block
return "failed";
}
return "success";
}
}
}
6、package org.slsale.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONArray;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.slsale.common.Constants;
import org.slsale.common.RedisAPI;
import org.slsale.pojo.Authority;
import org.slsale.pojo.Function;
import org.slsale.pojo.Menu;
import org.slsale.pojo.Role;
import org.slsale.pojo.RoleFunctions;
import org.slsale.pojo.User;
import org.slsale.service.authority.AuthorityService;
import org.slsale.service.function.FunctionService;
import org.slsale.service.role.RoleService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class AuthorityController extends BaseController {
private Logger logger = Logger.getLogger(AuthorityController.class);
@Resource
private RoleService roleService;
@Resource
private FunctionService functionService;
@Resource
private AuthorityService authorityService;
@Resource
private LoginController loginController;
@Resource
private RedisAPI redisAPI;
/**
* 进入到权限管理首页面
* @param session
* @param model
* @return
*/
@RequestMapping("/backend/authoritymanage.html")
public ModelAndView authorityManage(HttpSession session,Model model){
Map<String, Object> baseModel = (Map<String, Object>)session.getAttribute(Constants.SESSION_BASE_MODEL);
if(null == baseModel){
return new ModelAndView("redirect:/");
}else{
List<Role> roleList = null;
try {
roleList = roleService.getRoleIdAndNameList();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
roleList = null;
}
model.addAllAttributes(baseModel);
model.addAttribute(roleList);
return new ModelAndView("/backend/authoritymanage");
}
}
//获取菜单功能列表
@RequestMapping(value="/backend/functios.html",produces={"text/html;charset=UTF-8"})
@ResponseBody
public Object functions(){
String resultString = "nodata";
Function function = new Function();
try {
function.setId(0);
List<Function> fList = functionService.getSubFuncList(function);
List<RoleFunctions> rList = new ArrayList<RoleFunctions>();
if(fList != null){
for(Function func : fList){
RoleFunctions rFunctions = new RoleFunctions();
rFunctions.setMainFunction(func);
rFunctions.setSubFunctions(functionService.getSubFuncList(func));
rList.add(rFunctions);
}
resultString = JSONArray.fromObject(rList).toString();
logger.debug("resultString================== " + resultString);
}
} catch (Exception e) {
// TODO: handle exception
}
return resultString;
}
@RequestMapping(value="/backend/getAuthorityDefault.html",produces={"text/html;charset=UTF-8"})
@ResponseBody
public Object getAuthorityDefault(@RequestParam Integer rid,@RequestParam Integer fid){
String resultString = "nodata";
try {
Authority authority = new Authority();
authority.setRoleId(rid);
authority.setFunctionId(fid);
if(authorityService.getAuthority(authority) != null){
resultString = "success";
}
} catch (Exception e) {
// TODO: handle exception
}
return resultString;
}
@RequestMapping(value="backend/modifyAuthority.html",produces={"text/html;charset=UTF-8"})
@ResponseBody
public Object modifyAuthority(HttpSession session,@RequestParam String ids){
String resultString = "nodata";
try {
if(null != ids){
String[] idsArrayStrings = StringUtils.split(ids, "-");
if(idsArrayStrings.length > 0){
User user = this.getCurrentUser();
/**
* 权限表的更新操作(roleId functionids )au_thority=====事务
* 先把该角色下的所有功能授权删除(delete),
* 然后再根据functionids进行重新授权(add)
*/
authorityService.hl_addAuthority(idsArrayStrings, user.getLoginCode());
List<Menu> mList = null;
mList = loginController.getFuncByCurrentUser(Integer.valueOf(idsArrayStrings[0]));
JSONArray jsonArray = JSONArray.fromObject(mList);
redisAPI.set("menuList"+idsArrayStrings[0],jsonArray.toString());
//get all role url list to redis
Authority authority = new Authority();
authority.setRoleId(Integer.valueOf(idsArrayStrings[0]));
List<Function> functionList = functionService.getFunctionListByRoleId(authority);
if(functionList != null || functionList.size() >= 0){
StringBuffer sBuffer = new StringBuffer();
for(Function f: functionList){
sBuffer.append(f.getFuncUrl());
}
redisAPI.set("Role"+idsArrayStrings[0]+"UrlList", sBuffer.toString());
}
resultString = "success";
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return resultString;
}
}
7、package org.slsale.controller;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.log4j.Logger;
import org.slsale.common.Constants;
import org.slsale.common.HtmlEncode;
import org.slsale.common.JsonDateValueProcessor;
import org.slsale.common.PageSupport;
import org.slsale.pojo.Affiche;
import org.slsale.pojo.Information;
import org.slsale.pojo.User;
import org.slsale.service.affiche.AfficheService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class AfficheController extends BaseController {
private Logger logger = Logger.getLogger(AfficheController.class);
@Resource
private AfficheService afficheService;
@RequestMapping("/informanage/portalafficheList.html")
public ModelAndView afficheList(HttpSession session,Model model,@RequestParam(value="p",required=false)Integer p){
Map<String,Object> baseModel= (Map<String,Object>)session.getAttribute(Constants.SESSION_BASE_MODEL);
if(baseModel == null){
return new ModelAndView("redirect:/");
}else{
affiche(session,model,p,true);
}
return new ModelAndView("informanage/portalaffichelist");
}
@RequestMapping(value="/informanage/portalAfficheDetail.html", produces = {"text/html;charset=UTF-8"})
public ModelAndView viewAffiche(HttpSession session,@RequestParam Integer id,Model model){
Map<String,Object> baseModel= (Map<String,Object>)session.getAttribute(Constants.SESSION_BASE_MODEL);
if(baseModel == null){
return new ModelAndView("redirect:/");
}else{
if(null == id || "".equals(id)){
id = 0;
}else{
try {
Affiche affiche = new Affiche();
affiche.setId(id);
affiche = afficheService.getAffiche(affiche);
if(null != affiche && affiche.getCode() != null){
model.addAttribute("affiche", affiche);
}
} catch (Exception e) {
}
}
}
model.addAllAttributes(baseModel);
return new ModelAndView("informanage/portalaffichedetail");
}
@RequestMapping(value="/informanage/viewAffiche.html", produces = {"text/html;charset=UTF-8"})
@ResponseBody
public Object viewAffiche(HttpSession session,@RequestParam Integer id){
String result = "";
if(null == id || "".equals(id)){
result = "nodata";
}else{
try {
Affiche affiche = new Affiche();
affiche.setId(id);
affiche = afficheService.getAffiche(affiche);
if(null != affiche && affiche.getCode() != null && affiche.getTitle() != null){
affiche.setTitle(HtmlEncode.htmlDecode(affiche.getTitle()));
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(Date.class,new JsonDateValueProcessor());
result = JSONObject.fromObject(affiche,jsonConfig).toString();
}
} catch (Exception e) {
// TODO Auto-generated catch block
result = "failed";
}
}
return result;
}
@RequestMapping("/informanage/delAffiche.html")
@ResponseBody
public Object delAffiche(HttpSession session,@RequestParam Integer id){
if(null == id || "".equals(id)){
return "nodata";
}else{
try {
Affiche affiche = new Affiche();
affiche.setId(id);
afficheService.deleteAffiche(affiche);
} catch (Exception e) {
// TODO Auto-generated catch block
return "failed";
}
return "success";
}
}
@RequestMapping(value="/informanage/addAffiche.html",method=RequestMethod.POST)
public ModelAndView addAffiche(@ModelAttribute("addAffiche") Affiche affiche,HttpSession session){
logger.debug("================addAffiche====================");
if(session.getAttribute(Constants.SESSION_BASE_MODEL) == null){
return new ModelAndView("redirect:/");
}else{
try {
User sessionUser = ((User)session.getAttribute(Constants.SESSION_USER));
affiche.setPublisher(sessionUser.getLoginCode());
affiche.setPublishTime(new Date(System.currentTimeMillis()));
if(null != affiche.getTitle() && !affiche.getTitle().equals("")){
affiche.setTitle(HtmlEncode.htmlEncode(affiche.getTitle()));
}
afficheService.addAffiche(affiche);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return new ModelAndView("redirect:/informanage/affiche.html");
}
@RequestMapping(value="/informanage/modifyAffiche.html",method=RequestMethod.POST)
public ModelAndView modifyAffiche(@ModelAttribute("addAffiche") Affiche affiche,HttpSession session){
if(session.getAttribute(Constants.SESSION_BASE_MODEL) == null){
return new ModelAndView("redirect:/");
}else{
try {
User sessionUser = ((User)session.getAttribute(Constants.SESSION_USER));
affiche.setPublisher(sessionUser.getLoginCode());
affiche.setPublishTime(new Date(System.currentTimeMillis()));
if(null != affiche.getTitle() && !affiche.getTitle().equals("")){
affiche.setTitle(HtmlEncode.htmlEncode(affiche.getTitle()));
}
afficheService.modifyAffiche(affiche);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return new ModelAndView("redirect:/informanage/affiche.html");
}
@RequestMapping("/informanage/affiche.html")
public ModelAndView affiche(HttpSession session,Model model,
@RequestParam(value="p",required=false)Integer p,boolean isPortal){
Map<String,Object> baseModel= (Map<String,Object>)session.getAttribute(Constants.SESSION_BASE_MODEL);
List<Affiche> afficheList = null;
if(baseModel == null){
return new ModelAndView("redirect:/");
}else{
Affiche affiche = new Affiche();
//pages
PageSupport page = new PageSupport();
try{
if(isPortal){
page.setTotalCount(afficheService.portalCount());
}else{
page.setTotalCount(afficheService.count());
}
}catch (Exception e1) {
page.setTotalCount(0);
}
if(page.getTotalCount() > 0){
if(p != null)
page.setPage(p);
if(page.getPage() <= 0)
page.setPage(1);
if(page.getPage() > page.getPageCount())
page.setPage(page.getPageCount());
affiche.setStarNum((page.getPage() - 1) * page.getPageSize());
affiche.setPageSize(page.getPageSize());
try {
if(isPortal){
afficheList = afficheService.getPortalAfficheList(affiche);
}else{
afficheList = afficheService.getAfficheList(affiche);
}
}catch (Exception e) {
e.printStackTrace();
afficheList = null;
if(page == null){
page = new PageSupport();
page.setItems(null);
}
}
page.setItems(afficheList);
}else{
page.setItems(null);
}
model.addAllAttributes(baseModel);
model.addAttribute("page", page);
}
return new ModelAndView("informanage/affiche");
}
}