struts2的访问运行机制:
首先根据URL来访问webapp;
之后webapp开始参考web.xml配置文件去寻找对应的filter类,
其次filter开始参考struts.xml寻找与URL中对应的namespace
如果在struts.xml中找到了与URL对应的namespace则开始寻找对应的action的name和class,
找到对应的class后会调用里面的execute(){}或者是其他的能够返回一个字符串的方法,该方法将返回一个字符串,之后会与对应的result的name进行对比,
如果返回值与result的name相同,则显示出result标签中的内容,否则会出错;result的name可以省略,其默认值为“success”;例如:
<package name="default" namespace="/user" extends="struts-default">
<action name="hi" class="javaclass_source.IndexAction">
<result name="success">
/HI.jsp
</result>
</action>
访问该Hi.jsp的正确URL为http:localhost:8080/user/hi.action;此处的hi.action中的action可以省略"即URL也可以是http:localhost:8080/user/hi;
如果没有找到对应的namespace则返回web.xml进行处理;例如:
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
这个处理将会找到index.jsp;
例如: http://chessing-r:8080/Struts2_002_project/
这里的namespace为“/”之后这个namespace将会与struts.xml中的namespace进行对比;
jsp中路径问题:
在jsp之间进行相互链接跳转时尽量使用绝对路径,相对路径要注意例如http:localhost:8080/user/hi
如果在Hi.jsp中使用相对路径向index.jsp进行跳转如 <a href="index.jsp">index.jsp</a>则只跳转显示的URL为http:localhost:8080/user/index.jsp;显然会出错;
如果使用绝对路径进行跳转则要配好一定的注意事项,配置好bashpath如:
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
说明:第一句request.getContextPath(); 获得webapp名字,工程名;
第二句分别获得http;localhost;8080;
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
此语句后,所有的相对路径跳转都回自动在其前面自动添加basePath;实为绝对路径
<title>My JSP 'HI.jsp' starting page</title>
</head>
<body>
This is HI page. <br>
<a href="index.jsp">index.jsp</a>
</body>
</html>