zoukankan      html  css  js  c++  java
  • SpringMVC注解(二)

    四、@RequestParam注解: 绑定单个请求参数值
    如:  public String requestparam1(@RequestParam String username)
        请求中包含username参数(如/requestparam1?username=zhang),则自动传入。
       
    @RequestParam有以下三个参数:
        value:参数名字,即入参的请求参数名字,如username表示请求的参数区中的名字为username的参数的值将传入;
         required:是否必须,默认是true,表示请求中一定要有相应的参数,否则将抛出异常;
         defaultValue:默认值,表示如果请求中没有同名参数时的默认值,设置该参数时,自动将required设为false。
    如:public String requestparam4(@RequestParam(value="username",required=false) String username)
      表示请求中可以没有名字为username的参数,如果没有默认为null,此处需要注意如下几点:
           原子类型:必须有值,否则抛出异常,如果允许空值请使用包装类代替。
           Boolean包装类型:默认Boolean.FALSE,其他引用类型默认为null。
    如果请求中有多个同名的应该如何接收呢?如给用户授权时,可能授予多个权限,首先看下如下代码:
       public String requestparam7(@RequestParam(value="role") String roleList) 
    如果请求参数类似于url?role=admin&role=user,则实际roleList参数入参的数据为“admin,user”,即多个数据之间使用“,”分割;我们应该使用如下方式来接收多个请求参数:
      public String requestparam7(@RequestParam(value="role") String[] roleList)
      public String requestparam8(@RequestParam(value="list") List<String> list)
     
     
    @RquestMapping和@RequestParam注解示例:
       
      (1)实体类:
           public class User implements Serializable {
           private static final long serialVersionUID = 1L;
           private String loginname;
           private String password;
           private String username;
         }
     (2)控制器:
        @Controller
      public class UserController {
         private static List<User> userList;
         public UserController() {
              super();
              userList = new ArrayList<User>();
         }
         
         @GetMapping(value="/register")
         public String registerForm() {
              System.out.println("register Get方法被调用......");
              return "registerForm";
         }
         
         @PostMapping(value="/register")
         public String register(@RequestParam("loginname") String loginname,
                                 @RequestParam("password") String password,
                                 @RequestParam("username") String username) {
              
              System.out.println("register Post方法被调用......");
              User user = new User();
              user.setLoginname(loginname);
              user.setPassword(password);
              user.setUsername(username);
              userList.add(user);
              
              return "loginForm";
         }
         
         @RequestMapping(value="/login")
         public String login(@RequestParam("loginname") String loginname,
                              @RequestParam("password") String password,
                              Model model) {
              System.out.println("登录名:"+loginname+",密码:"+password);
              for(User user:userList) {
                  if(user.getLoginname().equals(loginname)&&user.getPassword().equals(password)) {
                       model.addAttribute("user",user);
                       return "welcome";
                  }
              }
              return "loginForm";
         }
    }
    (3)registerForm.jsp
        <center>
       <h2>用户注册</h2>
       <hr>
       <br>
       <form action="register" method="post">
           <table>
              <tr>
                 <td>登录名:</td>
                 <td>
                    <input type="text" id="loginname" name="loginname"/>
                 </td>
              </tr>
              <tr>
                 <td>&nbsp;&nbsp;&nbsp;码:</td>
                 <td>
                    <input type="password" id="password" name="password"/>
                 </td>
              </tr>
              <tr>
                 <td>真实姓名:</td>
                 <td>
                    <input type="text" id="username" name="username"/>
                 </td>
              </tr>
              <tr>
                 <td>
                    <input type="submit" value="注册"/>
                 </td>
              </tr>
           </table>
       </form>
    </center>
    (4)loginForm.jsp
      <center>
       <h2>用户登录</h2>
       <hr>
       <br>
       <form action="login" method="post">
           <table>
              <tr>
                 <td>登录名:</td>
                 <td>
                    <input type="text" id="loginname" name="loginname"/>
                 </td>
              </tr>
              <tr>
                 <td>&nbsp;&nbsp;&nbsp;码:</td>
                 <td>
                    <input type="password" id="password" name="password"/>
                 </td>
              </tr>
              <tr>
                 <td>
                    <input type="submit" value="登录"/>
                 </td>
              </tr>
           </table>
       </form>
    </center>
    (5)welcome.jsp:
            <h2>
                 欢迎【${requestScope.user.username}】
             </h2>
    五、@PathVariable注解:可以非常方便获取请求URL中的动态参数
     
    属性
    类型
    是否必要
    说明
    name
    String
    指定请求参数绑定的名称,如果省略则绑定同名参数
    value
    String
    name属性的别名
    required
    boolean
    指示参数是否必须绑定
    六、@MatrixVariable注解:拓展了URL请求地址的功能,多个变量可以使用分号分隔,该注解允许开发者进行多条件组合查询
    属性
    类型
    是否必要
    说明
    name
    String
    指定请求参数绑定的名称,如果省略则绑定同名参数
    value
    String
    name属性的别名
    pathVar
    String
    matrix variable所在路径的url path变量的名称
    required
    boolean
    指示参数是否必须绑定
    defaultValue
    String
    如果没有传递参数而使用的默认值
    注意:@MatrixVariable注解功能在SpringMVC中默认是不启用的,启用它需要设置
            <mvc:annotation-driven enable-matrix-variables="true"/>
     
    七、@RequestHeader注解:用于将请求的头信息数据映射到功能处理方法的参数上
    属性
    类型
    是否必要
    说明
    name
    String
    指定请求参数绑定的名称
    value
    String
    name属性的别名
    required
    boolean
    指示参数是否必须绑定
    defaultValue
    String
    如果没有传递参数而使用的默认值
    八、@CookieValue注解:用于将请求的Cookie数据映射到功能处理方法的参数上
    属性
    类型
    是否必要
    说明
    name
    String
    指定请求参数绑定的名称
    value
    String
    name属性的别名
    required
    boolean
    指示参数是否必须绑定
    defaultValue
    String
    如果没有传递参数而使用的默认值
      
    九、@RequestAttribute注解:用于访问由请求处理方法、过滤器或拦截器创建的、预先存在request作用域中的属性,将该属性转换到目标方法的参数中
    属性
    类型
    是否必要
    说明
    name
    String
    指定请求参数绑定的名称
    value
    String
    name属性的别名
    required
    boolean
    指示参数是否必须绑定
    十、@sessionAttribute注解:用于访问由请求处理方法、过滤器或拦截器创建的、预先存在sessopm作用域中的属性,将该属性转换到目标方法的参数中
    属性
    类型
    是否必要
    说明
    name
    String
    指定请求参数绑定的名称
    value
    String
    name属性的别名
    required
    boolean
    指示参数是否必须绑定
    十一、@SessionAttribute注解:允许有选择的指定Model中的哪些属性转存到HttpSession对象中
    属性
    类型
    是否必要
    说明
    names
    String[]
    Model中属性的名称,即存储在HttpSession当中的属性名称
    value
    String[]
    name属性的别名
    types
    Class<?>[]
    指示参数是否必须绑定
    示例:
      (1)配置文件:
        <mvc:annotation-driven enable-matrix-variables="true"/>
          <context:component-scan base-package="com.cn.controller"/>
          <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
             <property name="prefix" value="/WEB-INF/views/"></property>
             <property name="suffix" value=".jsp"></property>
           </bean>
        (2)控制器:
         @Controller
        public class VariableController {
         @GetMapping(value="/pathVariableTest/{userId}")
         public void pathVariableTest(@PathVariable Integer userId) {
              
              System.out.println("通过@PathVariable获得数据:userId="+userId);
         }
         
         @GetMapping(value="/matrixVariableTest/{userId}")
         public void matrixVariableTest(@PathVariable Integer userId,
                      @MatrixVariable(value="name",pathVar="userId") String name,
                      @MatrixVariable(value="age",pathVar="userId") Integer age){
                                           
              System.out.println("通过@PathVariable获得数据:userId="+userId);
              System.out.println("通过@MatrixVariable获得数据:name="+name+",age="+age);
                                        }
         
         @GetMapping(value="/productTest/{goods}")
         public void productTest(@PathVariable String goods,
                     @MatrixVariable(value="brand",pathVar="goods") List<String> brand,
                     @MatrixVariable(value="low",pathVar="goods") Integer low,
                     @MatrixVariable(value="height",pathVar="goods") Integer height
                                 ) {
              System.out.println("通过@PathVariable获得数据:="+goods);
              System.out.println("通过@MatrixVariable获得数据:"+brand);
              System.out.println("通过@MatrixVariable获得数据:low="+low+",height="+height);
         }
         
         @GetMapping(value="/reauestHeaderTest")
         public void reauestHeaderTest(
                     @RequestHeader("User-Agent") String userAgent,
                     @RequestHeader(value="Accept") String[] accepts) {
              
              System.out.println("通过@RequestHeader获得数据:"+userAgent);
              System.out.println("通过@RequestHeader获得accepts:");
              
              for(String accept:accepts) {
                  System.out.println(accept);
              }
         }
         
         @GetMapping(value="/cookieValueTest")
         public void cookieValueTest(
                     @CookieValue(value="JSESSIONID",defaultValue="") String sessionId)
         {
              System.out.println("通过@CookieValue获得JSESSIONID:"+sessionId);
         }
         
         @GetMapping("/attributeTest")
         public ModelAndView attributeTest(ModelAndView mv) {
              
              System.out.println("attributeTest方法被调用...");
              mv.setViewName("redirect:main");
              return mv;
         }
         
         @RequestMapping("/main")
         public String Main(@RequestAttribute("school") String school,
                 @SessionAttribute("author") String author) {
              
              System.out.println("main方法被调用...");
              System.out.println("school:"+school);
              System.out.println("author:"+author);
              
              return "welcome";
         }
    }
     (3)视图文件index.jsp
       <br><br>
        <a href="pathVariableTest/1">测试@PathVariable注解</a>
        <br><br>
        <a href="matrixVariableTest/1;name=jack;age=23">测试@MatrixVariable注解</a>
        <br><br>
        <a href="productTest/computer;brand=apple;acer;low=1000;height=10000">测试@MatrixVariable注解</a>
        <br><br>
        <a href="reauestHeaderTest">@ReauestHeader注解测试</a>
        <br><br>
        <a href="cookieValueTest">@CookieValue注解测试</a>
        <br><br>
        <a href="attributeTest">@RequestAttribute和@SessionAttribute注解测试</a>
     
  • 相关阅读:
    入门菜鸟
    FZU 1202
    XMU 1246
    Codeforces 294E Shaass the Great 树形dp
    Codeforces 773D Perishable Roads 最短路 (看题解)
    Codeforces 814E An unavoidable detour for home dp
    Codeforces 567E President and Roads 最短路 + tarjan求桥
    Codeforces 567F Mausoleum dp
    Codeforces 908G New Year and Original Order 数位dp
    Codeforces 813D Two Melodies dp
  • 原文地址:https://www.cnblogs.com/lone5wolf/p/10940962.html
Copyright © 2011-2022 走看看