Spring MVC基础控制类代码实例--Java免费学习网

 以下是Java免费学习网整理的Spring MVC实现中基础控制类:  

package com.app.common.spring.mvc;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.app.permission.model.Department;
import com.app.permission.model.User;
import com.util.SessionManager;

public abstract class BaseController extends MultiActionController{
 
 /**
  * OA 单点登录用户返回 OA ID 否则返回用户 ID
  * 
  * @param request
  * @return
  * @throws Exception
  */
 protected String getUserId(HttpServletRequest request) throws Exception{
  User user = (User)SessionManager.getUserInfo(request);
  if (user.getId() == null){
   return user.getOaId();
  } else {
   return user.getId()+"";
  }
 }
 /**
  *  
  * 
  * @param request
  * @return
  * @throws Exception
  */
 protected Department getUserDept(HttpServletRequest request) throws Exception{
  User user = (User)SessionManager.getUserInfo(request);
  
  Department department = SessionManager.getShowDepartment(request);
  return department;
   
 }
 
 /**
  * 获得当前登录的用户
  * 
  * @param request
  * @return
  * @throws Exception
  */
 protected User getUser(HttpServletRequest request) throws Exception{
  User user = (User)SessionManager.getUserInfo(request);
  return user;
 }
 
 /**
  * 获得当前用户的部门 ( 两级部门 )
  * Java免费学习  Java自学网 http://www.javalearns.com
  * @param request
  * @return
  * @throws Exception
  */
 protected Department getDepartment(HttpServletRequest request) throws Exception{
  User user = this.getUser(request);
  return user.getDepartment();
 }
 
