struts2应用

1、处理表单数据

GreetingAction
public class GreetingAction extends ActionSupport{
  private String username;
  public String execute() throws Exception{
    if(username==null||"".equals(username)){
       return ERROR;
    }else{
      return SUCCESS;
    }
  }
  public void setUsername(String username){
      this.username=username;
  }
  public String getUsername(){
    return username;
  }

}
struts.xml
<struts>
   <package name="myPackage" extends="struts-default">
      <action name="greeting" class="com.action.GreetingAction">
         <result name="success">success.jsp</result>
         <result name="error">error.jsp</result>
     </action>
   </package>
</struts>
index.jsp
<body>
   <form action="greeting.action" method="post">
     请输入你的姓名:<input type="text" name="username"/>
     <input type="submit"/>
  </form>
</body>
success.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<body>
  <font color="red">
     <s:property value="username"/>
  </font>
您好,欢迎来到本站
</body>
error.jsp
<body>
   <font color="red">错误:您没有输入姓名!</font>
</body>

2、使用Map类型的request、session和application对象

public class TestAction extends ActionSupport{
   private Map<String,Object> request;
   private Map<String,Object> response;
   private Map<String,Object> application;
   public TestAction(){
      ActionContext context=ActionContext.getContext();
      request=Map<String,Object> context.get("request");
      session=context.getSession();
      application=context.getApplication();
   }
   public String execute()throws Exception{
      String info="明日科技";
      request.put("info",info);
      session.put("info",info);
      application.put("info",info);
      return SUCCESS;
  }
}
struts.xml
<struts>
   <constant name="struts.devMode" value="true"/>
   <package name="myPackage" extends="struts-default">
      <action name="testAction" class="com.action.TestAction">
           <result>success.jsp</result>
      </action>
   </package>
</struts>
success.jsp
<body>
    request范围内的info值
    <font color="red">
        <%=request.getAttribute("info");%>  
    </font>
    <font color="red">
        <%=session.getAttribute("info");%>  
    </font>
    <font color="red">
        <%=application.getAttribute("info");%>  
    </font>
</body>
index.jsp
<body>
   <a href="testAction.action">Map类型的request、session、application</a>
   <br/>
</body>
原文地址:https://www.cnblogs.com/aigeileshei/p/5311990.html