如何在struts2中创建动态URL?

时间:2017-02-21 06:29:04

标签: java jsp url struts2

我创建了表单login.jsp,当用户输入username&密码,然后我想创建像:/companyName/username

的网址

示例:如果公司名称为“abc”且用户名为“parth1”,则网址为"http://localhost:8080/Temp_Central_Emp/abc/parth1/afterLogin.jsp"

我根据用户名从数据库中获取companyName

文件: login.jsp

<s:form action="afterLogin" method="post">
    <s:textfield label="Enter username" key="userId" maxlength="5" size="30" id="userId"/>
    <s:password label="Enter password" key="userPsw" size="30" />
    <tr>
        <td></td>
        <td>
            <img src="<c:url value='simple-captcha.png' />" />
            <br />
            <p>Press F5 for refresh.</p>
        </td>
    </tr>
    <s:textfield label="Enter code" key="captchaResponse" size="30" />
    <s:submit value="Login" />
</s:form>

文件: struts.xml

<struts>
<constant name="struts.enable.SlashesInActionNames" value="true"/> 
<constant name="struts.mapper.alwaysSelectFullNamespace" value="false"/>
<constant name="struts.devMode" value="true" />
<package name="a" extends="struts-default">

    <action name="afterLogin" class="com.parth.LoginAction">
        <result name="success">/afterLogin.jsp</result>
    </action>

</package>

文件: LoginAction.java

public class LoginAction extends ActionSupport{

private Map<String, Object> session;
private String userId;
private String userPsw;
private String url;

private static final long serialVersionUID = 1L;

@Override
@Action(value="{url}/afterLogin")
public String execute() throws Exception {      
    // business logic to insert user into database
    url = "/companyName/" + userId;
    return SUCCESS;
}

 /* Getters and Setters */
}

我引用这个链接,但我的需求是不同的。 Creating dynamic URL with 2 action parameters in Struts 2 using OGNL

我也尝试从这个链接编码,但我仍然没有解决它。

2 个答案:

答案 0 :(得分:0)

尝试将 url 变量放在struts.xml

<action name="afterLogin" class="com.parth.LoginAction">
    <result name="success">${url}/afterLogin.jsp</result>
</action>

并在此处删除您的注释Action

@Override
//@Action(value="{url}/afterLogin") // remove this
public String execute() throws Exception {      
    // business logic to insert user into database
    url = "/companyName/" + userId;
    return SUCCESS;
}

答案 1 :(得分:0)

如果要更改URL并遵循PRG模式,结果应为重定向操作类型。见Parameters in configuration results

<result name="success" type="redirectAction">afterLogin?companyName=${companyName}&userId=${userId}</result>

<action name="afterLogin">
   <result>/afterLogin.jsp</result>
</action>