SpringMVC学习笔记

SpringMVC快速入门

入门代码实现

导入SpringMVC坐标
<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.3.17</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.3.17</version>
    </dependency>
配置SpringMVC的前端控制器
<!--  配置SpringMVC的前端控制器-->
  <servlet>
    <servlet-name>DispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>DispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>mapping>
创建Controller类和视图界面,使用注解配置Controller类中业务方法的映射地址
@Controller
public class UserController {

    @RequestMapping("/quick")
    public String save(){
        System.out.println("Controller save running....");
                return "success.jsp";
    }
}
<html>
<head>
    <title>test</title>
</head>
<body>
    <h1>success!!!</h1>
</body>
</html>
配置SpringMVC核心文件spring-mvc.xml
<!--    Controller的组件扫描-->
    <context:component-scan base-package="com.example.controller"/>

运行测试

SpringMVC的数据响应方式

页面跳转

直接返回字符串
@RequestMapping(value = "/quick",method = RequestMethod.GET,params = {"username"})
    public String save(){
        System.out.println("Controller save running....");
//                return "redirect:/success.jsp";//forward:转发(默认) redirect:重定向
        return "success";
    }
通过ModelAndView对象返回
    @RequestMapping("/quick4")
    public String save4(HttpServletRequest request){
        request.setAttribute("username","王五");
        return "success";
    }

    @RequestMapping("/quick3")
    public String save3(ModelAndView modelAndView){
        modelAndView.addObject("username","李四");
        return "success";
    }

    @RequestMapping("/quick2")
    public ModelAndView save2(){
//        Model:模型 封装数据
//        view:视图 展示数据
        ModelAndView modelAndView = new ModelAndView();
        //设置模型数据
        modelAndView.addObject("username","张三");
        modelAndView.setViewName("success");
        return modelAndView;
    }

回写数据

直接返回字符串
    @RequestMapping("/quick8")
    @ResponseBody //告知SpringMVC框架 不进行视图跳转 直接进行数据响应
    public String save8() throws Exception{
        User user = new User();
        user.setUsername("lisi");
        user.setAge(30);
        //使用json的转换工具将对象转换成json格式字符串返回
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(user);
        return json;
    }

    @RequestMapping("/quick7")
    @ResponseBody //告知SpringMVC框架 不进行视图跳转 直接进行数据响应
    public String save7() throws Exception{
        return "{\"username\":\"zs\",\"age\":18}";
    }

    @RequestMapping("/quick6")
    @ResponseBody //告知SpringMVC框架 不进行视图跳转 直接进行数据响应
    public String save6() throws Exception{
        return "zl";
    }

    @RequestMapping("/quick5")
    public void save5(HttpServletResponse response) throws Exception{
        response.getWriter().print("hello word!");
    }
返回对象或集合
//<!--    MVC注解驱动-->
//        <mvc:annotation-driven/>
@RequestMapping(value = "/quick9",produces = "application/json;charset=UTF-8")
    @ResponseBody //告知SpringMVC框架 不进行视图跳转 直接进行数据响应
    //期望SpringMVC自动将User转换成json格式的字符串
    public User save9() throws Exception{
        User user = new User();
        user.setUsername("lisi");
        user.setAge(30);

        return user;
    }

SpringMVC获得请求数据

SpringMVC可以获得如下类型参数:

  • 基本类型参数

  • POJO类型参数

  • 数组类型参数

  • 集合类型参数

获得基本类型参数
    @RequestMapping("/quick")
    @ResponseBody //不进行页面跳转
    public void save(String username,int age) throws Exception{
        System.out.println(username);
        System.out.println(age);
    }
获取POJO类型参数
    @RequestMapping("/quick1")
    @ResponseBody //不进行页面跳转
    public void save(User user) throws Exception{
        System.out.println(user);
    }
获取数组类型参数
@RequestMapping("/quick2")
    @ResponseBody //不进行页面跳转
    public void save2(String[] strs) throws Exception{
        System.out.println(Arrays.asList(strs));
    }
获取集合类型参数
<html>
<head>
    <title>Title</title>
    <script src="/js/jquery.min.js"/>
    <script>
        var userList = new Array();
        userList.push({username:"zs",age:18});
        userList.push({username:"lisi",age:20});

        $.ajax({
            type:"POST",
            url:"/req/quick4",
            data:JSON.stringify(userList),
            contentType:"application/json;charset=UTF_8"
        });
    </script>
</head>
<body>

</body>
</html>
    @RequestMapping("/quick4")
    @ResponseBody //不进行页面跳转
    public void save4(@RequestBody List<User> userList) throws Exception{
        System.out.println(userList);
    }
请求数据乱码解决
<!--  配置全局过滤filter-->
  <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>
参数绑定注解@requestParam

当请求的参数名称与Controller的业务方法参数名称不一致时使用

    @RequestMapping("/quick5")
    @ResponseBody //不进行页面跳转
    public void save5(@RequestParam(value="name") String username) throws Exception{
       //@RequestParam参数:value(请求参数名称),required(此参数在请求中是否必须包括,默认为true),defaultValue(当没有指定参数时使用默认值赋值)
       System.out.println(username);
    }
获取请求头
//获取请求头
    @RequestMapping("/quick8")
    @ResponseBody //不进行页面跳转
    public void save8(@RequestHeader(value = "User-Agent",required = false) String header) throws Exception{
        System.out.println(header);
    }

    //获取Cookie值
    @RequestMapping("/quick9")
    @ResponseBody //不进行页面跳转
    public void save9(@CookieValue(value = "JSESSIONID",required = false) String cookie) throws Exception{
        System.out.println(cookie);
    }

文件上传

导入fileupload和io坐标
<!--      文件上传坐标导入-->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
    </dependency>

    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.6</version>
    </dependency>
配置文件上传解析器
<!--    配置文件上传解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--        上传文件总大小-->
        <property name="maxUploadSize" value="5242800"/>
<!--        上传单个文件大小-->
        <property name="maxUploadSizePerFile" value="5242800"/>
<!--        上传文件编码类型-->
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>
编写文件上传代码(单文件)
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="/req/quick10" method="post" enctype="multipart/form-data">
        <input name="username" type="text"><br>
        <input name="password" type="password"><br>
        <input type="file" name="upload1">
        <input type="submit" value="提交">
    </form>
</body>
</html>
    @RequestMapping("/quick10")
    @ResponseBody //不进行页面跳转
    public void save10(String name, MultipartFile upload1) throws Exception{
//        获得文件名称
        String originalFilename1 = upload1.getOriginalFilename();
//        保存文件
        upload1.transferTo(new File("E:\\Spring_Project\\"+originalFilename1));
    }
        
编写文件上传代码(多文件)
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="/req/quick11" method="post" enctype="multipart/form-data">
        <input name="username" type="text"><br>
        <input name="password" type="password"><br>
        <input type="file" name="upload">
        <input type="file" name="upload">
        <input type="submit" value="提交">
    </form>
</body>
</html>
    @RequestMapping("/quick11")
    @ResponseBody //不进行页面跳转
    public void save11(String name, MultipartFile[] upload) throws Exception{
//        获得文件名称
        for (MultipartFile multipartFile:upload) {
            String originalFilename = multipartFile.getOriginalFilename();
//        保存文件
            multipartFile.transferTo(new File("E:\\Spring_Project\\" + originalFilename));
        }
    }
posted @ 2022-04-07 13:35  YL_Hello  阅读(17)  评论(0编辑  收藏  举报