1. 程式人生 > 實用技巧 >Struts2入門02

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>