---
title: "Click Framework最佳实践-自动映射,导航（Navigation）"
author: "bill.end"
date: "2009-03-17T10:52:48Z"
tags: ["Eclipse", "HTML", "XML"]
slug: "click-framework-navigation"
draft: false
lastmod: "2009-03-17T10:57:58Z"
id: 350218
url: "https://bill-end.iteye.com/blog/350218"
---

**自动映射**

推荐使用自动映射配置特性。细节参看[自动映射](http://incubator.apache.org/click/)。

自动映射会免去你在click.xml中手动配置URL路径和Page类的映射。如果你遵循这个约定，维护和重构你的应用将会很容易。

你可以很快的找到Page类和对应的HTML模板，并且如果你使用ClickIDE（Eclipse插件）可以在Page类和模板间使用Ctrl+Alt+S快捷键切换。

click.xml配置文件中自动映射的例子（自动映射是默认的）：

```
<click-app>
  <pages package="com.mycorp.dashboard.page"/>
</click-app> 
```

 

设置应用的[mode](http://incubator.apache.org/click/docs/configuration.html#application-mode)值为debug，在应用启动时模板和对应的类的映射关系会被输出。

```
[Click] [debug] automapped pages:
[Click] [debug] /category-tree.htm -> com.mycorp.dashboard.page.CategoryTree
[Click] [debug] /process-list.htm -> com.mycorp.dashboard.page.ProcessList
[Click] [debug] /user-list.htm -> com.mycorp.dashboard.page.UserList  
```

 

**导航（Navigation）**

在Page间跳转使用forward和redirect，建议引用目标页面时使用Page类而不是路径。这会在编译期检查并且不会当你移动页面的位置后修改java代码中的路径字符。

使用Page类去forward到另一个页面：

```
public class CustomerListPage extends Page {

    public ActionLink customerLink = new ActionLink(this, "onCustomerClick");
    
    ..
    
    public boolean onCustomerClick() {
        Integer id = customerLink.getValueInteger();
        Customer customer = getCustomerService().getCustomer(id); 
   
        CustomerDetailPage customerDetailPage = (CustomerDetailPage)
            getContext().createPage(CustomerDetailPage.class);

        customerDetailPage.setCustomer(customer);
        setForward(customerDetailPage);
   
        return false;
    }
} 
```

 

为了redirect到另一个页面，可以使用Page类从Context中获得页面路径。在下面的例子中我们把顾客id作为一个请求参数传递给目标页面。

 

```
public class CustomerListPage extends Page {

    public ActionLink customerLink = new ActionLink(this, "onCustomerClick");
    
    ..
    
    public boolean onCustomerClick() {
        String id = customerLink.getValueInteger();
   
        String path = getContext().getPagePath(CustomerDetailPage.class);		
        setRedirect(path + "?id=" + id);
   
        return false;
    }
} 
```

 

一个快速的redirect到另一个页面的方法是引用目标类。下面的例子是登出一个用户，通过是他的session失效，然后redirect他到应用的主页面。

```
public boolean onLogoutClick() {
        getContext().getSession().invalidate();
        
        setRedirect(HomePage.class);
        
        return false;
    }
```