struts2 搭建框架例子如登陆界面,要求是用最新版struts2。
满意答案
典富软件 7级 2011-05-21
如果你用过Struts,你就不一定认为Struts版本越高越好,因为很多版本不是很稳定,我是经历过的,我现在用的struts2.1.6,版本很稳定,用起来从来没有因为版本问题而出错,我就用这个,如果你用高版本也没有什么区别,废话不多说,这是我给你写的一个例子:
1.在web.xml配置过滤器:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns=" http://java.sun.com/xml/ns/javaee"
xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
//配置过滤器
<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>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
2.登陆页面login.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>My JSP 'login.jsp' starting page</title>
</head>
<body>
<s:form action="login">
<s:textfield name="username" label="USERNAME"></s:textfield>
<s:textfield name="password" label="PASSWORD"></s:textfield>
<s:submit value="LOGIN"></s:submit>
</s:form>
</body>
</html>
3登录结果的页面welcome.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>My JSP 'welcome.jsp' starting page</title>
</head>
<body>
<s:property value="tip"/>
</body>
</html>
4.创建action文件LoginAction.java,我们设置登录用户名为admin,密码是123,登录的结果保存在tip变量中,在welcome.jsp中反馈出来
package action;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport {
private String username;
private String password;
private String tip;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getTip() {
return tip;
}
public void setTip(String tip) {
this.tip = tip;
}
public String login(){
System.out.println("ko");
if(getUsername().equals("admin")&&getPassword().equals("123")){
setTip("恭喜您,"+getUsername()+",登陆成功!");
return SUCCESS;
}else{
setTip("对不起,用户名或者密码错误!");
return ERROR;
}
}
}
5.创建配置文件struts.xml,注册action
<?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="default" extends="struts-default">
<action name="login" class="action.LoginAction" method="login">
<result name="success">/welcome.jsp</result>
<result name="error">/welcome.jsp</result>
</action>
</package>
</struts>
好了,你就可以运行了,本人亲测,一次性通过,项目的整体图如下所示:
登陆成功页面:
登录失败的页面:
呵呵,这么说你应该会明白吧!你自己调试下,希望能够帮助你!