or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

authentication-filters.mdauthorization-filters.mdenvironment-config.mdfilter-chain-management.mdindex.mdjsp-tag-library.mdservlet-filters.mdsession-management.mdweb-security-management.mdweb-subjects.mdweb-utilities.md

web-utilities.mddocs/

0

# Web Utilities

1

2

Utility classes for common web operations in Apache Shiro including request handling, path resolution, redirect management, request saving/restoration, and servlet request/response type conversion. These utilities simplify common web security tasks.

3

4

## Capabilities

5

6

### WebUtils Class

7

8

```java { .api }

9

class WebUtils {

10

/**

11

* Returns the path within the application for the given request.

12

*

13

* @param request the HTTP servlet request

14

* @return the path within the application

15

*/

16

public static String getPathWithinApplication(HttpServletRequest request);

17

18

/**

19

* Returns the context path for the given request.

20

*

21

* @param request the HTTP servlet request

22

* @return the context path

23

*/

24

public static String getContextPath(HttpServletRequest request);

25

26

/**

27

* Retrieves the WebEnvironment from the ServletContext.

28

*

29

* @param servletContext the servlet context

30

* @return the WebEnvironment instance

31

*/

32

public static WebEnvironment getWebEnvironment(ServletContext servletContext);

33

34

/**

35

* Issues a redirect to the specified URL.

36

*

37

* @param request the servlet request

38

* @param response the servlet response

39

* @param url the URL to redirect to

40

* @throws IOException if redirect fails

41

*/

42

public static void issueRedirect(ServletRequest request, ServletResponse response, String url) throws IOException;

43

44

/**

45

* Issues a redirect with query parameters.

46

*

47

* @param request the servlet request

48

* @param response the servlet response

49

* @param url the URL to redirect to

50

* @param queryParams query parameters to append

51

* @param contextRelative whether URL is context-relative

52

* @param http10Compatible whether to use HTTP 1.0 compatible redirect

53

* @throws IOException if redirect fails

54

*/

55

public static void issueRedirect(ServletRequest request, ServletResponse response, String url,

56

Map<String, ?> queryParams, boolean contextRelative, boolean http10Compatible)

57

throws IOException;

58

59

/**

60

* Saves the current request for later restoration.

61

*

62

* @param request the servlet request to save

63

*/

64

public static void saveRequest(ServletRequest request);

65

66

/**

67

* Retrieves a previously saved request.

68

*

69

* @param request the current servlet request

70

* @return the saved request or null if none exists

71

*/

72

public static SavedRequest getSavedRequest(ServletRequest request);

73

74

/**

75

* Retrieves and clears a previously saved request.

76

*

77

* @param request the current servlet request

78

* @return the saved request or null if none exists

79

*/

80

public static SavedRequest getAndClearSavedRequest(ServletRequest request);

81

82

/**

83

* Redirects to a previously saved request.

84

*

85

* @param request the servlet request

86

* @param response the servlet response

87

* @param fallbackUrl URL to redirect to if no saved request exists

88

* @throws IOException if redirect fails

89

*/

90

public static void redirectToSavedRequest(ServletRequest request, ServletResponse response, String fallbackUrl)

91

throws IOException;

92

93

/**

94

* Converts a ServletRequest to HttpServletRequest.

95

*

96

* @param request the servlet request

97

* @return the HTTP servlet request

98

*/

99

public static HttpServletRequest toHttp(ServletRequest request);

100

101

/**

102

* Converts a ServletResponse to HttpServletResponse.

103

*

104

* @param response the servlet response

105

* @return the HTTP servlet response

106

*/

107

public static HttpServletResponse toHttp(ServletResponse response);

108

109

/**

110

* Returns whether the request is an HTTP request.

111

*

112

* @param request the servlet request

113

* @return true if request is HTTP

114

*/

115

public static boolean isHttp(ServletRequest request);

116

}

117

```

118

119

### SavedRequest Class

120

121

```java { .api }

122

class SavedRequest implements Serializable {

123

/**

124

* Creates a SavedRequest from the given HTTP request.

125

*

126

* @param request the HTTP servlet request to save

127

*/

128

public SavedRequest(HttpServletRequest request);

129

130

/**

131

* Returns the HTTP method of the saved request.

132

*

133

* @return the HTTP method (GET, POST, etc.)

134

*/

135

public String getMethod();

136

137

/**

138

* Returns the query string of the saved request.

139

*

140

* @return the query string

141

*/

142

public String getQueryString();

143

144

/**

145

* Returns the request URI of the saved request.

146

*

147

* @return the request URI

148

*/

149

public String getRequestURI();

150

151

/**

152

* Returns the request URL of the saved request.

153

*

154

* @return the request URL

155

*/

156

public String getRequestURL();

157

158

/**

159

* Returns the parameter map of the saved request.

160

*

161

* @return Map of parameter names to value arrays

162

*/

163

public Map<String, String[]> getParameterMap();

164

165

/**

166

* Returns the headers of the saved request.

167

*

168

* @return Map of header names to value lists

169

*/

170

public Map<String, List<String>> getHeaders();

171

172

/**

173

* Returns the locales of the saved request.

174

*

175

* @return List of Locale objects

176

*/

177

public List<Locale> getLocales();

178

}

179

```

180

181

### RequestPairSource Interface

182

183

