struts2中,一个Form表单配置多个action实现原理及案例

一、原理说明

以登录注册为例
login.jsp:Form表单中包含登录、注册两个按钮。登录按钮配置LoginAction.java,注册按钮配置RegistAction.java

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户登录title>
head>
<body background="images/xxx.gif">
<center>

<script type="text/javascript">
    function regist(){
        myform.action="register.action";
        myform.submit();
    }
script>

<s:form action="login" method="post" name="myform">
    <s:textfield name="username" label="用户名" cssStyle="width:160px;heigh:26px;"/>
    <s:password name="password" label="密码" cssStyle="width:160px;heigh:26px"/>
    <input type=submit value="登录">
    <input type="button" value="注册" onclick="regist()"/>
s:form>

center>
body>
html>

struts.xml:一个package下配置了三个action,分别为login(登录按钮)、register(注册按钮)和regist(注册页面)



<struts>
    <package name="default" extends="struts-default">
        <action name="login" class="com.cy.action.LoginAction">
            
            <result name="success">success.jspresult>
            <result name="error">/login.jspresult>
        action>

        <action name="register" class="com.cy.action.LoginAction" method="register">
            <result name="regist">/regist.jspresult>
        action>

        <action name="regist" class="com.cy.action.RegistAction">
            <result name="input">/regist.jspresult>
            <result name="success">login.jspresult>
        action>

    package>
struts>

regist.jsp:一个简单注册页面,注册成功后跳转到登录页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>注册页面title>
head>
<body>
<center>

<s:form action="regist" method="post" onsubmit="return submitForm(this)">
    <s:textfield name="username" label="用户名" cssStyle="width:160px;heigh:26px;"/>
    <s:password name="password" label="密码" cssStyle="width:160px;heigh:26px"/>
    <s:submit value="注册"/>
s:form>

center>
body>
html>

二、分析

1、login.jsp :
form中需要指出name属性
注册按钮中要添加onclick属性,并且属性值“regist()”要与script中设置的一致
script中设置的action要与struts.xml中配置的名称一致,具体如下

2、struts.xml:
在register action中要指明method属性值为register,该值要与LoginAction.java中添加的register函数的函数名一致。

name="register" class="com.cy.action.LoginAction" method="register">
            <result name="regist">/regist.jspresult>
        

LoginAction.java中的register函数:

public String register(){
        return "regist";
    }

3、regist.jsp:
form表单中要指明onsubmit属性,该例为跳转到submitForm(登录表单)

<s:form action="regist" method="post" onsubmit="return submitForm(this)">

说明:所有源码已上传到笔者GitHub上,欢迎follow、star。感谢!!!

你可能感兴趣的:(Java)