首页 > 代码库 > Struts2例子

Struts2例子

创建一个web project;

导入Struts2的jar包放到lib目录下:

技术分享

 

WEB-INF下面创建login.jsp和welcome.jsp;index.jsp删掉;

技术分享

 

说一下<%@ taglib prefix="s" uri="/struts-tags"%> 

这句是Struts标签引入,一定记得写 不然下面的表格就不认了!

login.jsp页面代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>登录</title>
</head>
<body>
<s:form action="login" method="post">
<s:label value="http://www.mamicode.com/系统登录"></s:label>
<s:textfield name="username" label="账号"></s:textfield>
<s:password name="password" label="密码"></s:password>
<s:submit value="http://www.mamicode.com/登录"></s:submit>
</s:form>
</body>
</html>

welcome.jsp页面代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>欢迎</title>
</head>
<body>
欢迎${username}
</body>
</html>

在src下创建struts.xml:

<?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" namespace="/" extends="struts-default">
<action name="login" class="LoginAction" method="execute" >
<result name="success">/WEB-INF/welcome.jsp</result>
<result name="login">/WEB-INF/login.jsp</result>
</action>
</package>
</struts>

在src下编写LoginAction类:

import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport{
private static final long serialVersionUID = 1L;
//该类继承了ActionSupport,就可以直接使用SUCCESS LOGIN等变量和 重写execute方法
private String username;
private String password;
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;
}
@Override
public String execute() throws Exception {
if("sxh".equals(username) && "123".equals(password))
return SUCCESS;
return LOGIN;
}
}

 部署到tomcat启动就可以运行了!!!!!

代码链接:http://pan.baidu.com/s/1bpED1gj

 

Struts2例子