Struts2 学习笔记04 路径问题

来源:互联网 发布:ubuntu 安装 kde桌面 编辑:程序博客网 时间:2024/06/07 03:37

  今天学习下路径问题,Struts2 里路径根据action路径,而不是jsp路径,所以我们不要使用相对路径,简单做个试验说明一下。

struts.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN""http://struts.apache.org/dtds/struts-2.3.dtd"><struts>     <!-- Add packages here -->    <constant name="struts.devMode" value="true" />    <package name="front" namespace="/path" extends="struts-default">    <action name="hell" class="com.tfj.strut2.Path"><result name="success">/JSP/path.jsp</result></action>           </package>    </struts>


我把两个jsp文件放在Jsp文件夹里。

先访问http://localhost:8080/Struts2_0400_Path/path/hell。

path.jsp

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'path.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->  </head>    <body>    Struts2 里路径根据action路径,而不是jsp路径,所以我们不要使用相对路径.<a href="index.jsp">index</a> <br>  </body></html>
在path里用的“index”是相对路径。虽然path.jsp和index.jsp在同一文件夹下但是却无法访问成功。


为了避免这种情况,我们不使用相对路径,myeclipse会帮我们生成两个有关路径的变量在jsp文件里。

String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

那么我们有两种方法,来进行路径命名。

1.把<a href="index.jsp">index</a>改为<a href="<%=basePath%>JSP/index.jsp">index</a>;

2.在<head></head>里加个<base>标签 <base href="JSP/<%=basePath%>"/>然后所有的连接都会添加这个路径。只要用<a href="index.jsp">index</a>即可。

Tips: <welcome-file-list>
    <welcome-file>path.jsp</welcome-file>
  </welcome-file-list>

表示访问http://localhost:8080/Struts2_0400_Path/打开path.jsp,当然前提是path.jsp在根目录。


原创粉丝点击