[go: up one dir, main page]

0% found this document useful (0 votes)
14 views34 pages

Struts

Struts is an open-source framework for building web applications using the MVC (Model View Controller) architecture, primarily for J2EE applications. It simplifies the development of maintainable and extensible web applications by providing components such as Action, Result, and interceptors, along with a custom tag library for JSP pages. The framework promotes good design practices, supports input validation and internationalization, and enables easy integration with databases through JDBC.

Uploaded by

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

Struts

Struts is an open-source framework for building web applications using the MVC (Model View Controller) architecture, primarily for J2EE applications. It simplifies the development of maintainable and extensible web applications by providing components such as Action, Result, and interceptors, along with a custom tag library for JSP pages. The framework promotes good design practices, supports input validation and internationalization, and enables easy integration with databases through JDBC.

Uploaded by

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

Struts

Struts
• Struts is used to create a web applications based on servlet and JSP.
• Struts depend on the MVC (Model View Controller) framework. Struts application is a genuine web
application.
• Struts are thoroughly useful in building J2EE (Java 2 Platform, Enterprise Edition) applications because struts
takes advantage of J2EE design patterns. Struts follows these J2EE design patterns including MVC.
• In struts, the composite view manages the layout of its sub-views and can implement a template, making
persistent look and feel easier to achieve and customize across the entire application. A composite view is made
up by using other reusable sub views such that a small change happens in a sub-view is automatically updated
in every composite view.
• Struts consists of a set of own custom tag libraries.
• Struts are based on MVC framework which is pattern oriented and includes JSP custom tag libraries. Struts also
supports utility classes.
• Struts is an open source framework that extends the Java
Servlet API and employs a Model, View, Controller (MVC)
architecture.
• It enables you to create maintainable, extensible, and
flexible web applications based on standard technologies,
such as JSP pages, JavaBeans, resource bundles, and
XML.
Components of Struts in Java

• There are many components of struts. They are as follows-


• Filter Dispatcher
• Action
• Result
• Configuration file
• Interceptors
• Deployment descriptor
• Tag Library
1. Filter Dispatcher
• It is the controller component of Struts application. From a coding point of view, the
controller is represented by org.Apache.Struts2.filtered patcher class, which is just a filter
class.
• A controller component is responsible for each incoming request and identifies appropriate
actions to process the request at outer processing. The request is also responsible for
identifying appropriate views to display the result with the help of the result component.
<form action= “bean.jsp”>
• Here, action refers to the information the user holds by this. In other
words, this is a java bean class.
2. Action

• In Struts 2, the functionality of the model is represented by the action component. From
a coding point of view, an action is represented by a bean class containing the state of
an application and any business logic. This component is developed by the programmer.
An Action is a model in Struts 2 which is used to handle all the data.

3. Result
• The result means view. In the Struts2 application, the functionality of view is managed
by the result component. That is, the result component is responsible for the
presentation logic of the Struts application.
• A result is responsible for identifying JSP pages to display the results.
4. Configuration file

• Struts 2 uses a configuration file to describe the action, result and other
resources. The name of this file is — struts.xml.

5. Interceptors
• Interceptors are the helper components of the controller and are
responsible for applying cross-cutting concerns or other commonly used
logics. Wherever we want to use the logic in JSP or servlet, we use
interceptors. There are many interceptors in Struts.
6. Deployment Descriptor

• This is the deployment descriptor of the Struts Application and contains the
information about controller web.xml. All information gathered in the
deployment descriptor, which is used in MVC. It stores information about how
many JSP and servlets used in this application. Basically, it is the XML file.
7. Tag Library
• Struts 2 provides a custom tag library to develop JSP pages and to manipulate the
data. The user can design the form or text using the tag library. First, we make
the tag directive in this library.
Features of Struts:
• Struts encourages good design practices and modelling because the framework is designed with “time-proven” design
patterns.
• Struts is almost simple, so easy to learn and use.
• It supports many convenient features such as input validation and internationalization.
• It takes much of the complexity out as instead of building your own MVC framework, you can use struts.
• Struts is very well integrated with J2EE.
• Struts has large user community.
• It is flexible and extensible, it is easy for the existing web applications to adapt the struts framework.
• Struts provide good tag libraries.
• It allows capturing input form data into javabean objects called Action forms.
• It also hand over standard error handling both programmatically and declaratively.
Working of Struts:
• In the initialization phase, the controller rectify a configuration file and used it to deploy other control layer objects.
• Struts configuration is form by these objects combined together. The struts configuration defines among other things
the action mappings for an application.
• Struts controller servlet considers the action mappings and routes the HTTP requests to other components in the
framework.
• Request is first delivered to an action and then to JSP.
• The mapping helps the controller to change HTTP requests into application actions.
• The action objects can handle the request from and responds to the client (generally a web browser). Action objects
have access to the applications controller servlet and also access to the servlet’s methods.
• When delivering the control, an action objects can indirectly forward one or more share objects, including
javabeans by establish them in the typical situation shared by java servlets.
MVC Architecture
• MVC means Model-View-Controller where model is responsible for business logic, view handles
the user interaction with application and controller decides the flow of application.
• Figure 1.1 explains the working methodology behind MVC architecture which is as follows:
1. User sends the request using view which reaches to the controller on the server.
2. Controller decides the respective model and delivers the control to particular model.
3. As a result of business processing, model changes its state.
4. Depending on the state change of model, control redirects the flow to the view. Main
advantage of this architecture is the separation of data layer, presentation layer and pure
business logic.
MVC Architecture
MVC Architecture
• Model: Model is responsible for providing the data from the database and saving the data into the data
store. All the business logic are implemented in the Model. Data entered by the user through View are
check in the model before saving into the database. Data access, Data validation and the data saving
logic are part of Model.
• View: View represents the user view of the application and is responsible for taking the input from the
user, dispatching the request to the controller and then receiving response from the controller and
displaying the result to the user. HTML, JSPs, Custom Tag Libraries and Resources files are the part of
view component.
• Controller: Controller is intermediary between Model and View. Controller is responsible for receiving
the request from client. Once request is received from client it executes the appropriate business logic
from the Model and then produce the output to the user using the View component. ActionServlet,
Action, ActionForm and struts-config.xml are the part of Controller.
Advantages of Struts