    /**
     * 初始化binder的回调函数.
     * 默认以DateUtil中的日期格式设置DateEditor及允许Integer,Double的字符串为空.
     *
     * @see MultiActionController#createBinder(HttpServletRequest,Object)
     */
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
     SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        binder.registerCustomEditor(Integer.class, new CustomNumberEditor(Integer.class, true));
        binder.registerCustomEditor(Double.class, new CustomNumberEditor(Double.class, true));
  binder.registerCustomEditor(Long.class, null, new CustomNumberEditor(Long.class,true));
  binder.registerCustomEditor(Float.class, null, new CustomNumberEditor(Float.class,true));
        binder.registerCustomEditor(BigDecimal.class, null, new CustomNumberEditor(BigDecimal.class,true));
        binder.registerCustomEditor(Byte.class, null, new CustomNumberEditor(Byte.class,true));
    }

    /**
     * 从Request中绑定对象并进行校验.
     * Spring MVC中的Bind函数未完全符合需求,因此参考原代码进行了扩展
     *
     * @return 校验错误
     * @see #preBind(HttpServletRequest,Object,ServletRequestDataBinder)
     */
    protected BindingResult bindObject(HttpServletRequest request, Object command) throws Exception {
        Assert.notNull(command);

        //创建Binder
        ServletRequestDataBinder binder = createBinder(request, command);
        //回调函数,供子类扩展对binder做出更进一步设置,并进行不能由binder自动完成的绑定
        preBind(request, command, binder);

        //绑定
        binder.bind(request);

        //校验
        Validator[] validators = getValidators();

        if (validators != null) {
            for (int i=0;i<validators.length;i++) {
             Validator validator = validators[i];
                if (validator.supports(command.getClass())) {
                 ValidationUtils.invokeValidator(validator, command, binder.getBindingResult());
                }
            }
        }
        return binder.getBindingResult();
    }

    /**
     * 回调函数,在BindObject的最开始调用。负责
     * 1.继续对binder进行设置
     * 2.绑定一些不能由Binder自动绑定的属性.这些属性通常是需要查询数据库来获得对象的绑定.
     * 要注意设置这些属性为disallow. eg.
     * <pre>binder.setDisallowedFields(new String[]{"image","category"});</pre>
     *
     * @see #bindObject(HttpServletRequest, Object)
     * @see org.springframework.web.bind.ServletRequestDataBinder#setDisallowedFields(String[])
     */
    protected void preBind(HttpServletRequest request, Object object, ServletRequestDataBinder binder) throws Exception {
        //在子类实现
    }
    /**
     * 回调函数.校验出错时,将出错的对象及出错信息放回model.
     */
    protected ModelAndView onBindError(HttpServletRequest request, BindingResult result, ModelAndView mav, String viewName) {
     mav.setViewName(viewName);
        mav.addAllObjects(result.getModel());
        return mav;
    }


    /**
     * 回调函数,声明CommandName--对象的名字,默认为首字母小写的类名.
     *Java免费学习  Java自学网 http://www.javalearns.com
     * @see #bindObject(HttpServletRequest, Object)
     */
    protected String getCommandName(Object command) {
     String commandName = command.getClass().getName();
  int lastDot = commandName.lastIndexOf(".");
  if(lastDot!=-1){
   commandName = commandName.substring(lastDot+1);
  }
  int l = commandName.length();
  if(l>1){
   commandName = commandName.substring(0,1).toLowerCase()+commandName.substring(1);
  }else if(l==1){
   commandName = commandName.toLowerCase();
  }
  return commandName;
    }

    /**
     * 向页面传递参数
     * @param request
     * @param message
     */
    protected void sendMessage(HttpServletRequest request, String message) {
        if (StringUtils.isNotBlank(message)) {
         List messages = (List)request.getAttribute("messages");
         if(messages==null){
          messages = new ArrayList();
         }
         messages.add(message);
         request.setAttribute("messages",messages);
        }
    }
    protected String uploadImageToFile(HttpServletRequest request, String uploadDir, String parameterName,String saveFileName) throws IOException {

        String fileRelativePath = null;
        MultipartHttpServletRequest multipartRequest = null;

        try {
            multipartRequest = (MultipartHttpServletRequest) request;
        }
        catch (ClassCastException e) {
            return null; //only for testcast 中,mockservlet不能转为MultipartRequest
        }

        MultipartFile multipartFile = multipartRequest.getFile(parameterName);
        if (StringUtils.isNotEmpty(multipartFile.getOriginalFilename())) {
            String fileName = multipartFile.getOriginalFilename();
            String extName = "";
            if(fileName.lastIndexOf(".")!=-1){
                extName = fileName.substring(fileName.lastIndexOf("."));
            }
            String fileRealPath = getServletContext().getRealPath(uploadDir) + File.separator + saveFileName+extName;
            File file = new File(fileRealPath);
            multipartFile.transferTo(file);
            fileRelativePath = uploadDir + "/" + saveFileName+extName;
        }

        return fileRelativePath;
    }

    protected String uploadFile(HttpServletRequest request, String uploadDir, String parameterName,String saveFileName) throws IOException {

        String fileRelativePath = null;
        MultipartHttpServletRequest multipartRequest = null;

        try {
            multipartRequest = (MultipartHttpServletRequest) request;
        }
        catch (ClassCastException e) {
            return null; //only for testcast 中,mockservlet不能转为MultipartRequest
        }

        MultipartFile multipartFile = multipartRequest.getFile(parameterName);
        if (multipartFile!=null && StringUtils.isNotEmpty(multipartFile.getOriginalFilename())) {
            String fileName = multipartFile.getOriginalFilename();
            String extName = "";
            if(fileName.lastIndexOf(".")!=-1){
                extName = fileName.substring(fileName.lastIndexOf("."));
            }
            String fileRealPath = getServletContext().getRealPath(uploadDir) + File.separator + saveFileName+extName;
            File file = new File(fileRealPath);
            multipartFile.transferTo(file);
            fileRelativePath = uploadDir + "/" + saveFileName+extName;
            
        }
       

        return fileRelativePath;
    }
    
    /**
     * 处理出错信息
     * @param br
     * @throws Exception
     */
    protected void validationInputInfo(BindingResult br) throws Exception{
      if(br!=null && br.hasErrors()){
       List list = br.getAllErrors();
       for(int i=0;i<list.size();i++){
        System.out.println( i+"."+list.get(i) );
       }
        throw new Exception("您输入的信息有误,请仔细核对。如果核对无误,仍然不能提交,请联系系统管理员。");
      }
    }

}

文章转载自 http://www.javalearns.com/Html/?1619.html


更多Java知识学习请访问 Java免费学习网  http://www.javalearns.com

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值