Cheap VPS & Xen Server

Residential Proxy Network - Hourly & Monthly Packages

by convention


We can create struts 2 application without the configuration file struts.xml. There are two ways to create zero configuration file:

  • By convention
  • By annotation

The steps to create zero configuration file using convention is as follows:

  1. Create input page (optional)
  2. Create the action class
  3. Create view components

Example to create zero configuration file by convention.

In this example, we are creating 4 pages :

  1. index.jsp
  2. LoginAction.java
  3. login-success.jsp
  4. login-error.jsp

1) Create index.jsp for input (optional)

This jsp page creates a form using struts UI tags. It receives name and password from the user.

index.jsp

  1. <%@ taglib uri=“/struts-tags” prefix=“s” %>
  2. <s:form action=“login”>
  3. <s:textfield name=“name” label=“Name”></s:textfield>
  4. <s:password name=“password” label=“Password”></s:password>
  5. <s:submit value=“login”></s:submit>
  6. </s:form>

2) Create the action class

The action class name must be suffixed by action following the request name or it must implement the Action interface (or extend ActionSupport). Suppose that request name is login, action class name should be LoginAction if you don’t want to implement Action interface.

The action class must be located inside the action or actions or struts or struts2 package.

LoginAction.java

  1. package action;
  2. public class LoginAction {
  3. private String name,password;
  4. public String getName() {
  5.     return name;
  6. }
  7. public void setName(String name) {
  8.     this.name = name;
  9. }
  10. public String getPassword() {
  11.     return password;
  12. }
  13. public void setPassword(String password) {
  14.     this.password = password;
  15. }
  16. public String execute(){
  17.     if(password.equals(“struts”)){
  18.         return “success”;
  19.     }
  20.     else
  21.         return “error”;
  22. }
  23. }

3) Create view components

The view components must be located inside the WEB-INF/content folder.

The view components must be named with request name – (hyphen) string returned by action class. Suppose that request name is login and string returned by action class is success and error, file name must be login-success.jsp and login-error.jsp.

login-success.jsp

  1. <%@ taglib uri=“/struts-tags” prefix=“s” %>
  2. Welcome,<s:property value=“name”/>

login-error.jsp

  1. Sorry username or password error!
  2. <jsp:include page=“/index.jsp”></jsp:include>

Comments

comments