• An advanced framework with a lot of features.


• Based on the MVC architecture.
• Simple configuration.
• Interceptors to reduce the cross cutting functionality.
• OGNL(Object-Graph Navigation Language)
• Pluggable with different Result types like Ajax, JSP, Free Marker, Velocity
etc.
Why is Struts so useful?

• Structural separation of data presentation and business logic


• Easy separation of development tasks(web design, database…)
• Increases maintainability and extensibility(new views!)
• Increases reusability of code
• 2.Struts provides a controller that manages the control flow
• Changes in the flow can all be done in struts-config.xml
• Abstraction from (hard coded) filenames (forwards)
• 3.Easy localization ( internationalization is more important than ever)
• 4.Based on standard Java technologies ( JSP, Servlets, Javabeans)
• Thus running on all kinds of JSP/ Servlet containers
• 5.Open-source
• Affordable
• No dependence on external companies
• Robustness ( due to freely accessible source code)
• 6.Very vivid open-source project with growing developer community.
How Struts Works
• The basic purpose of the Java Servlets in struts is to handle requests made
by the client or by web browsers.
• In struts JavaServerPages (JSP) are used to design the dynamic web pages. I
• n struts, servlets helps to route request which has been made by the web
browsers to the appropriate ServerPage. The use of servlet as a router helps
to make the web applications easier to design, create, and maintain.
• Struts is purely based on the Model- View- Contoller (MVC) design pattern.
It is one of the best and most well developed design patterns in use.
• By using the MVC architecture we break the processing in three sections
named Model, the View, and the Controller.
How Struts Works
Process flow:
• web.xml : Whenever the container gets start up the first work it does is to check the web.xml file
and determine what struts action Servlets exist. The container is responsible for mapping all the file
request to the correct action Servlet.
• A Request : This is the second step performed by the container after checking the web.xml file. In
this the user submits a form within a browser and the request is intercepted by the controller.
• The Controller : This is the heart of the container. Most Struts application will have only one
controller that is ActionServlet which is responsible for directing several Actions. The controller
determines what action is required and sends the information to be processed by an action Bean.
The key advantage of having a controller is its ability to control the flow of logic through the highly
controlled, centralized points.
• struts.config.xml : Struts has a configuration file to store mappings of actions. By using this file
there is no need to hard code the module which will be called within a component. The one more
responsibility of the controller is to check the struts.config.xml file to determine which module to be
called upon an action request. Struts only reads the struts.config.xml file upon start up.
Process flow:
• Model : The model is basically a business logic part which takes the response from the user and stores the result for the
duration of the process. This is a great place to perform the preprocessing of the data received from request. It is
possible to reuse the same model for many page requests. Struts provides the ActionForm and the Action classes which
can be extended to create the model objects.
• View : The view in struts framework is mainly a jsp page which is responsible for producing the output to the user.
• Struts tag libraries : These are struts components helps us to integrate the struts framework within the project’s logic.
These struts tag libraries are used within the JSP page. This means that the controller and the model part can’t make use
of the tag library but instead use the struts class library for strut process control.
• Property file : It is used to store the messages that an object or page can use. Properties files can be used to store the
titles and other string data. We can create many property files to handle different languages.
• Business objects : It is the place where the rules of the actual project exists. These are the modules which just regulate
the day- to- day site activities.
The Response : This is the output of the View JSP object
Deploying the application in struts with database
connectivity

• Deploying an application in Struts with database


