SpringMVC通过注解获得参数

SpringMVC可以通过RequestParam注解来映射获得参数,具体用法如下:

SpringMVC通过注解获得参数

例子:

配置过程省略

1.新建controller类

  

 package com.loger.controller;

 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.RequestMapping;

 @Controller
 public class RequestParam {

     public static final String SUCCESS = "success";

     @RequestMapping(value="/requestparam")
     public String requestParam(@org.springframework.web.bind.annotation.
             RequestParam(value="username") String un,
             @org.springframework.web.bind.annotation.RequestParam(value="age") Integer age){

         System.out.println(un + " " + age);

         return SUCCESS;
     }
 }

2.index.jsp

SpringMVC通过注解获得参数

运行结果:

SpringMVC通过注解获得参数

SpringMVC通过注解获得参数

补充:如果表单名跟方法的参数名一致的话,无需再用@RequestParam注解来映射。

  如改为

   @RequestMapping(value="/requestparam")
     public String requestParam(String username,Integer age)即可!


用类作为参数,且包含级联属性的参数获取方法

  1.新建Adress类
  
 package com.loger.bean;

 public class Address {
     private String province;
     private String city;
     public String getProvince() {
         return province;
     }
     public void setProvince(String province) {
         this.province = province;
     }
     public String getCity() {
         return city;
     }
     public void setCity(String city) {
         this.city = city;
     }
     @Override
     public String toString() {
         return "Address [province=" + province + ", city=" + city + "]";
     }

 }

2.新建User类

 package com.loger.bean;

 public class User {
     private String name;
     private int age;
     private Address address;
     public String getName() {
         return name;
     }
     public void setName(String name) {
         this.name = name;
     }
     public int getAge() {
         return age;
     }
     public void setAge(int age) {
         this.age = age;
     }
     public Address getAddress() {
         return address;
     }
     public void setAddress(Address address) {
         this.address = address;
     }
     @Override
     public String toString() {
         return "User [name=" + name + ", age=" + age + ", address=" + address + "]";
     }

 }

3.controller

SpringMVC通过注解获得参数

4.表单

  User有级联属性Address,表单传入的参数是address.city address.province

 <form action="pojoparam">
         姓名:<input type="text" name="name"><br>
         年龄:<input type="text" name="age"><br>
         城市:<input type="text" name="address.city"><br>
         省份:<input type="text" name="address.province"><br>
         <input type="submit" value="提交"><br>
     </form>

运行结果:

SpringMVC通过注解获得参数



上一篇:Qt入门(6)——Qt的界面布局


下一篇:java定时器schedule和scheduleAtFixedRate区别