SpringMVC常用注解&请求参数绑定&回显

@RequestMapping

  1. path 指定请求路径的url

  2. value value属性和path属性是一样的

  3. mthod 指定该方法的请求方式

  4. params 指定限制请求参数的条件

  5. headers 发送的请求中必须包含的请求头

  • PostMapping
  • GetMapping

请求参数绑定

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Z3fIhCSr-1607603076836)(C:\Users\hello\AppData\Roaming\Typora\typora-user-images\image-20201114163814684.png)]

1.收集普通参数

  • 提交表单的name名称与参数名称相同即可(get方式一样可以获取)

  • 区分大小写

  • 不同的话的可以使用@Requestparam

    (@RequestParam(value="username",required=false)String name)
    
    1. value:请求参数中的名称

    2. required:请求参数中是否必须提供此参数,默认值是true,必须提供

  • 获取请求获取占位符的参数 @PathVariable

    <form action="#"   th:object="${tag}" th:action="*{id}==null ? @{/admin/tags} : @{/admin/tags/{id}(id=*{id})}" method="post"  class="ui form">
        //*{id}是获得对象(th:object="${tag}")的属性
    
    @PostMapping("/tags/{id}")
    public String editPost(@PathVariable Long id)
    

2.收集javabean

  • 只要form表单名和javabean的属性名相同即可

前端:cc.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>首页</h1>
<form th:action="@{/hellopojo}" method="get">
    <div><input name="username" type="text" placeholder="用户名"/> </div>
    <div><input name="password" type="text" placeholder="密码" /></div>
    <div> <input type="submit" value="提交"></div>
</form>
</body>
</html>

controller:

package com.Controller;

import com.Pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller

public class TestController {
    @RequestMapping("/")
    public String index(){
        return "cc";
    }
    @RequestMapping("/hellopojo")
    public String testpojo(User user,Model model){
        System.out.println(user.getUsername()+"___>"+user.getPassword());
        user.setUsername("陈伟斌");
        model.addAttribute("user",user);
        return "hello";
    }

}

回显:hello.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>hello cwb</h1>
<input name="name" th:value="${user.username}">
</body>
</html>

3.收集数组

  • checkbox 的name名必须全都相同,且与controller方法参数的数组名相同

前端:cc.html

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YHPhaK2j-1607603076840)(C:\Users\hello\AppData\Roaming\Typora\typora-user-images\image-20201114174043900.png)]

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
爱好:
<form th:action="@{/hobby}" method="post">
    <table align="center">
        <tr>
            <td>爱好</td>
            <td><input type="checkbox" name="hobby" value="篮球">篮球</td>
            <td><input type="checkbox" name="hobby" value="足球">足球</td>
            <td><input type="checkbox" name="hobby" value="排球">排球</td>
            <td><input type="checkbox" name="hobby" value="羽毛球">羽毛球</td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="提交">
            </td>
        </tr>
    </table>

</form>
</body>
</html>

后端:

  @RequestMapping("/hobby")
    public String testhobby(String[] hobby,Model model){
        for(String i : hobby){
            System.out.println("--->"+i);
        }
      List<String> list= Arrays.asList(hobby);
        model.addAttribute("list",list);
        return "hello";
    }

前端循环回显:

<h1> 遍历输出hobby</h1>
<div th:each="hobby : ${list}">
    <input  th:value="${hobby}">
</div>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qSnaXOoF-1607603076842)(C:\Users\hello\AppData\Roaming\Typora\typora-user-images\image-20201114174349128.png)]

4.收集List<JavaBean>

将List<JavaBean>封装到一个javabean中

  • 原则还是和javabean中的属性名保持一致
  • 然后通过数组对应List

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-N2Z3PKhk-1607603076845)(C:\Users\hello\AppData\Roaming\Typora\typora-user-images\image-20201114180436393.png)]

