struts中的路径用的是action路径,而不是Jsp路径,所以用的时候尽量不要用相对路径,而是用绝对路径
1、index.jsp文件
Java代码
- <body>
- <a href="path/path.action">路径问题说明</a>
- </body>
2、path.jsp文件
Java代码
- <?xml version="1.0" encoding="GB18030" ?>
- <%@ page language="java" contentType="text/html; charset=GB18030"
- pageEncoding="GB18030"%>
- <%@taglib uri="/struts-tags" prefix="s" %>
- <SPAN style="COLOR: #ff0000"> <%
- String path = request.getContextPath();
- String basePath = request.getScheme() "://" request.getServerName() ":" request.getServerPort() path "/";
- %></SPAN>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www./TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www./1999/xhtml">
- <head>
- <SPAN style="COLOR: #ff0000"><base href="<%=basePath%>" /></SPAN>
- <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>
注意,这里使用base来制定文件的绝对路径
<% 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
最后bastPath其实是http://127.0.0.1:8080/Struts2_0400_Path/
3、PathAction.java文件(在包package org.hualang.strutsaction下)
Java代码
- package org.hualang.strutsaction;
- public class PathAction {
- public String execute() {
- return "path";
- }
- }
4、struts.xml文件
Java代码
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE struts PUBLIC
- "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
- "http://struts./dtds/struts-2.0.dtd">
-
- <struts>
- <constant name="struts.devMode" value="true" />
- <package name="path" extends="struts-default" namespace="/path">
- <action name="path" class="org.hualang.strutsaction.PathAction">
- <result name="path">/path.jsp</result>
- </action>
- </package>
- </struts>
运行结果:
当点击路径问题后会跳转到
当点击index.jsp会跳转到
|