View Javadoc

1   /*
2    * $Id: URLBean.java 439747 2006-09-03 09:22:46Z mrdon $
3    *
4    * Copyright 2006 The Apache Software Foundation.
5    *
6    * Licensed under the Apache License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    *
10   *      http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.struts2.util;
19  
20  import java.util.HashMap;
21  import java.util.Map;
22  
23  import javax.servlet.http.HttpServletRequest;
24  import javax.servlet.http.HttpServletResponse;
25  
26  import org.apache.struts2.views.util.UrlHelper;
27  
28  
29  /***
30   * A bean that can generate a URL.
31   *
32   */
33  public class URLBean {
34  
35      HashMap params;
36      HttpServletRequest request;
37      HttpServletResponse response;
38      String page;
39  
40  
41      public void setPage(String page) {
42          this.page = page;
43      }
44  
45      public void setRequest(HttpServletRequest request) {
46          this.request = request;
47      }
48  
49      public void setResponse(HttpServletResponse response) {
50          this.response = response;
51      }
52  
53      public String getURL() {
54          // all this trickier with maps is to reduce the number of objects created
55          Map fullParams = null;
56  
57          if (params != null) {
58              fullParams = new HashMap();
59          }
60  
61          if (page == null) {
62              // No particular page requested, so go to "same page"
63              // Add query params to parameters
64              if (fullParams != null) {
65                  fullParams.putAll(request.getParameterMap());
66              } else {
67                  fullParams = request.getParameterMap();
68              }
69          }
70  
71          // added parameters override, just like in URLTag
72          if (params != null) {
73              fullParams.putAll(params);
74          }
75  
76          return UrlHelper.buildUrl(page, request, response, fullParams);
77      }
78  
79      public URLBean addParameter(String name, Object value) {
80          if (params == null) {
81              params = new HashMap();
82          }
83  
84          if (value == null) {
85              params.remove(name);
86          } else {
87              params.put(name, value.toString());
88          }
89  
90          return this;
91      }
92  
93      public String toString() {
94          return getURL();
95      }
96  }