default location of result pages
In Struts2, the default location for result pages (such as JSP files) is the root directory of the web application or any directory under the WebContent or webapp folder, depending on the project structure. Typically, result pages are placed under the /WEB-INF/pages or similar directory for better organization and to prevent direct access.
For example, if you configure a result as <result name=”success”>/hello.jsp</result>, Struts2 will look for hello.jsp in the root directory of the web application.
Table of Contents
Changing the Default Location
You can change the default location of result pages by specifying a different path in the <result> element in your struts.xml configuration file. You can also use a basePath property to define a common base path for all result locations.
Java Example
Let’s create a simple Struts2 application and configure the result pages to be in a custom directory.
xml
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" namespace="/" extends="struts-default">
<!-- Define an action -->
<action name="hello" class="com.example.action.HelloAction">
<!-- Specify a custom location for the result page -->
<result name="success">/WEB-INF/views/hello.jsp</result>
</action>
</package>
</struts>
java
package com.example.action;
import com.opensymphony.xwork2.ActionSupport;
public class HelloAction extends ActionSupport {
private String message;
@Override
public String execute() {
message = "Hello, World!";
return SUCCESS;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
jsp
<%@ taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<title>Hello</title>
</head>
<body>
<h1><s:property value="message" /></h1>
</body>
</html>
Explanation of the Example
- 1. Â Configuration : The struts.xml file defines an action hello with its result page located at /WEB-INF/views/hello.jsp. This custom location ensures that the JSP file is not directly accessible via the browser, enhancing security.
- 2. Â Struts2 Action : HelloAction.java is a simple action that sets a greeting message.
- 3. Â JSP Page : hello.jsp is placed in the /WEB-INF/views directory and displays the message set by HelloAction.
Benefits of Custom Result Location:
- Security : Placing JSP files under WEB-INF prevents direct access from the web, allowing access only through actions.
- Organization : A custom directory structure helps keep the project organized, especially in larger applications.
Testing the Custom Location
To access the HelloAction, you would use the URL:
http://localhost:8080/yourapp/hello.action
Struts2 will forward the request to the hello.jsp located in the /WEB-INF/views directory.