form th:action="@{/client}">
    <input name="cNmae">
    <table border="2" align="center">

        <caption><h2>批量注册员工</h2></caption>
        <tr>
            <td><input type="text" name="user[0].username" value="哈哈"/></td>
            <td><input type="text" name="user[0].password" value="7000"/></td>
        </tr>
        <tr>
            <td><input type="text" name="user[1].username" value="呵呵"/></td>
            <td><input type="text" name="user[1].password" value="7500"/></td>
        </tr>
        <tr>
            <td><input type="text" name="user[2].username" value="班长"/></td>
            <td><input type="text" name="user[2].password" value="8000"/></td>
        </tr>
        <tr>
            <td><input type="text" name="user[3].username" value="键状哥"/></td>
            <td><input type="text" name="user[3].password" value="8000"/></td>
        </tr>
        <tr>
            <td colspan="2" align="center">
                <input type="submit" value="批量注册"/>
            </td>
        </tr>
    </table>
</form>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qZevYQiK-1607603076847)(C:\Users\hello\AppData\Roaming\Typora\typora-user-images\image-20201114180222279.png)]

contoller:

    @RequestMapping("/client")
    public String testclient(Client client){
        System.out.println("----"+client.getcNmae());
        for(User i : client.getUser()){
            System.out.println("--->"+i.getUsername());
        }

        return "hello";
    }

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8J2LE4RR-1607603076849)(C:\Users\hello\AppData\Roaming\Typora\typora-user-images\image-20201114180314023.png)]

5.收集多个模型

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-A40lhJA3-1607603076850)(C:\Users\hello\AppData\Roaming\Typora\typora-user-images\image-20201114180610518.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cJi2hcSp-1607603076851)(C:\Users\hello\AppData\Roaming\Typora\typora-user-images\image-20201114180634375.png)]

6.自定义参数转换(字符串转日期)

配置自定义类型转化器

基本数据类型的数据springMVC框架可以自动为我们完成数据封装到参数,但是有些自定义的日期字符串,无法封装为java日期格式。因此需要自定义类型转化器

  • 实现Converter接口来实现自定义参数转换

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TxLEY3QK-1607603076853)(C:\Users\hello\AppData\Roaming\Typora\typora-user-images\image-20201114181550043.png)]

    //String转Date
    public class StringConvertDate  implements Converter<String, Date> {
    
        public Date convert(String s) {
            try {
              // 前端输入 2020/9/20 转化为date  
                return new SimpleDateFormat("yyyy/MM/dd").parse(s);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
    
  • springMVC.xml配置转化器

    FormattingConversionServiceFactoryBean

      <!-- 转换器 -->
       <mvc:annotation-driven conversion-service="myConversionService" />
        <bean id="myConversionService"
              class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
            <property name="converters">
                <list>
                    <bean class="com.ConvertUtil.StringConvertDate"/>
                </list>
            </property>
        </bean>
    
     @RequestMapping("/convert")
        public String testconvert(Date date){
            System.out.println(date);
            return "hello";
        }
    

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FdV6BWm7-1607603076855)(C:\Users\hello\AppData\Roaming\Typora\typora-user-images\image-20201114201015880.png)]

    mvc:annotation-driven conversion-service="myConversionService"相当于进行了如下配置,最后把converter放到了RequestMappingHandlerAdapter适配器中

        <!-- 自定义webBinder -->
        <bean id="customBinder"
            class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
            <!-- 使用converter进行参数转 -->
            <property name="conversionService" ref="myConversionService" />
        </bean>
    
    
        <!-- 注解适配器 -->
        <bean
            class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
            <!-- 在webBindingInitializer中注入自定义属性编辑器、自定义转换器 -->
            <property name="webBindingInitializer" ref="customBinder"></property>
        </bean>
    

    配置去除字符串转换器

    public class StringTrimConverter implements Converter<String, String> {
    
        @Override
        public String convert(String source) {
            try {
                //去掉字符串两边空格,如果去除后为空设置为null
                if(source!=null){
                    source = source.trim();
                    if(source.equals("")){
                        return null;
                    }
                }
                
            } catch (Exception e) {
                e.printStackTrace();
            }
            return source;
        }
    }
    =====================================
        只需在转换器set配置中添加bean
        <list>
                    <bean class="cn.itcast.ssm.controller.converter.CustomDateConverter"/>
                    <bean class="cn.itcast.ssm.controller.converter.StringTrimConverter"/>
                </list> 
    

7.使用原生的ServletAPI

只需要在控制器的方法参数定义HttpServletRequest和HttpServletResponse对象

@ModelAttribute

  1. 作用:

    • 出现在方法上:便是当前方法会在控制器方法执行前执行

         /*** 作用在方法,先执行 * @param name * @return */
          @ModelAttribute
          public User showUser()
          {
              System.out.println("showUser执行了...");
              // 模拟从数据库中查询对象
              User user = new User();
              user.setUsername("哈哈");
              user.setPassword("123");
              return user;
          }
          /*** 修改用户的方法
           * @param cookieValue
           * @return */
      
          @RequestMapping(path="/updateUser")
          public String updateUser(User user) {
              System.out.println(user.getUsername()); return "hello";
          }
      //自动填充在User上
      

      第二种方式:无返回值

         /*** 作用在方法,先执行 * @param name * @return */
          @ModelAttribute
          public void showUser(Map<String,User> map)
          {
              System.out.println("showUser执行了...");
              // 模拟从数据库中查询对象
              User user = new User();
              user.setUsername("哈哈");
              user.setPassword("123");
              map.put("user1",user);
      
          }
          /*** 修改用户的方法
           * @param cookieValue
           * @return */
      
          @RequestMapping(path="/updateUser")
          public String updateUser(@ModelAttribute(value = "user1") User user) {
              System.out.println(user.getUsername()); return "hello";
          }
      
      
    • 出现在参数上:给指定的参数赋值

  2. 引用场景:提交表单的数据不是完整的实体数据,保证没有提交的数据使用数据库原来的数据。

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ATb0qN3G-1607603076857)(C:\Users\hello\AppData\Roaming\Typora\typora-user-images\image-20201114210818857.png)]

