您的位置:首页 > 编程语言 > Java开发

35-001-1 Struts2框架的前期配置准备

2016-05-11 22:33 477 查看
    首先需要在web.xml中为此web项目添加struts2的过滤器,这样每次客户的请求才能通过过滤器转交给struts2框架,这样struts2框架才能发挥作用的,否则struts2框架就是一个摆设。   

    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">
    <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><!-- *表示所有的请求都交给老子struts2来处理 -->
    </filter-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

 

 在struts1中配置了一个ApplicationResource.xml资源文件,在Struts2中同样存在资源配置文件,
在Struts2中有三种范围的资源文件:
        · 第一种:针对包中的配置资源文件 package.properties ;
        · 第二种:针对一个Action的资源文件,XxxAction.properties ;
        · 第三种:全局性的资源配置文件,一般直接在src目录下,需要额外的配置:struts.properties 中的配置
在Action所在的目录文件中定义一个package.properties    ;
hello.msg = hello world    //资源文件字符串没有双引号

    如果要访问资源文件中的内容,可以通过ActionSupport提供的getText()方法即可
    下面通过在HelloAction中的方法execute()提供getText()方法
public class HelloAction extends ActionSupport {
    private String msg ;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    @Override
    public String execute() throws Exception {
        setMsg(super.getText("hello.msg")) ; //获取资源文件中的内容

        return ActionSupport.SUCCESS;
    }

}

    由于配置的是一个包级别的资源文件,所以会从package.properties取得文件 ;
    配置一个针对Action的资源文件  HelloAction.properties
hello.msg = mapped action

    如果在一个acition对应的目录中存在XxxAction.properties和package.properties等资源文件,
则XxxAction.properties资源文件的优先级更高 ;
 案例:直接在src目录下建立一个全局的资源文件,Message.properties (资源文件名的首字母大写)
 hello.msg = Global scope in the src folder

       此时配置后,打开网页没有效果,即strut2不认这个资源文件,此时必须定义一个struts.properties文件,但是还依然无法读取次资源文件的内容 ,此时必须研究struts-core开发包,在org.apache.struts2.default.properties,找到此文件中的struts.custom.i18n.resources,然后把struts.custom.i18n.resources=Message复制到struts.properties文件中既可以让struts识别到message文件中的内容
;    
案例:struts.properties(struts不要大写)
struts.custom.i18n.resources=Message
此时是可以访问Message.properties里面的内容了,但是必须要先删除掉XxxAction.properties和package.properties文件。从default.properties文件的struts.custom.i18n.resources中可以看到struts可以配置多个全局的资源文件 ;

资源文件下载:https://yunpan.cn/OcSsUKCQCGv4sU  访问密码 75fc
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: