Skip to content

Commit

Permalink
Detect and remove HTTP fragments from the path.
Browse files Browse the repository at this point in the history
  • Loading branch information
igr committed Jan 9, 2021
1 parent 2c35fe9 commit d359c65
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/main/java/jodd/http/HttpRequest.java
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ public class HttpRequest extends HttpBase<HttpRequest> {
protected String host = "localhost";
protected int port = Defaults.DEFAULT_PORT;
protected String method = "GET";
protected String fragment = null;
protected String path = StringPool.SLASH;
protected HttpMultiMap<String> query;

Expand Down Expand Up @@ -133,6 +134,13 @@ public HttpRequest port(final int port) {
return this;
}

/**
* Returns HTTP fragment, if specified; otherwise returns <code>null</code>.
*/
public String fragment() {
return fragment;
}

// ---------------------------------------------------------------- set

/**
Expand Down Expand Up @@ -329,6 +337,14 @@ public HttpRequest path(String path) {
path = StringPool.SLASH + path;
}

// remove fragment

final int fragmentIndex = path.indexOf('#');
if (path.indexOf('#') != -1) {
this.fragment = path.substring(fragmentIndex + 1);
path = path.substring(0, fragmentIndex);
}

final int ndx = path.indexOf('?');

if (ndx != -1) {
Expand Down Expand Up @@ -516,6 +532,11 @@ public String url() {
url.append(queryString);
}

if (fragment != null) {
url.append('#');
url.append(fragment);
}

return url.toString();
}

Expand Down
28 changes: 28 additions & 0 deletions src/test/java/jodd/http/FragmentTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package jodd.http;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

class FragmentTest {

@Test
void testFragment() {
final HttpRequest request = HttpRequest.get("https://studioharrison.com/#product-group");

assertEquals("/", request.path);
assertEquals("product-group", request.fragment());

assertEquals("https://studioharrison.com/#product-group", request.url());
}

@Test
void testFragmentWithQuery() {
final HttpRequest request = HttpRequest.get("https://studioharrison.com/foo?me=1#foo");

assertEquals("/foo", request.path);
assertEquals("foo", request.fragment());

assertEquals("https://studioharrison.com/foo?me=1#foo", request.url());
}
}

0 comments on commit d359c65

Please sign in to comment.