1. 程式人生 > >struts2 屬性驅動模型 獲取表達資料

struts2 屬性驅動模型 獲取表達資料

login.jsp

<%--
  Created by IntelliJ IDEA.
  User: WenSe
  Date: 2018/10/25
  Time: 13:49
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
    <base href="<%=basePath%>">
    <meta charset="utf-8">
    <title>login</title>
</head>
<body>
<form action="login">
    userName:<input type="text" name="userName">
    userPsw:<input type="text" name="userPsw">
    <input type="submit" value="login">
</form>
</body>
</html>

注意兩個input的標籤name為“userName”、“userPsw”,則其表單處理類,此處是LoginAction類應有對應名稱的屬性以及set方法

LoginAction.java

package com.action;

import com.opensymphony.xwork2.Action;

/**
 * @author WenSe
 * @date 2018/10/25 13:40
 */

public class LoginAction {
    private String userName;
    private String userPsw;

    public String login(){
        System.out.println(userName + "/"+userPsw);
        return Action.SUCCESS;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserPsw() {
        return userPsw;
    }

    public void setUserPsw(String userPsw) {
        this.userPsw = userPsw;
    }
}
action處理類提供get方法則頁面可通過el表示式獲取屬性值

success.jsp

<%--
  Created by IntelliJ IDEA.
  User: WenSe
  Date: 2018/10/25
  Time: 13:53
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
    <base href="<%=basePath%>">
    <meta charset="utf-8">
    <title>登入成功</title>
</head>
<body>
歡迎${userName}
</body>
</html>

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