路径问题及动态方法调用(DMI)
路径问题
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
-------------------------------------------------------------------------------------------
1. String path = request.getContextPath(); 代表项目路径, 比如项目名为:struts2_004_Path, 则表示为: /struts2_004_Path
2. request.getScheme() 代表http
3. request.getServerName() 代表localhost
4. request.getServerPort() 代表8080
5. 所以String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
拼接之后就是http://localhost:8080/struts2_004_Path/
此路径用于绝对路径
以上绝对路径如果不加入<base href="<%=basePath%>">, 那么就要在index.jsp前面加上<%=basePath %>, 才能访问到index.jsp
动态action---DMI: Dynamic Method Invoke
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>
<constant name="struts.devMode" value="true" />
<package name="user" namespace="/user" extends="struts-default">
<!-- 第一种方式 -->
<action name="userAdd" class="com.bjsxt.struts2.user.action.UserAction" method="add">
<result>/user_add_success.jsp</result>
</action>
<!-- 第二种方式 -->
<action name="user" class="com.bjsxt.struts2.user.action.UserAction">
<result>/index.jsp</result>
</action>
</package>
</struts>
UserAction.java:
public String add() {
return SUCCESS;
}
jsp页面:
(1) 不推荐使用: 比较古老和繁琐
<a href="user/userAdd">第一种方式:添加用户</a><br>
(2) 推荐使用: 这种方式比较简单, 而且只配置一个action, 使用通配符可以访问多个方法
<a href="user/user!add">第二种方式:添加用户</a>