Struts2学习笔记---namespace

今天的重点:

namespace决定了action的访问路径,默认为“”,可以接受所有路径的action

namespace可以写为/,或者/xxx,或者/xxx/yyy,对应的action访问路径诶/index.action,/xxx/index.aciton,或者

/xxx/yyy/index.action

namespace最要也用模块来命名

1、创建项目

2、配置web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

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>
    <!-- Add packages here -->
	<!-- 下面这句为调为开发模式 -->
	<constant name="struts.devMode" value="true" />
     	<package name="front" extends="struts-default" namespace="/front">
    	<!-- 访问时是/front/test -->
        	<action name="test">
            		<result name="success">/Namespace.jsp</result>
       	 </action>
    </package>
</struts>

首先解释一下:<constant name="struts.devMode" value="true" />这句话

struts.xml中的开发模式
<constant name="struts.devMode" value="true" />
value="true" 表示你的配置文件修改后不需要重起服务器而可以直接运行
value="false" 表示你的配置文件修改后需要重起服务器后再运行 默认为 false

好了,现在看看struts.xml里面的内容,首先name是front,而namespace是/front,action的名字是test,所以访问的时候要/front/test的方式才能访问,否则报错,运行结果如下



 

当namespace为空的时候,这时,请求action的时候如果找不到具体的namespace,那么默认都会到这个空的namespace中来处理,即使你的访问路径是/fasdfsadf/fasdfs/test,还是/fdsfadfsfsaf/asfdd/fd/test,都默认到这个路径下处理,即使上面的乱字符串的路径不存在,也会正常运行

<?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>
    <!-- Add packages here -->
	<!-- 下面这句为调为开发模式 -->
	<constant name="struts.devMode" value="true" />
    <package name="front" extends="struts-default" namespace="/front">
    	<!-- 访问时是/front/test -->
        <action name="test">
            <result>/Namespace.jsp</result>
        </action>
    </package>
    
    <package name="main" extends="struts-default" namespace="">
        <action name="test">
            <result>/Namespace.jsp</result>
        </action>
    </package>
</struts>

 

下面是运行结果



 上面的东西其实就是当请求一个action的时候,如果有这个名字的namespace,如果有,就用这个namespace来处理,如果没有则默认由空的namespace来处理

猜你喜欢

转载自hualang.iteye.com/blog/1028802