在這篇文章:Apache 利用 mod_rewrite 做到網址轉換達成SEO優化 說到使用此方法的好處,在 Struts2 中也可以利用 WildcardMappings 來達成 SEO 優化,舉下列例子來說明:

原來:http://localhost:8080/guEBS/guWeb/userChooseLang?lang=chinese

變成:http://localhost:8080/guEBS/guWeb/userChooseLang/chinese

 

Step 1:在 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>    
    <constant name="struts.mapper.alwaysSelectFullNamespace" value="false"/>
    <constant name="struts.enable.SlashesInActionNames" value="true"/>
    <constant name="struts.patternMatcher" value="namedVariable"/>        
    
    <package name="guWeb" namespace="/guWeb" extends="struts-default">  

        <action name="userChooseLang/{lang}" class="com.gu.web.GUsetLang">    
            <result>/guWeb/Home.jsp</result>        
        </action>  


    </package>
    <!-- Add addition packages and configuration here. -->
</struts>

 

Step 2:Action Class: com.gu.web.GUsetLang.java

package com.gu.web;

public class GUsetLang extends ActionSupport {

    private String lang;
    @Override
    public String execute() throws Exception {
        // TODO Auto-generated method stub
        String sLang = "chinese".equalsIgnoreCase(getLang()) ? "zh-TW" : "en-US" ;        
        session.put("userLang", sLang);
        super.execute();
        setNavMenu("guWeb");
        return SUCCESS;
    }
    public String getLang() {
        return lang;
    }
    public void setLang(String lang) {
        this.lang = lang;
    }

}

 

Step 3:jsp頁面Home.jsp 的測試

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
       <h1>Wild Card Value</h1>
       lang: <s:property value="lang"/>
</body>
</html>

 

但要注意,若常數 <constant name="struts.patternMatcher" value="namedVariable"/> 或 <constant name="struts.patternMatcher" value="regex"/> ,則 <action name="demo_*" method="{1}" class="..."> 會無法正常作業,這設定只能二擇一。在 http://struts.apache.org/release/2.2.x/docs/wildcard-mappings.html 有說明。


Only one PatternMatcher implementation can be used at a time. The two implementations included with Struts 2 are mutually exclusive. You cannot use Wildcards and Named Variable patterns at the same application (if that were required, you'd need to create a custom PatternMatcher implementation).

參考:

http://www.struts2.info/blog/better-urls-with-struts2

http://struts.apache.org/release/2.2.x/docs/wildcard-mappings.html

arrow
arrow
    文章標籤
    Struts2 WildcardMappings rewrite
    全站熱搜

    MIS 發表在 痞客邦 留言(0) 人氣()