connectivity involves several steps. Struts is a popular
Java web application framework for building enterprise-
level applications, while database connectivity is typically
handled through technologies like JDBC (Java Database
Connectivity), Hibernate, or JPA (Java Persistence API).
Here, we'll walk through the general process for
deploying a Struts application with database connectivity.
• Steps to Deploy a Struts Application with Database Connectivity in Java:-
• 1. Setup Your Development Environment
• Install Java Development Kit (JDK): Make sure you have the JDK installed and
configured on your machine.
• Install Apache Tomcat: Download and install Apache Tomcat or any other servlet
container to run your Struts application.
• Struts Framework: Include the Struts libraries in your project. You can use a
build tool like Maven or Gradle to manage dependencies, or manually download the
Struts JARs.
• Database: Install a database system like MySQL, PostgreSQL, or Oracle. Make
sure your database is up and running.
• 2. Create a Struts Application
• Project Structure:
• WEB-INF/: Contains your Struts configuration files (struts-config.xml), web.xml, and JSP files.
• src/: Your Java classes (Struts Actions, Form Beans, etc.).
• lib/: The libraries (JAR files) that your application needs (Struts JARs, JDBC driver, etc.).
3. Configure Struts:-
struts-config.xml: This file configures the Action classes, Form Beans, and
mapping for each action
• <struts-config>
• <form-beans>
• <form-bean name="loginForm" type="com.example.LoginForm" />
• </form-beans>
<action-mappings>
• <action path="/login"
• type="com.example.LoginAction"
• name="loginForm"
• scope="request"
• input="/login.jsp">
• <forward name="success" path="/home.jsp" />
• <forward name="failure" path="/login.jsp" />
• </action>
• </action-mappings>
• </struts-config>
4. Database Connectivity:- For database interaction, you'll likely use JDBC to connect to a database. Ensure
you have the required JDBC driver in your WEB-INF/lib folder.

•JDBC Setup:
•Create a DataSource in your web.xml or use a connection pool (like Apache Commons DBCP or C3P0).
•Write a DAO (Data Access Object) class to interact with the database
Example DBConnection.java (using JDBC):

• import java.sql.*;
public class DBConnection {
• public static Connection getConnection() {
• try {
• Class.forName("com.mysql.cj.jdbc.Driver");
• return DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "username", "password");
• } catch (Exception e) {
• e.printStackTrace();
• return null;
• }
• }
• }
• Action Class with Database Connectivity: In Struts,
actions are used to process user requests. You can
interact with the database from the action class.
• Example LoginAction.java:
• import org.apache.struts.action.Action;
• import org.apache.struts.action.ActionForm;
• import org.apache.struts.action.ActionMapping;
• import org.apache.struts.action.ActionForward;

• public class LoginAction extends Action {


• public ActionForward execute(ActionMapping mapping, ActionForm form,
• HttpServletRequest request, HttpServletResponse response) throws Exception {
• LoginForm loginForm = (LoginForm) form;
• String username = loginForm.getUsername();
• String password = loginForm.getPassword();

• // Connect to the database and validate credentials


• Connection conn = DBConnection.getConnection();
• String sql = "SELECT * FROM users WHERE username=? AND password=?";
• PreparedStatement ps = conn.prepareStatement(sql);
• ps.setString(1, username);
• ps.setString(2, password);
• ResultSet rs = ps.executeQuery();
if (rs.next()) {
• return mapping.findForward("success");
• } else {
• return mapping.findForward("failure");
• }
• }
• }
• JSP Files for User Interface:- Create JSP pages for displaying forms and results. For example, a login form
(login.jsp) .
• Example login.jsp:
• <html>
• <body>
• <h2>Login</h2>
• <form action="login.do" method="post">
• <input type="text" name="username" placeholder="Username" />
• <input type="password" name="password" placeholder="Password" />
• <input type="submit" value="Login" />
• </form>
• </body>
• </html>
• Configure web.xml:- Define servlet mappings and other configurations in web.xml
• Example web.xml: <web-app>
• <servlet>
• <servlet-name>struts</servlet-name>
• <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
• <init-param>
• <param-name>config</param-name>
• <param-value>/WEB-INF/struts-config.xml</param-value>
• </init-param>
• <load-on-startup>1</load-on-startup>
• </servlet>
• <servlet-mapping>
• <servlet-name>struts</servlet-name>
• <url-pattern>*.do</url-pattern>
• </servlet-mapping>
• </web-app>
•Build the Application:- Use a build tool like Maven to package the application into a WAR (Web ARchive)
file, or manually package it.
Example Maven pom.xml (dependencies for Struts and JDBC):

<dependencies>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts</artifactId>
<version>1.3.10</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
</dependencies>
•Deploy the Application:- Once you've built the WAR file, deploy it to your servlet container (e.g., Tomcat).
•Copy the WAR file to the webapps directory of your Tomcat server.
•Start or restart the Tomcat server.

• Test the Application:-

•Open a browser and navigate to the deployed application (e.g., http://localhost:8080/yourapp/login.jsp).


•Test the database functionality by entering a username and password into the login form.

You might also like