Struts2入门02

二、Struts2初步使用说明

1、struts2.xml中result

result的type属性常用的4种方式

转发:dispatcher

重定向:redirect

转发到action:chain

重定向到action:redirectAction(重定向到action是重定向到包中配置的action标签的name中的action)

<struts>
        <package name="demo3" namespace="/" extends="struts-default">
            <!-- 转发 -->
            <action name="DemoDisAction" class="Struts03.DemoDisAction" method="Demo">
                <result name="success" type="dispatcher">/Demo1.jsp</result>
            </action>
            <!-- 重定向 -->
            <action name="demo2_*" class="Struts03.Demo2DisAction" method="{1}">
                <result name="success" type="redirect">/Demo2.jsp</result>
            </action>
            
            <!-- 转发到action -->
            <action name="Demo3DisAction" class="Struts03.Demo3DisAction" >
                <result name="success" type="chain">
                    <param name="actionName">DemoDisAction</param>
                    <param name="namespace">/</param>
                </result>
            </action>
            
            <!-- 重定向到action -->
            <action name="Demo4DisAction" class="Struts03.Demo3DisAction" >
                <result name="success" type="redirectAction">
                    <param name="actionName">DemoDisAction</param>
                    <param name="namespace">/</param>
                </result>
            </action>
        </package>
    </struts>

 2、获取ServletAPI

方式一、(推荐)

使用ActionContext获取

public class Sdemo1 extends ActionSupport {

    /**
     * ActionContext作为一个容器,存放着所有Servlet中的对象
     * ActionContext生命周期:
     *             每次请求都会创建一个对应的ActionContext对象,
     *             请求完成,ActionContext销毁
     *             ActionContext会与当前线程绑定,通过ThreadLocal获取
     * */
    public String Func() throws Exception {
        //通过ActionContext获取域
        
        //获取request域  本质:map 不推荐
        Map<String,Object> requestScope = (Map<String, Object>) ActionContext.getContext().get("request");
        requestScope.put("name", "张三");
        //struts2将request进行了包装,所以可以直接将以前放入request中的内容放入ActionContext中
        //推荐
        ActionContext.getContext().put("age", 23);
        
        //获取session域  map
        Map<String, Object> session = ActionContext.getContext().getSession();
        session.put("user", "Admin");
        
        //获取Application域
        Map<String, Object> application = ActionContext.getContext().getApplication();
        application.put("address", "北京");
        
        return SUCCESS;
    }
}

方式二、

通过ServletActionContext获取

public class Sdemo2 extends ActionSupport {

    //不推荐
    public String Func1() throws Exception{
        //通过ServletActionContext获取
        
        //原生request
        HttpServletRequest request =ServletActionContext.getRequest();
        //原生session
        HttpSession session = request.getSession();
        //原生response
        HttpServletResponse response = ServletActionContext.getResponse();
        //原生ServletContext
        ServletContext context = ServletActionContext.getServletContext();
        
        return SUCCESS;
    }
}

方式三、(不推荐)

通过实现接口获取

public class Sdemo3 extends ActionSupport implements ServletRequestAware {

    private HttpServletRequest request=null;
    
    //通过接口方式获取原生request
    //其他session response applicaiotn获取方式相同,实现对应接口即可
    //不推荐使用
    public String Func3() throws Exception{
        
        String name = request.getParameter("name");
        return SUCCESS;
    }
    
    @Override
    public void setServletRequest(HttpServletRequest request) 
    {
        // TODO Auto-generated method stub
        this.request=request;
    }

}

 3、获取页面参数

方式一、

属性驱动获得参数(必须添加对应的get set方法)

//属性驱动获取页面提交的参数
public class Gdemo1 extends ActionSupport 
{
    /**
     * Action的生命周期:
     *         每次请求都会创建一个新的Action实例
     *         Action是线程安全的,可以使用成员变量接受参数
     *      为什么Servlet线程不安全?
     *         原因:一个Servlet在运行时只会有一个Servlet实例
     *             因此接受的参数需要放入方法域中,不能用成员变量存放,否则会发生值被覆盖的情况
     * */

    //属性要求与页面提交的表单中的name名称一致
    private String name;
    //自动类型转换,只能转换8大基本类型以及包装类
    private Integer age;
    //支持特定字符类型转换为Date,例如 yyyy-MM-dd
    private Date birthday;
    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;
    }
    
    public String Func() throws Exception {
        System.out.println(name+"__"+age+"__"+birthday);
        ActionContext.getContext().put("name", name);
        ActionContext.getContext().put("age", name);
        ActionContext.getContext().put("birthday", birthday.toString());
        return SUCCESS;
    }
}
<body>
    <form action="${pageContext.request.contextPath }/Gdemo">
    
    姓名:<input type="text" name="name"> <br/>
    年龄:<input type="text" name="age"><br/>
    生日:<input type="text" name="birthday"/><br/>
    <input type="submit" value="提交"/>
    </form>
</body>

 方式二、

对象驱动(get set方式,表单的name值需要 对象名.属性名)

//对象驱动获取页面提交的参数
public class Gdemo2 extends ActionSupport 
{
    private User user;
    
    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String Func() throws Exception {
        
        System.out.println(user);
        return NONE;
    }
}

public class User {

    public String name;
    public int age;
    public Date birthday;
    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 Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    @Override
    public String toString() {
        return "User [name=" + name + ", age=" + age + ", birthday=" + birthday + "]";
    }
}
<body>
    <form action="${pageContext.request.contextPath }/Gdemo2" method="post">
    
    姓名:<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>

方式三、

模型驱动获取页面参数

实现ModelDriven<T>接口,重写getModel方法并返回对象,对象需要手动创建

//模型驱动获取页面提交的参数
public class Gdemo3 extends ActionSupport implements ModelDriven<User>
{
    private User user=new User();
        

    public String Func() throws Exception {
        
        System.out.println(user);
        return NONE;
    }

    @Override
    public User getModel() {
        return user;
    }
}
<body>
    <form action="${pageContext.request.contextPath }/Gdemo3" method="post">
    
    姓名:<input type="text" name="name"> <br/>
    年龄:<input type="text" name="age"><br/>
    生日:<input type="text" name="birthday"/><br/>
    <input type="submit" value="提交"/>
    </form>
</body>

方式四、

参数提交封装到List集合或Map集合中(集合需要有get set  map需要在表单中写入map的key)

//使用集合取页面提交的参数
public class Gdemo4 extends ActionSupport 
{
    private List<String>list;
    private Map<String,String>map;
        

    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;
    }


    public String Func() throws Exception {
        
        System.out.println(list);
        System.out.println(map);
        return NONE;
    }
    
}
<body>
    <form action="${pageContext.request.contextPath }/Gdemo4" method="post">
    
    姓名:<input type="text" name="list"> <br/>
    年龄:<input type="text" name="list[1]"><br/>
    参数4:<input type="text" name="list[4]"><br/>
    map1name:<input type="text" name="map['name']"/><br/>
    map2age:<input type="text" name="map['age']"/><br/>
    <input type="submit" value="提交"/>
    </form>
</body>
原文地址:https://www.cnblogs.com/harriets-zhang/p/13437806.html