前端传入的数据和后端查询的数据共同组成了user对象

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-G2DneS4X-1607603076858)(C:\Users\hello\AppData\Roaming\Typora\typora-user-images\image-20201114210922508.png)]

@PathVariable

  1. 作用:拥有绑定url中的占位符的。例如:url中有/delete/{id},{id}就是占位符

  2. Restful风格的URL

  • 请求路径一样,可以根据不同的请求方式去执行后台的不同方法
  1. restful风格的URL优点:
  • 结构清晰
  • 符合标准
  • 易于理解
  • 扩展方便
<form action="#"   th:object="${tag}" th:action="*{id}==null ? @{/admin/tags} : @{/admin/tags/{id}(id=*{id})}" method="post"  class="ui form">
    //*{id}是获得对象(th:object="${tag}")的属性
@PostMapping("/tags/{id}")
public String editPost(@PathVariable Long id)

@RequestHeader

  1. 作用:获取指定的请求头的信息

  2. 属性:

    value:指定请求头的名称

    @RequestMapping("/hello") 
    public String sayHello(@RequestHeader(value="Accept") String header) 
    { System.out.println(header); return "success"; }
    

@CookieValue

  1. 作用:获取指定cookie的值

  2. 属性:

    value:cookie名称

    @RequestMapping("/hello") 
    public String sayHello(@CookieValue(value="JSESSIONID") String cookieValue) 
    { System.out.println(cookieValue); return "success"; }
    

@SessionAttributes

  1. 作用:多次执行控制器方法之间参数共享 (直接用HttpSession更好?)

@RequestBody与ResponseBody

  • 将请求的json数据转化为java对象
  • 将java对象转化为json数据
1.需要导入Jackson的jar包
  • jackson-core
  • jackson-annotions
  • jackson-databind
 <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-core</artifactId>
          <version>2.9.6</version>
      </dependency>
      <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
          <version>2.9.6</version>
      </dependency>
      <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-annotations</artifactId>
          <version>2.9.6</version>
      </dependency>
2 .创建ajax请求

注意:

  • thymeleaf模板下的url必须写成[[@{/json}]]
  • data的json数据必须引号括起来,且必须在一行,不要换行

1.将List转化为json

