SpringMVC learning log three

I. Review

1.1 If the parameter is received datetime type, need to be processed in the controller.

     @InitBinder

     Entity type class encapsulates time @DateTimeFormat

1.2 How to save data so that the data acquisition web page.

  ModelAndView:

  Model: default request scope

  Map:

  HttpServletRequest:

  HttpSession:

  @SessionAttributes(name={})

1.3 deal with static resources.

    If the request address DispatcherServlet process is /, then it will also deal with static resources.

  Used in the configuration file <mvc: default-servlet-handler> does not process the static resources.

1.4 How to use redirection. Redirect

1.5 Springmvc complete ajax function.

    Ajax data type of server response time. html, json

    The result is html @ResponseBody response but it will be garbled. StringHttpMessageConvert.

    The results are Json response type. Jackson need the help of the jar package and @ResponseBody 

Second, file upload

  1. Import jar package

  2. Web page.

  Forms must be post submitted code must be multipart / form-data   file upload text box must be named.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form action="addStudent" method="post" enctype="multipart/form-data" >
        姓名:<input type="text" name="name"><br/> 
        年龄:<input type="text" name="age"><br/> 
        请选择上传的文件:<input type="file" name="myfile" /><br /> 
        <input type="submit" value="上传">
    </form>
</body>
</html>

  3. In springmvc configuration file upload parser.

  <-! Upload the configuration file parser -> 
    <bean the above mentioned id = " the MultipartResolver "  class = " org.springframework.web.multipart.commons.CommonsMultipartResolver " > 
        <! - set the file upload size -> 
        <Property name = " maxUploadSize " value = " 20971520 " > </ Property> 
    </ the bean>

  4. In the control layer processing code

package com.zhiyou100.klb.controller;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class UploadController {

    @RequestMapping("upload")
    public String upload(MultipartFile myfile,HttpServletRequest request) {
        //1.获取文件上传的真实保存路径
        Path = request.getServletContext String () getRealPath (. " / The Upload " ); 
        System. OUT .println (path);
         // 2. Create a file object 
        File File = new new File (path);
         IF (! File.Exists ( )) { 
            file.mkdirs (); 
        } 
        
        // 3. get file name 
        String name = myfile.getOriginalFilename (); 
        the System. OUT .println (name); 
        file targetfile = new new file (path + " / " + name); 
        
        the try {
            FileUtils.writeByteArrayToFile(targetFile, myfile.getBytes());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "redirect:index.jsp";
    }
}

Third, the interceptor (blocking both control layer address filter:.)

  1. Create a class that implements the interface HandlerInterceptor

  2. The method of rewriting the interface

package com.zhiyou100.klb.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class MyInterceptor implements HandlerInterceptor {

    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        System.out.println("请求处理完成后执行的方法");

    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
        System.out.println("==========");

    }

    @Override
    public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("起始点");
        return true;//如果返回true表示允许通过
    }

}

  3. The class created to springmvc configuration file.

  <! - Configuration interceptor -> 
    <MVC: interceptors> 
        <! - may be a plurality of interceptors -> 
        <MVC: Interceptor> 
            ! <- ** represents all subdirectories and user request address - -> 
            <MVC: Mapping path = " / User / ** " /> 
            <MVC:-Mapping the exclude path = " /user/list.do " /> 
            <the bean class = " com.zhiyou100.klb.interceptor.MyInterceptor " > </ the bean> 
        </ MVC: Interceptor> 
    </ MVC: interceptors>

 Fourth, data validation

  1. Import jar package

  2. Add annotations corresponding entity classes

   3. In the control parameter receiving layer.

    @RequestMapping("register")    //requestMapping:表示的就是你的访问地址
    public String register(@Valid Users user,BindingResult br,Model model) {
        if(br.hasErrors()) {
            List<FieldError> fieldErrors = br.getFieldErrors();
            Map<String,Object> errorMsg = new HashMap<>();
            for(FieldError f:fieldErrors) {
                errorMsg.put(f.getField(), f.getDefaultMessage());
            }
            model.addAttribute("errorMsg", errorMsg);
            return "register";
        } else {
            list.add(user);
            return "forward:list";
        }
    }

  4. Receive error messages file .jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    欢迎注册
    <form action="/SpringMVC-user/user/register" method="post">
        账号:<input type="text" name="name" >${errorMsg.name }<br/>
        密码:<input type="text" name="password">${errorMsg.password }<br/>
        电话:<input type="text" name="phone">${errorMsg.phone }<br/>
        <input type="submit" value="注册">
        <input onclick="location.href='javascript:history.go(-1)'" type="button" value="返回">
    </form>
</body>
</html>

  5. Common Annotations

 

Guess you like

Origin www.cnblogs.com/kklb/p/11462419.html