Java mac idea Struts2的使用02

1. Struts2的结果处理方式

<struts>
    <package name="result" namespace="/" extends="struts-default" >
    <!-- 1. 转发 -->
        <action name="Demo1Action" class="cn.itheima.a_result.Demo1Action" method="execute" >
            <result name="success" type="dispatcher" >/hello.jsp</result>
        </action>
    <!-- 2. 重定向 -->
        <action name="Demo2Action" class="cn.itheima.a_result.Demo2Action" method="execute" >
            <result name="success" type="redirect" >/hello.jsp</result>
        </action>
    <!-- 3. 转发到Action -->
        <action name="Demo3Action" class="cn.itheima.a_result.Demo3Action" method="execute" >
             <result name="success" type="chain">
                    <!-- action的名字 -->
                 <param name="actionName">Demo1Action</param>
                    <!-- action所在的命名空间 -->
                 <param name="namespace">/</param>
             </result>
        </action>
        <!-- 4. 重定向到Action -->
        <action name="Demo4Action" class="cn.itheima.a_result.Demo4Action" method="execute" >
            <result  name="success"  type="redirectAction">
                 <!-- action的名字 -->
                 <param name="actionName">Demo1Action</param>
                 <!-- action所在的命名空间 -->
                 <param name="namespace">/</param>
            </result>
        </action>
    </package>

2. Struts2 获得 servletApi

方式一:

  1. 配置文件
<struts>
    <package name="api" namespace="/" extends="struts-default" >
        <action name="Demo5Action" class="cn.itheima.b_api.Demo5Action" method="execute" >
            <result name="success" type="dispatcher" >/api.jsp</result>
        </action>
    </package>
</struts>
  1. Demo5Action
//如何在action中获得原生ServletAPI
public class Demo5Action extends ActionSupport {

    public String execute() throws Exception {
        //request域=> map (struts2并不推荐使用原生request域)
        //不推荐
        Map<String, Object> requestScope = (Map<String, Object>) ActionContext.getContext().get("request");
        //推荐
        ActionContext.getContext().put("name", "requestTom");
        //session域 => map
        Map<String, Object> sessionScope = ActionContext.getContext().getSession();
        sessionScope.put("name", "sessionTom");
        //application域=>map
        Map<String, Object> applicationScope = ActionContext.getContext().getApplication();
        applicationScope.put("name", "applicationTom");
        
        return SUCCESS;
    }
}
  1. api.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    request: ${requestScope.name}<br>
    session:${sessionScope.name}<br>
    application:${applicationScope.name}<br>
</body>
</html>

方式二:


//如何在action中获得原生ServletAPI
public class Demo6Action extends ActionSupport {
    //并不推荐
    public String execute() throws Exception {
        //原生request
        HttpServletRequest request = ServletActionContext.getRequest();
        //原生session
        HttpSession session = request.getSession();
        //原生response
        HttpServletResponse response = ServletActionContext.getResponse();
        //原生servletContext
        ServletContext servletContext = ServletActionContext.getServletContext();
        return SUCCESS;
    }
}

3. 参数获取方式

3.1 action的生命周期

action的生命周期和request的生命周期是一样的

3.2 属性驱动获取参数

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/Demo8Action">
        用户名:<input type="text" name="name" /><br>
        年龄:<input type="text" name="age" /><br>
        生日:<input type="text" name="birthday" /><br>
        <input type="submit" value="提交" />
    </form>
</body>
</html>
//struts2如何获得参数
//每次请求Action时都会创建新的Action实例对象
public class Demo8Action extends ActionSupport  {
    
    public Demo8Action() {
        super();
        System.out.println("demo8Action被创建了!");
    }


    //准备与参数键名称相同的属性
    private String name;
    //自动类型转换 只能转换8大基本数据类型以及对应包装类
    private Integer age;
    //支持特定类型字符串转换为Date ,例如 yyyy-MM-dd
    private Date   birthday;
    

    public String execute() throws Exception { 
        
        System.out.println("name参数值:"+name+",age参数值:"+age+",生日:"+birthday);
        
        return SUCCESS;
    }


    public String getName() {
        return name;
    }


    public void setName(String name) {
        this.name = name;
    }


    public Integer getAge() {
        return age;
    }


    public void setAge(Integer age) {
        this.age = age;
    }


    public Date getBirthday() {
        return birthday;
    }


    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }   
}

3.3 对象驱动获取参数

//struts2如何获得参数-方式2
public class Demo9Action extends ActionSupport  {
    //准备user对象
    private User user;

