Struts2 学习之路(一):从一个filter 控制器开始学习 Struts2

自定义过滤器作为控制器的小case

1./index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

    <a href="product-add.action">productAdd</a>

</body>
</html>

2./WEB-INF/pages/productAdd.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

    <form action="product-save.action" method="get">
        productName:<input type="text" name="name">
        <br>
        productPrice:<input type="text" name="price">
        <br>
        productDesc:<input type="text" name="desc">
        <br>
        <input type="submit" value="Submit">    
    </form>

</body>
</html>

3./WEB-INF/pages/showDetails.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    productId:${requestScope.product.id }
    <br>
    productName:${requestScope.product.name }
    <br>
    productPrice:${requestScope.product.price }
    <br>
    productDesc:${requestScope.product.desc }
</body>
</html>

4.Product.java

public class Product {

    private Integer id;
    private String name;
    private String desc;
    private BigDecimal price;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDesc() {
        return desc;
    }
    public void setDesc(String desc) {
        this.desc = desc;
    }
    public BigDecimal getPrice() {
        return price;
    }
    public void setPrice(BigDecimal price) {
        this.price = price;
    }
    public Product(Integer id, String name, String desc, BigDecimal price) {
        super();
        this.id = id;
        this.name = name;
        this.desc = desc;
        this.price = price;
    }
    public Product() {
        super();

    }
    @Override
    public String toString() {
        return "Product [id=" + id + ", name=" + name + ", desc=" + desc + ", price=" + price + "]";
    }

}

5.ProductFilter.java

@WebFilter("*.action")
public class ProductFilter extends HttpFilter {


    /**
     * @Field Name:serialVersionUID
     * @Description:TODO (就是一个序列化版本号) 
     */

    private static final long serialVersionUID = 1L;

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //1.首先对请求的路径进行判断,然后进行相关的处理
        HttpServletRequest req = (HttpServletRequest)request;
        String servletPath = req.getServletPath();
        System.out.println(servletPath);

        String path = null;
        if("/product-add.action".equals(servletPath)) {
            path = "/WEB-INF/pages/productAdd.jsp";
        }

        if("/product-save.action".equals(servletPath)) {
            path = "/WEB-INF/pages/showDetails.jsp";
            String name = request.getParameter("name");
            String desc = request.getParameter("desc");
            String price = request.getParameter("price");
            //把请求信息封装成一个Product对象
            Product product = new Product(null, name, desc, BigDecimal.valueOf(Double.parseDouble(price)));
            product.setId(1001);
            //再把Product对象封装到request的请求域中
            request.setAttribute("product", product);
            System.out.println(product);
        }
        //如果path不为空,就进行转发
        if(path != null) {
            request.getRequestDispatcher(path).forward(request, response);
            return;
        }

        chain.doFilter(request, response);
    }

    public void init(FilterConfig fConfig) throws ServletException {
    }
}
使用一个过滤器作为控制器,可以方便的在应用程序里对所有资源包括静态资源进行控制访问,而且还有一个FilterChain的api可以使用,struts2中的拦截器栈就是利用了类似的 api 进行请求的拦截处理
获取源代码请点击我
通过struts2来进行上面案例的重写
  • 步骤
    1. 由product-add.action超链接转到/WEB-INF/pages/productAdd.jsp,在struts.xml中配置一个Struts2默认提供的action
    2. 由productAdd.jsp跳转到/WEB-INF/pages/showDetails.jsp的action(在Product类中定义一个save方法而且返回值为”details”)
    3. struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
    "http://struts.apache.org/dtds/struts-2.5.dtd">

<struts>
    <!-- 
        package:包,struts2使用package来组织模块
        name属性:必须,用于其他的包继承这个包
        extends:当前包继承哪个包,可以继承其中所有配置,通常情况下继承struts-default
        namespace:可选,如果没有给出,那么默认就是/,若namespace有一个非默认值,则想要调用这个包里面的action,就必须把名称空间加入到访问uri中
                       http://localhost:8080/contextpath/namespace/actionName.action
     -->
    <package name="helloworld" extends="struts-default" >
    <!-- 配置一个action:一个strtus2的请求就是一个action
         name:对应一个struts2的请求的名字,就是一个servletPath去掉开始的/和扩展名
         class的默认值:可以省略,com.opensymphony.xwork2.ActionSupport
         method的默认值:可以省略,execute
         result:结果      
     -->
        <action name="product-add" class="com.opensymphony.xwork2.ActionSupport" method="execute">
            <!-- result结果:表示action方法执行后可能返回的结果,所以一个action节点可能会有多个result子节点,多个result子节点使用name来区分
                 name:可以省略,标识一个result,和action的方法返回值对应,默认值是success
                 type:可以省略,表示结果的类型,默认是dispatcher,即转发类型
             -->
            <result name="success" type="dispatcher">/WEB-INF/pages/productAdd.jsp</result>
        </action>

        <action name="product-save" class="cn.zc_cris.Product" method="save">
            <result name="details">/WEB-INF/pages/showDetails.jsp</result>
        </action>
    </package>
</struts>
  • Product.java(即便是简单的javaBean对象也可以作为struts中的action控制器)
public class Product {

    private Integer id;
    private String name;
    private String desc;
    private BigDecimal price;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDesc() {
        return desc;
    }
    public void setDesc(String desc) {
        this.desc = desc;
    }
    public BigDecimal getPrice() {
        return price;
    }
    public void setPrice(BigDecimal price) {
        this.price = price;
    }
    @Override
    public String toString() {
        return "Product [id=" + id + ", name=" + name + ", desc=" + desc + ", price=" + price + "]";
    }

    public String save() {
        System.out.println("save: "+this);
        return "details";
    }
}

showDetails.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    productId:${id }
    <br>
    productName:${name }
    <br>
    productPrice:${price }
    <br>
    productDesc:${desc }
</body>
</html>
获取源代码请点击我
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值