码迷,mamicode.com
首页 > 编程语言 > 详细

Spring Mvc 笔记二之异常和文件上传

时间:2016-04-05 19:58:57      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

   
                                                    spring mvc的异常与文件上传



1.异常:

        spring注解版的异常有局部异常和全局异常
        
       1.局部异常对单个controller有效;(在controller类写一个处理异常的方法)

        

@ExceptionHandler(value={UserException.class})
    public String handlerExceptionTest(UserException e ,HttpServletRequest request){
        request.setAttribute("msg", "用户不存在");
        
        return "error";
    }

 



       2.全局异常对所有的controller有效(在配置文件中配置;用于所有的controller)

      

   <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
      <property name="exceptionMappings">
        <props>
         <prop key="po.UserException">error</prop>
        </props>
      </property>
   </bean>

 

//上边两种方法中使用的异常类UserException是我们自己创建的,继承自一个异常类.  (我通常extends(继承)  RuntimeException或Exception)

 



2.文件上传

     //页面

     form表单设置enctype属性
       

      <form action="/SpringOne/login" method="post" enctype="multipart/form-data" class="hehe">
      用户名<input type="text" name="name"/>
      密码<input type="text" name="pwd"/>
     文件 <input type="file" name="attach"/>
       <input type="submit" value="提交"/> 
      </form>

 


     //

     在配置文件(xxx-servlet.xml)中配置如下代码:

    

      <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

           <property name="maxUploadSize" value="5000000">



           </property>

      </bean>

//controller中

    @RequestMapping(value="/login",method=RequestMethod.POST)
    public  String login(String name,String pwd,HttpSession session,MultipartFile attach) throws UserException, IOException{
        boolean flag=true;
        if(name!=null && !name.equals("")){
            for (User item : list) {
                if(name.equals(item.getName())){
                    //model.addAttribute("user",item);
                    session.setAttribute("user", item);
                
                    flag= false;
                    
                }
        }
            }
            //为true抛出局部异常        
            if(flag){
                throw new UserException();
            }
//文件上传 System.out.println(session.getServletContext().getRealPath(
"/static/upoload")); FileUtils.copyInputStreamToFile(attach.getInputStream(),new File(session.getServletContext().getRealPath("/static/upoload")+File.separator+attach.getOriginalFilename())); return "redirect:/hello"; }

 

Spring Mvc 笔记二之异常和文件上传

标签:

原文地址:http://www.cnblogs.com/xiangtianxiayu/p/5356306.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!