0% found this document useful (0 votes)
20 views6 pages

J2ee - ch5 - Struts - Last 4 Topics

The document discusses four key topics related to Apache Struts 2 and Java web applications: creating and using ActionObjects to process requests, handling request parameters with form beans, prepopulating and redisplaying input forms, and utilizing properties files for configuration management. It provides code examples and explanations for each topic, illustrating how to implement these concepts effectively. Overall, the document serves as a guide for managing user input and application settings in Java web applications.

Uploaded by

Trainbit Device
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views6 pages

J2ee - ch5 - Struts - Last 4 Topics

The document discusses four key topics related to Apache Struts 2 and Java web applications: creating and using ActionObjects to process requests, handling request parameters with form beans, prepopulating and redisplaying input forms, and utilizing properties files for configuration management. It provides code examples and explanations for each topic, illustrating how to implement these concepts effectively. Overall, the document serves as a guide for managing user input and application settings in Java web applications.

Uploaded by

Trainbit Device
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Struts last 4 topics:

(1) Processing requests with ActionObjects

In Apache Struts 2, actions are essentially Java objects responsible for processing user requests.
These actions, often referred to as ActionObjects, handle incoming requests, perform required
business logic, and return a result back to the user. Here's how you can create and use ActionObjects
in Struts 2:

1. Create Action Classes (ActionObjects):


Create a Java class for your action, implementing the Action interface or extending the
ActionSupport class. The execute() method contains the logic to process the request.

For example:

public class MyAction extends ActionSupport {


public String execute() {
// Logic to process the request
return SUCCESS; // or any other result code
}
}
2. Configure Action Mappings in struts.xml:
In your Struts 2 configuration file (struts.xml), define action mappings. Here's an example
configuration:

<struts>
<package name="default" namespace="/" extends="struts-default">
<action name="myAction" class="com.example.MyAction">
<result>/success.jsp</result>
</action>
</package>
</struts>
In this example, the myAction URL is mapped to the MyAction class. The SUCCESS result is mapped
to success.jsp, which will be displayed if the action's execute() method returns SUCCESS.

3. Create JSP Views:


Create a JSP file to display the output to the user. For example, success.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


<html>
<head>
<title>Success</title>
</head>
<body>
<h1>Action Executed Successfully!</h1>
</body>
</html>
4. Access the Action through the URL:
Users can access the action by navigating to the corresponding URL, like http://yourapp/myAction.

When the user accesses the URL, Struts 2 will invoke the execute() method of the corresponding
action class (MyAction in this case). The action processes the request, and the SUCCESS result
renders the success.jsp page.

(2) Handling Request Parameters with FormBeans


Handling request parameters with form beans is a common practice in Java web applications,
especially in frameworks like Struts and JavaServer Faces (JSF). Form beans are Java objects used to
encapsulate the data submitted by a form on a web page.
They provide a way to organize and validate user input before processing it in the backend. Here's
how you can handle request parameters with form beans in a typical Java web application:

1. Create a Form Bean:


First, create a Java class representing your form bean. This class should have private fields
corresponding to the form fields, along with getters and setters for each field. The fields should
match the name attributes of the form fields in your JSP.

public class UserForm {


private String username;
private String password;

// Getters and setters for the fields


// ...
}

2. Create a JSP Form:


In your JSP, create a form that submits data to your server. Use the name attributes of the input
fields to match the properties of your form bean.

<form action="processForm" method="post">


Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" /><br />
<input type="submit" value="Submit" />
</form>

3. Configure Your Servlet or Action Class:


In your Servlet or Action class (depending on your web framework), you can use the form bean to
handle the request parameters. For example, in a servlet:

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Retrieve request parameters


String username = request.getParameter("username");
String password = request.getParameter("password");

// Create a form bean and populate it with request parameters


UserForm userForm = new UserForm();
userForm.setUsername(username);
userForm.setPassword(password);

// Perform validation and further processing as needed

// Forward the form bean to a JSP for display or further processing


request.setAttribute("userForm", userForm);
RequestDispatcher dispatcher = request.getRequestDispatcher("result.jsp");
dispatcher.forward(request, response);
}

4. Handle Form Bean in Result JSP:


In your result JSP (result.jsp), you can access the form bean attributes using EL (Expression Language)
and display them:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<h2>Form Data</h2>
Username: <c:out value="${userForm.username}" /><br />
Password: <c:out value="${userForm.password}" /><br />
In this example, ${userForm.username} and ${userForm.password} access the properties of the form
bean, displaying the submitted data.

