4、表单提交、拦截器与文件上传

 1          表单提交,如下

//添加两个方法
@RequestMapping("/add")
public String add(){
    return "blogAdd";
}

@PostMapping("/add")
public  String add(@RequestParam String title, @RequestParam String content, Model m){
    m.addAttribute("title", title);
    m.addAttribute("content", content);

    return title == "" ? "blogAdd" : "redirect:/blog/get?title="+title+content;
}
 
<!—如果是get方式请求add返回blogAdd页面
如果是post方式请求add,如果title为空返回blogAdd页面,否则跳转/blog/get页面-->
<div th:text="${title}">title</div>
<div th:text="${content}">content</div>

<form method="post">
    <input type="text" name="title" />
    <input type="text" name="content" />
    <input type="submit" />
</form>

1.1         “redirect:/uri”可以跳转到相应页面

1.2         @PostMapping("/uri”)映射post的请求url

1.3         @PutMapping、@DeleteMapping映射put、delete方式的请求

 

2          Interceptor(拦截器)与servletapi中的filter功能类似

2.1         下图是spring mvc的处理流程,请求经过dispatcher servlet的调度后,会顺序执行一系列的interceptor(拦截器)并执行其中的方法,拦截器有三个方法

4、表单提交、拦截器与文件上传

2.2         Bool preHandle,在步骤5处执行,为true则继续下一个拦截器,否则返回

2.3         Void postHandle,在步骤10处执行

2.4         Void afterHandle,在步骤12处执行

 

3          使用拦截器

3.1         拦截器必须实现HandlerInterceptorAdapter接口,建立拦截器如下

//创建拦截器,并重写preHandle方法
public class MyInterceprtorextends HandlerInterceptorAdapter {

   
@Override
   
public boolean preHandle(
            HttpServletRequest request
,
           
HttpServletResponse response,
           
Object handle
    )
throws Exception{

       
//拦截器,输出时间和拦截器信息
       
SimpleDateFormat f = newSimpleDateFormat("yyyy-MM-dd HH:mm:ss");
       
System.out.println(f.format(newDate()) + "  myInterceptor preHandle function");
       
//可在此判断用户权限,权限通过则为true继续,否则为false直接跳转
       
return true;
   
}
}

3.2         设置拦截器

//添加拦截器必须实现WebMvcConfigurerAdapter抽象类
//
需重写addInterceptors方法
@Configuration
public class WebMvcConfigextends WebMvcConfigurerAdapter {

   
@Override
   
public void addInterceptors(InterceptorRegistry registry){

       
//添加拦截器
        //registry.addInterceptor(newMyInterceprtor());
        //
拦截器增加url限制
       
registry.addInterceptor(newMyInterceprtor()).addPathPatterns("/blog/getcontent/**");
   
}
}

 

4          文件上传

4.1         文件上传需增加属性配置enctype为multipart/form-data,如下(标红)

<form method=”post” enctype=”multipart/form-data”>
    <input type=”text” name=”title” value=”tianmaying”>
    <input type=”file” name=”avatar”>
    <input type=”submit”>
</form>

4.2         服务端代码

//get请求页面
@GetMapping("/getfile")
public String getfile(){
    return "getfile";
}

//post请求地址
@PostMapping("/upload")
@ResponseBody
public String getfile(@RequestParam("file") MultipartFile file) throws Exception{

    //获取文件的字节码
    byte[] bytes =  file.getBytes();
    //直接输出信息
    return "file upload success";
}