刚接触struts2,学习中...先做个登陆的例子
1、建立web项目
2、导入struts2的jar包
commons-fileupload-1.2.1.jar
commons-io-1.3.2.jar
commons-logging-1.0.4.jar
freemarker-2.3.15.jar
ognl-2.7.3.jar
struts2-core-2.1.8.1.jar
xwork-core-2.1.6.jar
官方下载地址:http://struts.apache.org/download.cgi#struts2014
3、配置WEB-INF/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>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- filter-class中也可以写成org.apache.struts2.dispatcher.FilterDispatcher -->
注:StrutsPrepareAndExecuteFilter是struts2 2.1.*之后的才有的,2.0.*没有该filter,之前为FilterDispatcher.
该系统使用struts2-core-2.1.8版本
4、配置src/struts.xml,最后看看WEB-INF/classes下是否存在
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd ">
<struts>
<package name="struts" extends="struts-default">
<action name="login" class="com.struts2.action.LoginAction">
<result name="success">/loginSuccess.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>
命名空间可以省 也可以namespace="/"
5、创建LoginAction 实现Action接口 或者继承actionSupport
在action实例类中得到jsp页面的内容
直接定义属性 写get、set方法 会自动获取页面提交的内容
注意:这儿的属性名称要与jsp页面的一致
然后再写execute方法
public String execute() throws Exception {
if(name.equals("admin")&&pwd.equals("123")){
System.out.println("userName:"+name+"Password:"+pwd);
return "success";
}else
return "error";
};
6、写jap页面 jsp中用到struts标签时 Form的action="login" 就不用写成login.action
出现一个警告: No configuration found for the specified action: 'loginAction.action' in namespace: ''.
Form action defaulting to 'action' attribute's literal value.
出现警告的原因:struts.xml配置文件中没有写namespace 而jsp页面提交的action写成loginAction.action
两种解决方法:1、jsp页面只写loginAction,去掉.action
2、在struts.xml配置文件中添加命名空间
<package name="struts" extends="struts-default" namespace="/">