spring框架-第六弹

来源:互联网 发布:龙泉驾校网络上课流程 编辑:程序博客网 时间:2024/06/06 09:21

  • 简介
  • 文件上传
    • 配置multipart解析器
    • 修改表单中entype属性
    • 后台controller接受文件
  • 字符过滤器java方式配置
  • 异常处理
    • 首先新建一个异常类
    • controller中抛出异常
    • 异常统一处理
  • 重定向
    • 重定向与转发
    • controller中重定向
    • 携带对象进行重定向

简介

1.文件上传

2.字符过滤器(java方式配置)

3.异常处理

4.重定向(携带属性转发)

文件上传

在许多情况下,开发中需要用户上传一些文件,如图片、文档等,这些数据因为是二进制数据,那么就不能想处理字符串那种方式进行处理了!

为了处理文件,应该分以下几个步骤

配置multipart解析器

在SpringWebAppInitializer.java这个配置文件中,重载customizeRegistration这个方法(这个需要servlet3.0

//文件上传控制器    @Override    protected void customizeRegistration(ServletRegistration.Dynamic registration) {        registration.setMultipartConfig(new MultipartConfigElement("/Users/xxxx/Downloads/idea/temp/spring"));        super.customizeRegistration(registration);    }

修改表单中entype属性

<sf:form method="post" commandName="user" action="display" enctype="multipart/form-data">        name:<sf:input path="name" cssErrorClass="error"/>        <sf:errors path="name" cssClass="error"/>        <br>        password:<sf:password path="password"/>        <sf:errors path="password"/>        <br>        age:<sf:input path="age" type="number"/>        <sf:errors path="age"/>        <br>        picture:<input type="file" name="pic">        <br>        <input type="submit" value="SUBMIT">    </sf:form>

后台controller接受文件

@RequestMapping(value = "display", method = RequestMethod.POST)    public String display(            @Valid            @ModelAttribute("user")                    User user, Errors errors,            @RequestPart("pic")                    MultipartFile file, Map model) throws IOException {        if (file.isEmpty()) {            throw new SimException();        }        String filename = file.getOriginalFilename();        String sim = filename.substring(filename.lastIndexOf('.'));        file.transferTo(                new File("/Users/xxx/Downloads/idea/temp/spring/" + user.getName() + sim));        if (errors.hasErrors()) {            return "login";        }        model.put("user", user);        return "display";    }

@RequestPart("pic") MultipartFile file:接受文件,这个参数类型可以改成byte[],当然一般不用这个

这是一个接受文件的接口对象,通过这个对象可以得到文件名称,也可以便捷的将文件保存下来,即方法transferTo()

字符过滤器(java方式配置)

在SpringWebAppInitializer.java这个文件中重载getServletFilters这个方法

//字符过滤器    @Override    protected Filter[] getServletFilters() {        CharacterEncodingFilter filter = new CharacterEncodingFilter();        filter.setEncoding("utf-8");        filter.setForceEncoding(true);        return new Filter[]{filter};    }

异常处理

在实际开发中,一般应用出现错误时,应该进行捕获并给予用户友好的提示

在一个处理请求的方法中,可以通过try…catch…这个语句来进行异常捕获,但是如果这个应用非常 复杂,那么涉及到的异常也就非常多,并且有时候也是需要抛出自定义异常,那么应该如何进行统一处理呢?

首先新建一个异常类

package cn.simfg.note.web.exception;import org.springframework.http.HttpStatus;import org.springframework.web.bind.annotation.ResponseStatus;@ResponseStatus(value = HttpStatus.NOT_FOUND,reason = "File can't be null")public class SimException extends RuntimeException {}

ResponseStatus这个注解时将异常以异常代码进行映射

controller中抛出异常

//这个是上述controller处理表单的方法中的片段if (file.isEmpty()) {    throw new SimException();}

异常统一处理

当然也可以根据这个if判断的结果来进行处理,但是如果多处有类似情况,自然就不能这个处理了,因为显得代码过于冗余

package cn.simfg.note.web.exception.handler;import org.springframework.web.bind.annotation.ControllerAdvice;import cn.simfg.note.web.exception.SimException;@ControllerAdvicepublic class ExceptionHandler {    @org.springframework.web.bind.annotation.ExceptionHandler(SimException.class)    public String handlerSimException() {        return "file-error";    }}

异常处理类,需要在类上添加@ControllerAdvice注解

@org.springframework.web.bind.annotation.ExceptionHandler(SimException.class):注解中的值表示将捕捉哪种异常

重定向

一般来说,在用户登陆后,需要将页面重定向到另一页面!

重定向与转发

重定向:原始请求结束,并且会发起一个新的GET请求,原始请求中所带的模型数据也随着请求一起消亡了,这也就意味着在新的请求中没有任何模型数据。页面上的体现就是url改变

转发:原始请求不结束,会携带原始请求中模型数据,页面上url不变

controller中重定向

@RequestMapping(value = "list")    public String list(){        return "redirect:flash";    }

携带对象进行重定向

有时候希望这个用户登录后,不在去数据库中查询这个用户的信息,而是直接使用原始请求中的数据,当然如果这个表单中没有的数据,还是需要进行查询的

@RequestMapping(value = "list")    public String list(RedirectAttributes model){        model.addFlashAttribute("other",getAbc(89));        return "redirect:flash";    }

这种需要进行重定向携带的属性被称为Flash属性

这个方法接受的参数是RedirectAttributes,这就是为设置flash属性的接口,当然这个大部分和Map和Model 一样

这样设置后,在flash请求中就可以接受到这个参数

@RequestMapping("flash")    public String flash(Model model,int id){        if(model.containsAttribute("other")){            System.out.println("success ...");        }        return "other";    }