struts2教程:11、请求参数接收

来源:互联网 发布:java写文件换行 编辑:程序博客网 时间:2024/05/21 17:10

接收请求参数

采用基本类型接收请求参数(get/post)

Action类中定义与请求参数同名的属性,struts2便能自动接收请求参数并赋予给同名属性。

请求路径: http://localhost:8080/test/view.action?id=78

public class ProductAction {

      private Integer id;

      public void setId(Integer id) {//struts2通过反射技术调用与请求参数同名的属性的setter方法来获取请求参数值

             this.id = id;

      }

      public Integer getId() {return id;}

  }

struts2中不再像struts1一样使用formbean接受请求参数,而是直接在action中接受参数。注意是action中属性名要和请求参数名一致。

struts2使用request.getParamer()来接受请求参数的,所以get/post方法的提交都可以接受。

采用复合类型接收请求参数

请求路径: http://localhost:8080/test/view.action?product.id=78

 public class ProductAction {

   private Product product;

   public void setProduct(Productproduct) {  this.product = product; }

   public Product getProduct() {return product;}

}

Struts2首先通过反射技术调用Product的默认构造器创建product对象,然后再通过反射技术调用product中与请求参数同名的属性的setter方法来获取请求参数值。

jsp中可以用EL表达式获取复合类型的值,${product.id }     ${product.name}    

如果遇到要在action中添加很多的属性,建议使用复合类型接受参数,不至于在action类中显得很臃肿。

关于struts2.1.6接收中文请求参数乱码问题

struts2.1.6版本中存在一个Bug,即接收到的中文请求参数为乱码(post方式提交),原因是struts2.1.6在获取并使用了请求参数后才调用HttpServletRequestsetCharacterEncoding()方法进行编码设置 ,导致应用使用的就是乱码请求参数。这个bugstruts2.1.8中已经被解决,如果你使用的是struts2.1.6,要解决这个问题,你可以这样做:新建一个Filter,把这个Filter放置在Struts2Filter之前,然后在doFilter()方法里添加以下代码

public void doFilter(...){

  HttpServletRequestreq = (HttpServletRequest) request;

  req.setCharacterEncoding("UTF-8");//应根据你使用的编码替换UTF-8

  filterchain.doFilter(request, response);

}

struts2.1.6中有很多bug,建议使用struts2.1.8

原创粉丝点击