1.struts1使用ActionServlet获取用户请求充当控制器的角色,核心是action,actionform,actionforward、
struts2的核心就是action,拦截器,action可以不用继承父类,并且糅合了action和actionform,降低耦合度。
2.依然是从最简单的登陆入手,项目还是maven项目,先导包,就不详述了,将包依赖添加到pom.xml中,再build。
3.web.xml的配置,不再使用servlet,而是过滤器:
<!-- Struts2配置 -->
<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>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
4.struts.xml的配置,放在resources下:
package 属性:①name:必选,包名。
②namespace:可选,指定命名空间,可以允许不同命名空间,相同名字的action name。默认为“”,如果填写了命名空间,则action处理url时,指定:命名空间/action name。如:action=“struts2Demo/login.action”
③ extends:继承父xml,包括父类定义的action,拦截器等。
action属性:①name:后面要使用的自定义的action name。
②class:指定action所在的类
③method:可选,指定action中的特定的方法,因此可以不用覆盖ActionSupport中的方法。
<span style="color:#000000;"> <struts>
<package name="struts2Demo" namespace="/struts2Demo" extends="struts-default">
<action name="login" class="struts2Demo.LoginAction">
<result name="suc">/index.jsp</result>
<result name="fail">/error.jsp</result>
</action>
</package>
</struts> </span>
5.LoginAction,可以不继承父类,但要执行的方法要与父类定义的方法名相同,如execute,也可以继承ActionSupport,覆盖提供的方法。
<span style="color:#000000;">public class LoginAction {
private String user;
private String pswd;
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPswd() {
return pswd;
}
public void setPswd(String pswd) {
this.pswd = pswd;
}
public String exe(){
if("admin".equals(user) && "admin".equals(pswd)) {
return "suc";
}
return "fail";
}
}</span>
6.login.jsp
<span style="color:#000000;"><form action="struts2Demo/login.action" method="post">
<p>用户名:</p><input name="userName" type="text"/><br>
<p>密码:</p><input name="pswd" type="password"/> <br>
<input type="submit" value="登陆" />
</form></span>
③