Struts2学习日记-3 Path Action 通配符
Struts2学习日志---3 Path Action 通配符
struts2中的路径问题是根据action的路径而不是jsp路径来确定,所以尽量不要使用相对路径。
虽然可以用redirect方式解决,但redirect方式并非必要。
解决办法非常简单,统一使用绝对路径。(在jsp中用request.getContextRoot方式来拿到webapp的路径)
或者使用myeclipse经常用的,指定basePath
<% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <base href="<%=basePath%>"> <a href="<%=basePath%>index.jsp">index.jsp</a>
动态方法调用:
Action执行的时候并不一定要执行execute方法
可以在配置文件中配置Action的时候用method=来指定执行哪个方法
也可以在url地址中动态指定(动态方法调用DMI)(推荐)
前者会产生太多的action,所以不推荐使用
UserAction.java中
package com.zhangmin.struts.action; import com.opensymphony.xwork2.ActionSupport; public class UserAction extends ActionSupport { public String add() { return SUCCESS; } }
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" extends="struts-default" namespace="/user"> <action name="user" class="com.zhangmin.struts.action.UserAction"> <result>/user_add_success.jsp</result> </action> </package> </struts>
jsp文件中
<a href="<%=path %>/user/user!add">添加用户</a>
通配符
使用通配符,将配置量降到最低
不过,一定要遵守"约定优于配置"的原则
1.src 目录下包括CourseAction.java TeacherAction.java StudentAction.java
package com.zm.struts.action;
import com.opensymphony.xwork2.ActionSupport; public class CourseAction extends ActionSupport{ public String add(){ return SUCCESS; } public String delete(){ return SUCCESS; } }
package com.zm.struts.action;
import com.opensymphony.xwork2.ActionSupport; public class StudentAction extends ActionSupport{ public String add(){ return SUCCESS; } public String delete(){ return SUCCESS; } }
package com.zm.struts.action; import com.opensymphony.xwork2.ActionSupport; public class TeacherAction extends ActionSupport{ public String add(){ return SUCCESS; } public String delete(){ return SUCCESS; } }
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="actions" namespace="/actions" extends="struts-default"> <action name="Student*" class="com.zm.struts.action.StudentAction" method="{1}"> <result>/Student{1}_success.jsp</result> </action> <action name="*_*" class="com.zm.struts.action.{1}Action" method="{2}"> <result>/{1}_{2}_success.jsp</result> </action> </package> </struts>
3.webRoot下面的jsp文件,用于显示:
Course_add_success.jsp
Course_delete_success.jsp
Student_add_success.jsp
Student_delete_success.jsp
Teacher_add_success.jsp
Teacher_delete_success.jsp