注意回调函数:

  • 用List转化为json,前端相当于通过数组获取,即对象存在数组中
    - [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HYflq5ZL-1607603076859)(C:\Users\hello\AppData\Roaming\Typora\typora-user-images\image-20201115131136305.png)]

- [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4hXBZcQP-1607603076860)(C:\Users\hello\AppData\Roaming\Typora\typora-user-images\image-20201115131021733.png)]

<script>
    $(function(){
        $("#btn").click(
            function(){
                $.ajax(
                    {
                        url:"[[@{/json}]]",
                        type:"post",
                        //预计服务器返回的数据类型
                        dataType:"json",
                        contentType:"application/json;charset=UTF-8",
                        data:'{"username":"陈伟斌","password":"1234"}',
                        success:function(data){
                            console.log(data);
                            var json="";
                            for(var i=0;i<data.length;i++){
                                json+=data[i].username;
                                json+=data[i].password;
                            }
                            alert(json);
                        }
                    });
            });
    });
</script>

后端

 @RequestMapping("/json")
    public @ResponseBody List testjson(@RequestBody User user) {
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        List<User> list=new ArrayList();
        User user1=new User("尼玛","77777");
        User user2=new User("niba","99999");
        User user3=new User("你爹","88888");
        list.add(user1);
        list.add(user2);
        list.add(user3);
        return list;
    }

2.将Map转化为json

注意回调函数

  • 将Map转化为json,相当于从map对象的属性中获取值
    - [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-N1QTqurB-1607603076862)(C:\Users\hello\AppData\Roaming\Typora\typora-user-images\image-20201115131237570.png)]
<script>
    $(function(){
        $("#btn2").click(
            function(){
                $.ajax(
                    {
                        url:"[[@{/json2}]]",
                        type:"post",
                        //预计服务器返回的数据类型
                        dataType:"json",
                        contentType:"application/json;charset=UTF-8",
                        data:'{"username":"陈伟斌","password":"1234"}',
                        success:function(data){
                            console.log(data);
                            var json="";
                            json=data.boy.username+data.girl.username;
                            alert(json);
                        }
                    });
            });
    });
</script>

后端:

 @RequestMapping("json2")
    public @ResponseBody Map testJson3(@RequestBody String body){
        Map map =new HashMap();
        User user1=new User("陈伟斌","123");
        User user2=new User("刘亦菲","98594");
        map.put("boy",user1);
        map.put("girl",user2);
        System.out.println(body);
        return map;
    }

mvc:resources

当DispatcherServlet拦截/开头的所有请求,对静态资源的访问就报错:我们需要配置对静态资源的解析,多静态资源不过滤

    <!-- 静态资源 解析 -->
    <mvc:resources location="/js/" mapping="/js/**" />
    <mvc:resources location="/img/" mapping="/img/**" />
 1. location元素表示webapp目录下的包下的所有文件
2. mapping元素表示以/static开头的所有请求路径,如/static/a 或者/static/a/b

/**就表示不管有多少层,都对其进行解析,/*代表的是当前层的所有资源…

return “/blog” return “redirect:/blog"

return “/blog” 继续请求业务方法

);
User user2=new User(“刘亦菲”,“98594”);
map.put(“boy”,user1);
map.put(“girl”,user2);
System.out.println(body);
return map;
}


## mvc:resources

**当DispatcherServlet拦截/开头的所有请求,对静态资源的访问就报错:我们需要配置对静态资源的解析**,多静态资源不过滤

```xml
    <!-- 静态资源 解析 -->
    <mvc:resources location="/js/" mapping="/js/**" />
    <mvc:resources location="/img/" mapping="/img/**" />
 1. location元素表示webapp目录下的包下的所有文件
2. mapping元素表示以/static开头的所有请求路径,如/static/a 或者/static/a/b

/**就表示不管有多少层,都对其进行解析,/*代表的是当前层的所有资源…

return “/blog” return “redirect:/blog"

return “/blog” 继续请求业务方法

return “redirect:/blog" 浏览器重新发起一次请求,例如添加信息之后,用来刷新页面

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值