2012年12月26日

作者:小巫

Strust2 学习 第4part path(路径问题)

Struts 路径是一个小问题,但一不注意会有×××烦

项目例子:Struts2_Path

Action实现类:PathAction.java

 
  
  1. package com.wwj.struts2.path.action;  
  2.  
  3. import com.opensymphony.xwork2.ActionSupport;  
  4.  
  5. public class PathAction extends ActionSupport{  
  6.     @Override 
  7.     public String execute() throws Exception {  
  8.         // TODO Auto-generated method stub  
  9.         return "path";  
  10.     }  

struts.xml配置文件如下:

 
  
  1. <?xml version="1.0" encoding="UTF-8" ?> 
  2. <!DOCTYPE struts PUBLIC  
  3.     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
  4.     "http://struts.apache.org/dtds/struts-2.0.dtd"> 
  5. <struts> 
  6.     <constant name="struts.devMode" value="true" /> 
  7.     <package name="path" extends="struts-default" namespace="/path"> 
  8.         <action name="path" class="com.wwj.struts2.path.action.PathAction"> 
  9.             <result name="path">/path.jsp</result> 
  10.         </action> 
  11.     </package> 
  12. </struts> 

我们可以从struts配置文件有以下内容:

命名空间:/path

action:path

result :path

显示页面:path.jsp

运行项目url :http://localhost:8080/Struts2_Path/path/path.action

会在浏览器显示以下结果:

path.jsp文件

 
  
  1. <?xml version="1.0" encoding="GB18030" ?> 
  2. <%@ page language="java" contentType="text/html; charset=GB18030" 
  3.     pageEncoding="GB18030"%> 
  4. <%@taglib uri="/struts-tags" prefix="s"%> 
  5. <%  
  6.     String path = request.getContextPath();  
  7.     String basePath = request.getScheme() + "://"  
  8.             + request.getServerName() + ":" + request.getServerPort()  
  9.             + path + "/";  
  10. %> 
  11. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
  12. <html xmlns="http://www.w3.org/1999/xhtml"> 
  13.     <head> 
  14.         <base href="<%=basePath%>" /> 
  15.         <meta http-equiv="Content-Type" content="text/html; charset=GB18030" /> 
  16.         <title>Insert title here</title> 
  17.     </head> 
  18.     <body> 
  19.         struts2中的路径问题是根据action的路径而不是jsp路径来确定,所以尽量不要使用相对路径。  
  20.         <br /> 
  21.         <a href="index.jsp">index.jsp</a> 
  22.         <br /> 
  23.         虽然可以用redirect方式解决,但redirect方式并非必要。  
  24.         <br /> 
  25.         解决办法非常简单,统一使用绝对路径。(在jsp中用request.getContextRoot方式来拿到webapp的路径)  
  26.         <br /> 
  27.         或者使用myeclipse经常用的,指定basePath  
  28.     </body> 
  29. </html> 

如果在path.jsp文件中,不指定bastpath,点击index.jsp会发现项目报错,说index.jsp不可用。为什么?因为链接的时候只会根据当前指定的地址来链,而当前地址下没有index.jsp文件,所有会报错。怎么解决这种问题,以上的<base href="<%=basepath%>/>就是用来指定路径的。

路径为:http://localhost:8080/Struts2_Path/

所以呢,在开发项目的时候,需要注意路径这一点,不然会是一件很恐怖的事情,这不是我说的,是马士兵老师说的。