    public String execute() throws Exception { 
        
        System.out.println(user);
        
        return SUCCESS;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/Demo9Action">
        用户名:<input type="text" name="user.name" /><br>
        年龄:<input type="text" name="user.age" /><br>
        生日:<input type="text" name="user.birthday" /><br>
        <input type="submit" value="提交" />
    </form>
</body>
</html>

3.4 模型驱动获取参数

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/Demo10Action">
        用户名:<input type="text" name="name" /><br>
        年龄:<input type="text" name="age" /><br>
        生日:<input type="text" name="birthday" /><br>
        <input type="submit" value="提交" />
    </form>
</body>
</html>
//struts2如何获得参数-方式2
public class Demo10Action extends ActionSupport implements ModelDriven<User> {
    //准备user 成员变量
    private User user =new User();

    public String execute() throws Exception { 
        
        System.out.println(user);
        
        return SUCCESS;
    }

    @Override
    public User getModel() {
        return user;
    }
}

3.5 集合类型封装参数

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/Demo11Action" method="post" >
        list:<input type="text" name="list" /><br>
        list:<input type="text" name="list[3]" /><br>
        map:<input type="text" name="map['haha']" /><br>
        <input type="submit" value="提交" />
    </form>
</body>
</html>
//struts2 封装集合类型参数
public class Demo11Action extends ActionSupport  {
    //list
    private List<String> list;
    //Map
    private Map<String,String> map;
    
    
    public String execute() throws Exception { 
        
        System.out.println("list:"+list);
        System.out.println("map:"+map);
        
        return SUCCESS;
    }

    public List<String> getList() {
        return list;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

    public Map<String, String> getMap() {
        return map;
    }

    public void setMap(Map<String, String> map) {
        this.map = map;
    }

}

4. 添加客户

public class CustomerAction extends ActionSupport implements ModelDriven<Customer> {

    private CustomerService customerService = new CustomerServiceImpl();

    private Customer customer = new Customer();

    public String add() throws Exception {

        customerService.save(customer);

        return "toList";
    }


    public String list() throws Exception {

        // 1. 接受参数
        String cust_name = ServletActionContext.getRequest().getParameter("cust_name");

        // 2. 创建离线查询对象
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Customer.class);

        // 3. 根据参数封装查询条件
        if (StringUtils.isNotBlank(cust_name)) {

            detachedCriteria.add(Restrictions.like("cust_name", "%" + cust_name + "%"));

        }

        List list = customerService.getAll(detachedCriteria);

        ServletActionContext.getRequest().setAttribute("list", list);

        return "list";
    }

    @Override
    public Customer getModel() {

        return customer;
    }
}
<struts>

    <!-- i18n:国际化. 解决post提交乱码 -->
    <constant name="struts.i18n.encoding" value="UTF-8"></constant>
    <!-- 指定反问action时的后缀名
        http://localhost:8080/struts2_day01/hello/HelloAction.do
    -->
    <!--<constant name="struts.action.extension" value="action"></constant>-->
    <!-- 指定struts2是否以开发模式运行
            1.热加载主配置.(不需要重启即可生效)
            2.提供更多错误信息输出,方便开发时的调试
     -->
    <constant name="struts.devMode" value="true"></constant>



    <!-- package:将Action配置封装.就是可以在Package中配置很多action.
            name属性: 给包起个名字,起到标识作用.随便起.不能其他包名重复.
            namespace属性:给action的访问路径中定义一个命名空间
            extends属性: 继承一个 指定包
            abstract属性:包是否为抽象的; 标识性属性.标识该包不能独立运行.专门被继承
      -->
    <package name="customer" namespace="/" extends="struts-default" >
        <!-- action元素:配置action类
                name属性: 决定了Action访问资源名.
                class属性: action的完整类名
                method属性: 指定调用Action中的哪个方法来处理请求
         -->
        <action name="CustomerAction_*" class="web.CustomerAction" method="{1}" >
            <!-- result元素:结果配置
                    name属性: 标识结果处理的名称.与action方法的返回值对应.
                    type属性: 指定调用哪一个result类来处理结果,默认使用转发.
                    标签体:填写页面的相对路径
            -->
            <result name="list" type="dispatcher" >/jsp/customer/list.jsp</result>

            <!--重定向到 CustomerAction_list-->
            <result name="toList" type="redirectAction" >
                <param name="actionName" >CustomerAction_list</param>
                <param name="nameSpace">/</param>
            </result>

        </action>
    </package>

</struts>
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,045评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,114评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,120评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,902评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,828评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,132评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,590评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,258评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,408评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,335评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,385评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,068评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,660评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,747评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,967评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,406评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,970评论 2 341

推荐阅读更多精彩内容