Struts中的路径用的是action路径,而不是jsp路径,所以用的时候尽量不要用相对路径而是绝对路径。绝对路径才是王道。
现在有连个jsp页面,分别为index.jsp和path.jsp。
1、index.jsp文件
<?xml version="1.0" encoding="GB18030" ?> <%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%> <%-- String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; //在head中<base href>指定basePath --%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030" /> <title>Insert title here</title> </head> <body> <a href="path/path.action">路径问题说明</a> </body> </html>
2、path.jsp文件
<?xml version="1.0" encoding="GB18030" ?> <%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%> <%@taglib uri="/struts-tags" prefix="s" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <base href="<%=basePath%>" /> <meta http-equiv="Content-Type" content="text/html; charset=GB18030" /> <title>Insert title here</title> </head> <body> struts2中的路径问题是根据action的路径而不是jsp路径来确定,所以尽量不要使用相对路径。<br /> <a href="index.jsp">index.jsp</a> <br /> 虽然可以用redirect方式解决,但redirect方式并非必要。 <br /> 解决办法非常简单,统一使用绝对路径。(在jsp中用request.getContextRoot方式来拿到webapp的路径) <br /> 或者使用myeclipse经常用的,指定basePath </body> </html>
注意,这里使用basePath来制定文件的绝对路径
<% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>
getContextPath()根据当前的内容得到路劲,getScheme()得到的是http,getServerName()得到的是127.0.0.1(即IP地址),getServerPort()得到当前端口8080,path得到当前项目所在路径,也就是Struts2_0400_Path,最后basePath其实就是http://localhost:8080/Struts2_0400_Path。
然后在每一个的jsp的连接前面都加上basePath就可以得到这个连接的绝对路径。
3、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="path" extends="struts-default" namespace="/path"> <action name="path" class="com.bjsxt.struts2.path.action.PathAction"> <result name="path">/path.jsp</result> </action> </package> </struts>
4、PathAction.java
package com.bjsxt.struts2.path.action; public class PathAction { public String execute() { return "path"; } }