```java { .api }

184

interface RequestPairSource {

185

/**

186

* Returns the servlet request.

187

*

188

* @return the ServletRequest instance

189

*/

190

ServletRequest getServletRequest();

191

192

/**

193

* Returns the servlet response.

194

*

195

* @return the ServletResponse instance

196

*/

197

ServletResponse getServletResponse();

198

}

199

```

200

201

## Usage Examples

202

203

### Request Saving and Restoration

204

205

```java

206

public class LoginController {

207

208

public void handleLogin(HttpServletRequest request, HttpServletResponse response) {

209

Subject currentUser = SecurityUtils.getSubject();

210

211

if (!currentUser.isAuthenticated()) {

212

// Save the original request before redirecting to login

213

WebUtils.saveRequest(request);

214

WebUtils.issueRedirect(request, response, "/login");

215

return;

216

}

217

218

// User is authenticated, redirect to saved request or default

219

WebUtils.redirectToSavedRequest(request, response, "/dashboard");

220

}

221

222

public void processLogin(HttpServletRequest request, HttpServletResponse response,

223

String username, String password) {

224

try {

225

Subject currentUser = SecurityUtils.getSubject();

226

UsernamePasswordToken token = new UsernamePasswordToken(username, password);

227

currentUser.login(token);

228

229

// Login successful, redirect to saved request

230

WebUtils.redirectToSavedRequest(request, response, "/dashboard");

231

232

} catch (AuthenticationException e) {

233

// Login failed, redirect back to login page

234

WebUtils.issueRedirect(request, response, "/login?error=true");

235

}

236

}

237

}

238

```

239

240

### Path and URL Utilities

241

242

```java

243

public class SecurityUtils {

244

245

public boolean isSecurePath(HttpServletRequest request) {

246

String path = WebUtils.getPathWithinApplication(request);

247

return path.startsWith("/admin/") || path.startsWith("/secure/");

248

}

249

250

public String buildAbsoluteUrl(HttpServletRequest request, String relativePath) {

251

String contextPath = WebUtils.getContextPath(request);

252

String scheme = request.getScheme();

253

String serverName = request.getServerName();

254

int serverPort = request.getServerPort();

255

256

StringBuilder url = new StringBuilder();

257

url.append(scheme).append("://").append(serverName);

258

259

if ((scheme.equals("http") && serverPort != 80) ||

260

(scheme.equals("https") && serverPort != 443)) {

261

url.append(":").append(serverPort);

262

}

263

264

url.append(contextPath).append(relativePath);

265

return url.toString();

266

}

267

268

public void enforceHttps(HttpServletRequest request, HttpServletResponse response)

269

throws IOException {

270

if (!"https".equals(request.getScheme())) {

271

String httpsUrl = buildAbsoluteUrl(request, request.getRequestURI())

272

.replace("http://", "https://");

273

WebUtils.issueRedirect(request, response, httpsUrl);

274

}

275

}

276

}

277

```

278

279

### Custom Redirect Handling

280

281

```java

282

public class CustomRedirectHandler {

283

284

public void redirectWithMessage(ServletRequest request, ServletResponse response,

285

String url, String message) throws IOException {

286

Map<String, String> params = new HashMap<>();

287

params.put("message", message);

288

289

WebUtils.issueRedirect(request, response, url, params, true, false);

290

}

291

292

public void redirectToLogin(ServletRequest request, ServletResponse response,

293

String reason) throws IOException {

294

// Save current request

295

WebUtils.saveRequest(request);

296

297

// Redirect to login with reason

298

Map<String, String> params = new HashMap<>();

299

params.put("reason", reason);

300

301

WebUtils.issueRedirect(request, response, "/login", params, true, false);

302

}

303

304

public void handleLogout(HttpServletRequest request, HttpServletResponse response)

305

throws IOException {

306

Subject currentUser = SecurityUtils.getSubject();

307

currentUser.logout();

308

309

// Clear any saved requests

310

WebUtils.getAndClearSavedRequest(request);

311

312

// Redirect to home page

313

WebUtils.issueRedirect(request, response, "/?logout=success");

314

}

315

}

316

```

317

318

### Request Analysis Utilities

319

320

```java

321

public class RequestAnalyzer {

322

323

public void analyzeRequest(HttpServletRequest request) {

324

String path = WebUtils.getPathWithinApplication(request);

325

String contextPath = WebUtils.getContextPath(request);

326

327

System.out.println("Request Analysis:");

328

System.out.println(" Context Path: " + contextPath);

329

System.out.println(" Path within App: " + path);

330

System.out.println(" Full Request URI: " + request.getRequestURI());

331

System.out.println(" Query String: " + request.getQueryString());

332

333

// Check for saved requests

334

SavedRequest savedRequest = WebUtils.getSavedRequest(request);

335

if (savedRequest != null) {

336

System.out.println(" Saved Request:");

337

System.out.println(" Method: " + savedRequest.getMethod());

338

System.out.println(" URI: " + savedRequest.getRequestURI());

339

System.out.println(" Query: " + savedRequest.getQueryString());

340

}

341

}

342

343

public boolean isSameOrigin(HttpServletRequest request, String url) {

344

try {

345

URL requestUrl = new URL(request.getRequestURL().toString());

346

URL targetUrl = new URL(url);

347

348

return requestUrl.getProtocol().equals(targetUrl.getProtocol()) &&

349

requestUrl.getHost().equals(targetUrl.getHost()) &&

350

requestUrl.getPort() == targetUrl.getPort();

351

} catch (MalformedURLException e) {

352

return false;

353

}

354

}

355

}

356

```