By using form beans, you can easily manage form data, perform validation, and keep your code
modular and maintainable. Remember that this example demonstrates a servlet-based approach,
but the concept can be applied in various Java web frameworks.

(3) Prepopulating and Redisplaying Input Forms


Handling request parameters with form beans is a common practice in Java web applications,
especially in frameworks like Struts and JavaServer Faces (JSF). Form beans are Java objects used to
encapsulate the data submitted by a form on a web page.
They provide a way to organize and validate user input before processing it in the backend. Here's
how you can handle request parameters with form beans in a typical Java web application:

1. Create a Form Bean:


First, create a Java class representing your form bean. This class should have private fields
corresponding to the form fields, along with getters and setters for each field. The fields should
match the name attributes of the form fields in your JSP.

public class UserForm {


private String username;
private String password;

// Getters and setters for the fields


// ...
}
2. Create a JSP Form:
In your JSP, create a form that submits data to your server. Use the name attributes of the input
fields to match the properties of your form bean.

<form action="processForm" method="post">


Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" /><br />
<input type="submit" value="Submit" />
</form>

3. Configure Your Servlet or Action Class:


In your Servlet or Action class (depending on your web framework), you can use the form bean to
handle the request parameters. For example, in a servlet:

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Retrieve request parameters


String username = request.getParameter("username");
String password = request.getParameter("password");

// Create a form bean and populate it with request parameters


UserForm userForm = new UserForm();
userForm.setUsername(username);
userForm.setPassword(password);

// Perform validation and further processing as needed

// Forward the form bean to a JSP for display or further processing


request.setAttribute("userForm", userForm);
RequestDispatcher dispatcher = request.getRequestDispatcher("result.jsp");
dispatcher.forward(request, response);
}

4. Handle Form Bean in Result JSP:


In your result JSP (result.jsp), you can access the form bean attributes using EL (Expression Language)
and display them:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<h2>Form Data</h2>
Username: <c:out value="${userForm.username}" /><br />
Password: <c:out value="${userForm.password}" /><br />
In this example, ${userForm.username} and ${userForm.password} access the properties of the form
bean, displaying the submitted data.

By using form beans, you can easily manage form data, perform validation, and keep your code
modular and maintainable. Remember that this example demonstrates a servlet-based approach,
but the concept can be applied in various Java web frameworks.
(4) Using Properties Files
Using properties files in Java applications is a common practice for managing configuration settings,
internationalization (i18n), and other constant values. Properties files store key-value pairs, making
it easy to read and modify configurations without altering the source code. Here's how you can use
properties files in a Java application:

1. Creating a Properties File:


Create a .properties file with key-value pairs. For example, let's say you have a configuration file
named config.properties:

# Database Configuration
db.url=jdbc:mysql://localhost:3306/mydatabase
db.username=myuser
db.password=mypassword

# Application Settings
app.version=1.0
app.debugMode=false

2. Loading Properties File in Java:


You can load properties from the file using the java.util.Properties class:

import java.io.InputStream;
import java.util.Properties;

public class ConfigLoader {


private Properties properties = new Properties();

public ConfigLoader() {
try (InputStream input = getClass().getClassLoader().getResourceAsStream("config.properties"))
{ properties.load(input); }
catch (Exception e)
{
e.printStackTrace(); // Handle the exception according to your application's needs
}
}

public String getDbUrl() {


return properties.getProperty("db.url");
}

public String getDbUsername() {


return properties.getProperty("db.username");
}

public String getDbPassword() {


return properties.getProperty("db.password");
}
public String getAppVersion() {
return properties.getProperty("app.version");
}

public boolean isDebugMode() {


return Boolean.parseBoolean(properties.getProperty("app.debugMode"));
}
}
In this example, ConfigLoader class loads the properties from config.properties file. You can then use
methods like getDbUrl(), getDbUsername(), etc., to get the specific values from the properties file.

3. Using the Configuration in Your Application:

public class Main {


public static void main(String[] args) {
ConfigLoader config = new ConfigLoader();

System.out.println("Database URL: " + config.getDbUrl());


System.out.println("Database Username: " + config.getDbUsername());
System.out.println("Application Version: " + config.getAppVersion());
System.out.println("Debug Mode: " + config.isDebugMode());
}
}
This is a basic example, and in real-world applications, you might want to handle exceptions
properly, close the input stream correctly, and provide more robust error handling.

Using properties files in this way allows you to centralize your configuration settings, making it easier
to modify application behavior without modifying the source code.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy