Struts 2是一个MVC框架,以WebWork框架的设计思想为核心,吸取了Struts 1的部分优势web
Struts 2拥有更加广阔的前景,自身功能强大,还对其余框架下开发的程序提供很好的兼容性apache
步骤1: 配置web.xml文件浏览器
<filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <!-- 拦截全部的action --> <url-pattern>/*</url-pattern> </filter-mapping>
步骤2:在src下建立名称为struts.xml的配置文件tomcat
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <!-- 配置文件中只要添加如下配置,那么之后修改配置文件不用重启tomcat --> <constant name="struts.devMode" value="true" /> <package name="default" namespace="/" extends="struts-default"> <!-- 第一个action的例子 --> <action name="helloWorld" class="cn.happy.action.HelloWorldAction"> <result name="success"> index.jsp </result> </action> <!-- 登录的action --> </package> <!-- Add packages here --> </struts>
步骤3:编写HelloWorldActionapp
package cn.happy.action; import com.opensymphony.xwork2.Action; public class HelloWorldAction implements Action{ private String name ; private String message; public String execute() throws Exception { setMessage("Hello"+getName()); return "success"; } }
步骤4:建立index.jsp页面框架
<div>
<h1>
<!--显示Struts Action中message的属性内容-->
<s:property value="message"/>
</h1>
</div>
<div>
<form action="helloWorld.action" method="post">
请输入您的姓名:
<input name="name" type="text" />
<input type="submit" value="提交" />
</form>
</div>
步骤5:经过浏览器访问jsp
点击提交后结果post
<!-- 配置文件中只要添加如下配置,那么之后修改配置文件不用重启tomcat --> <constant name="struts.devMode" value="true" />
问题描述:No configuration found for the specified action: 'login.action' in namespace: ''. Form action defaulting to 'action' attribute's literal value.url
解析:spa
<s:form action="Login" method="post" namespace="/"> or <s:form action="/Login" method="post" >
步骤一:struts.xml文件
<!-- 登录的action --> <action name="login" class="cn.happy.action.LoginAction"> <result name="success"> login/success.jsp </result> <result name="login"> login/login.jsp </result> </action>
步骤二:LoginAction类的建立
package cn.happy.action; import com.opensymphony.xwork2.Action; public class LoginAction implements Action{ private String username = ""; private String password = ""; public String execute() throws Exception { if (username.equals("1")&&password.equals("1")) { return SUCCESS; }else { return LOGIN; } } }
步骤三:建立登录界面
<s:form name="form1" namespace="/" method="post" action="login">
请输入用户名: <s:textfield name="username"></s:textfield> <br/>
<s:textfield name="password"></s:textfield><br/>
<s:submit value="登录"></s:submit>
</s:form>
步骤四:在浏览器中访问
在开发中,一般会以JavaBean方式保存数据。因此能够有以下写法
Action类
Jsp页面