spring mvc

一、spring jar

core package MVC AOP log related Database related
spring-aop-4.3.9.RELEASE.jar spring-web-4.3.9.RELEASE.jar aspectjweaver-1.8.10.jar commons-logging-1.1.1.jar spring-tx-4.3.9.RELEASE.jar
spring-beans-4.3.9.RELEASE.jar spring-webmvc-4.3.9.RELEASE.jar log4j-1.2.17.jar spring-jdbc-4.3.9.RELEASE.jar
spring-context-4.3.9.RELEASE.jar
spring-core-4.3.9.RELEASE.jar
spring-expression-4.3.9.RELEASE.jar

Second, spring-MVC configuration


  • Configuration ```xml in web.xml file



<filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

```

  • Spring-MVC configuration

    <!--视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <!-- 配置前缀 -->
    <property name="prefix" value="/WEB-INF/view/"/>
    <!-- 配置后缀 -->
    <property name="suffix" value=".jsp"/>
    </bean>

Third, the use of java

1. Get request parameters
@Controller
public class Hello {
    //请求映射
    @RequestMapping("/hello")
    public String helloword(){
        //拼接上spring-MVC配置文件中的前缀和后缀
        return "hello";
    }
}
@RequestMapping("/hello")
/**
 * 接受参数
 * @RequestParam 注解贴在形参的前面
 *  value:参数的名称 default 形参的name
 *  required:参数是否为必须的 有@RequestParam注解时 默认值是true(不传参会报错,当有defaultValue时不会报错) 没有注解时传不传都行
 *  defaultValue :参数的默认值 没有传参时使用默认值 ; age=  传参却为空时是null 或""(String);
 */
public String paramTest(String name,@RequestParam(required = true)Integer age){
    System.out.println("name = [" + name + "], age = [" + age + "]");
    return "hello";
}

/**
 * 当返回的参数数值为空串时: String显示"";基本数据类型会报错;其他数据类型会显示null
 * 当返回的参数中没有pojo类中的数据时:String类型是"null"基本数据类型会显示各自的默认值;其他数据类型会显示null
 */
@RequestMapping("/pojo")
public String PojoTest(Person person){
    System.out.println("person = [" + person + "]");
    System.out.println("-"+person.getName()+"-");
    return "hello";
}
2. Set the response information
@RequestMapping("test1")
public ModelAndView test1(String name,Integer age){
    //创建模型视图对象
    ModelAndView m = new ModelAndView();
    //指定视图
    m.setViewName("hello");
    //添加模型对象 (设置到 request作用域中)
    m.addObject("name",name);
    m.addObject("age",age);
    return m;
}
@RequestMapping("test2")
//直接在参数列表中创建Map (设置Map到 request作用域中)
public String test2(String name,Integer age,Map<String,Object> map){
    map.put("name",name);
    map.put("age",age);
    return "hello";
}
3. File upload
@RequestMapping("file")
    public String testFile(HttpServletRequest request, MultipartFile file) throws IOException {
        //获取文件的io流
        InputStream is = file.getInputStream();
       //获取文件名
        String fileName = file.getOriginalFilename();
        String [] strs = fileName.split("\\.");
        if(strs.length>=2){
            fileName = UUID.randomUUID()+"."+strs[strs.length-1];
        }else{
            fileName = UUID.randomUUID()+"";
        }
        //获取项目的决定路径
        String savePath = request.getServletContext().getRealPath(File.separator+"upload");
        //创建文件对象UUID.randomUUID() 保证文件名唯一
        File saveFile = new File(savePath+File.separator + fileName);
        //查看目录是否存在
        if(!saveFile.getParentFile().exists()){
            //创建文件的目录
            saveFile.getParentFile().mkdir();
        }
        //创建输出流对象
        FileOutputStream out = new FileOutputStream(saveFile);
        //copy文件 使用工具类需要导包commons-io-2.5.jar
        IOUtils.copy(is,out);
       /*byte[] b = new byte[1024];
        int n=0;
        while((n=is.read(b))!=-1){
            out.write(b, 0, n);
        }

        is.close();
        out.close();*/

        return "hello";
    }
<!--文件上传 spring-mvc.xml文件配置-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

</bean>
4. Handling exceptions
//@ControllerAdvice注解可以使全局的异常都转发到error页面 而不用每个controller都定义一个处理异常的方法
@ControllerAdvice
public class ErrorContreller {
    //被@ExceptionHandler标注的类只能有异常类型的参数;@ExceptionHandler({Throwable的子类的数组})
    @ExceptionHandler
    public ModelAndView exception(Exception e){
        ModelAndView m = new ModelAndView("error");
        m.addObject("exception",e);
        return m;
    }
}

Fourth, the configuration of springMVC coding interceptor

<!--配置编码过滤器-->
<filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
    <!-- 初始化参数指定编码格式 -->
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Five, spring-MVC type converter

1. Simple types do not require custom type converters
  1. String-->Date@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date date
  2. String-->number@NumberFormat(pattern = "#,###") int number

    2.java custom type converter
    ```java
    /**
  • custom type converter
  • Implement the Converter interface
    • The first generic parameter: the original type
    • Second generic parameter: target type
      */
      @Component
      public class StringBookConverter implements Converter


```

6. Loading static resources

<!--使用默认的servlet处理 可以加载静态资源 只配置default-servlet-handler 会使spring-mvc请求找不到 需要配合下面的设置-->
<mvc:default-servlet-handler/>
<mvc:annotation-driven />
<!-- 
<mvc:annotation-driven>会自动注册RequestMappingHandlerMapping与RequestMappingHandlerAdapter两个Bean,
这是Spring MVC为@Controller分发请求所必需的,并且提供了数据绑定支持,
@NumberFormatannotation支持;
@DateTimeFormat支持;
@Valid支持读写XML的支持(JAXB);
读写JSON的支持(默认Jackson)等功能。
 -->

Seven, the configuration of the interceptor

<!-- 配置拦截器 -->
<mvc:interceptors>
<!-- 拦截全部 -->
    <ref bean="firstInterceptors"/>
<!-- 拦截指定的类型 *:代表一级目录 ; **:代表任意级目录-->
    <mvc:interceptor>
        <mvc:mapping path = "/x/**"/>
        <ref bean="firstInterceptors"/>
    </mvc:interceptor>  
    
</mvc:interceptors>
/**
*方法执行的流程
*  当preHandle返回的是true时
*      preHandle-->servletf发-->postHandle-->afterCompletion
* 当preHandle返回的是false时 只执行 preHandle
*/
@Component
public class FirstInterceptors  implements HandlerInterceptor{
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        System.out.println("FirstInterceptors.preHandle");
        //返回是true放行;false拦截
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("FirstInterceptors.postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("FirstInterceptors.afterCompletion");
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325001790&siteId=291194637
Recommended