举个简单例子来说明
第一步:新建一个JSP文件
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="user!login.do" method="post">
用户名<input type="text" name="username" /><br><br>
密 码 <input type="password" name="password" /><br><br>
<input type="submit" value="登陆" />
</form>
</body>
</html>
然后写Action,这里写一个简单的登录逻辑,定义两个私有的变量username和password,生成getting和setting的方法,然后定义一个login()方法,返回值为String,直接定义两个字符串a和b来接受从form表单传递过来的username和password值,进行一个判断,如果为结果为真,return一个success值,跳转到登录成功的界面,否则return一个error值,跳转到失败的界面,这个例子里失败跳转到还是登录界面
package com.Action;
import com.opensymphony.xwork2.ActionSupport;
public class DemoActiom extends ActionSupport{
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;
}
public String login(){
String a=username;
String b=password;
if(a.equals("admin") && b.equals("admin")){
System.out.println("登陆成功");
return SUCCESS;
}else{
System.out.println("登陆失败");
return "error";
}
}
}
然后修改struts.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<!-- 设置开发者模式 -->
<constant name="struts.devMode" value="true"/>
<!-- 设置action过滤value中定义的扩展类型 -->
<constant name="struts.action.extension" value="do"/>
<!-- 有人习惯用action <constant name="struts.action.extension" value="action"/>-->
<!-- 设置开启动态调用DMI 2.3版本以上必须加上 -->
<constant name="struts.enable.DynamicMethodInvocation" value="true"/>
<package name="struts" extends="struts-default">
<global-allowed-methods>regex:.*</global-allowed-methods>
<action name="user" class="com.Action.DemoActiom" >
<!--这里有两个返回结果,一个为真,一个为假,会跳转到不同的页面-->
<result name="success">/index.jsp</result>
<result name="error">/Login.jsp</result>
</action>
</package>
</struts>