Vous êtes sur la page 1sur 32

Srinivasa Reddy Challa

Struts 2.X Version 1.0

urtrainer.java@gmail.com

Enterprise:
It is a business organization; group of organizations running under a single label is called as an Enterprise.

Enterprise Application:
It is a Software application, which will be designed for an Enterprise in order to improve their business. To design Enterprise Application we have to provide the fallowing 3 logic system layers. User Interface Layer Business Processing Layer Data Storage and Access Layer The main purpose of the UIL is to improve look and feels to the Enterprise application. To accept user details in order to execute Enterprise applications. To perform client side data validations with java script functions. To prepare UIL we will use a particular logic called as presentation logic To provide presentation logic in Enterprise application development we will use the technologies like AWT, SWING, HTML, JSP, VELOCITY, Free Marker etc..

User Interface Layer:


Business Processing Layer:


It is the heart of the Enterprise applications BPL will provide very good environment to define and execute business rules and regulations required by the clients. To design BPL in Enterprise applications we will use a type of logic called business logic To provide Business logic in Enterprise applications development we will use the technologies like Servlets, Jsps, Java Beans, EJBs etc.. BPL will improve the accuracy of the Enterprise applications.

Data Storage And Access Layer:


It is bottom most layer in Enterprise applications This layer will provide a very good environment to interact with the data base in order to perform the basic data base operations like insert, update, delete etc. To design this layer in Enterprise applications development we will use a type of logic called as persistence logic. To provide persistence logic in Enterprise applications we will use the technologies like JDBC, HIBERNATE, EJBs entity beans, JPA, JTA

System Architectures:
After providing logic layers in Enterprise applications development we have to define degree of the Enterprise application, which will specify a particular tiered architecture for the enterprise application. To design Enterprise applications we will use the fallowing system architectures. 1) 1 Tier Architecture 2) 2 - Tier Architecture 3) 3 - Tier Architecture . . . N - Tier Architecture

Srinivasa Reddy Challa

Struts 2.X Version 1.0

urtrainer.java@gmail.com

1-Tier Architecture:
In general 1-Tier Architecture is suggestible for standalone applications In case of 1-Tier Architecture we have to provide all the system logic layers within a single pc, in this context single PC may provide limited number of system resources which may not be sufficient to accommodate and execute the complete Enterprise Application. In case of 1-Tier Architecture it is not possible to provide clear cut separation between the components which are used for UIL, BPL and DSAL. Due to the above reason 1-Tier Architecture may provide tightly coupled design to the Enterprise Application. 1-Tier Architecture will not provide any specific mechanism to handle multiple numbers of requests. 1-Tier Architecture will not provide component sharability

2 -Tier Architecture: In the case of 2 -Tier Architecture we have to use 2 layers of machines to design Enterprise Applications 2 -Tier Architecture is conventional architecture to design enterprise applications The best example for 2 -Tier Architecture is Client - Server Architecture. In the case of 2 -Tier Architecture tier 1 will maintain user interface layer and tier -2 will maintain BPL and DSAL. When compare the sharability tier -1 architecture 2 -Tier Architecture will improve component

In the case of 2 -Tier Architecture there is specific mechanism to handle multiple numbers of requests. In the case of 2 -Tier Architecture there is a clear cut separation between the components which are used for UIL and Components used for BPL and DSAL. In the case of 2 -Tier Architecture it is possible provide loosely coupled design Enterprise application when compare to the 1 -Tier Architecture. In the case of 2 -Tier Architecture even though if we separate UIL from BPL and DSAL still there is no clear cut separation between the components which are used for BPL and which is used for DSAL . So that, when compare to 3 -Tier Architecture 2 -Tier Architecture will provide still tightly coupled design.

Srinivasa Reddy Challa

Struts 2.X Version 1.0

urtrainer.java@gmail.com

In case of 2 -Tier Architecture we will use application server at Tier -2, which will improve server side components sharability to multiple number of clients but still 2 -Tier Architecture will not provide centralized data base access.

3 -Tier Architecture: In case of 3 Tier Architecture we can use 3 layers of missions to design and execute Enterprise Applications. In 3 Tier Architecture, tier -1 will maintain UIL; tier -2 will maintain BPL and Tier -3 will maintain DSAL. When compare to tier -1, tier -2 architectures 3 tier Architecture will provide clear cut separation between the components which are used for UIL, BPL and DSAL. Due to the above reason 3 Architecture will provide more loosely coupled design for the Enterprise Applications when compare to 1 tier and 2 tier Architectures. 3 Tier Architecture will improve both Application server and data base server components sharability.

Srinivasa Reddy Challa

Struts 2.X Version 1.0

urtrainer.java@gmail.com

To design web applications in Servlets and Jsps Sun Microsystems has provided the fallowing 2 models. 1) Model -1 Architecture 2) Model 2 Architecture Model-1 Architecture: 1) In Model-1 Architecture the JSP page will take the responsibility to pick up the request, to handle the request and to generate dynamic response to the client. 2) In Model-1 Architecture the single JSP page is taking the responsibility to control the entire web application in this case to control the entire web application the existed JSP features are not at all sufficient, there is a requirement to provide java code inside the jsp pages. But it is against to JSP technology. 3) In Model-1 Architecture we have to use JSP Technology to provide view part and controller part, which will not provide clear cut separation between the components which are used for view part and which are used for controller part, therefore Model-1 Architecture will provide tightly coupled design. 4) Model-1 Architecture also called as Page Centric Design Pattern. Also called as JSP Front. Model-2 Architecture: 1) Model 2 Web application Architecture was implemented on the basis of MVC Design Pattern. 2) In Model 2 Web applications Architecture we will use a Servlet as controller, set of jsp pages as view part and java beans, Hibernate as model part. 3) Due to above reason Model 2 Web applications Architecture will provide clear cut separation between the components which are used for controller part and the components which are used for view part. 4) So we are saying that Model 2 Web application Architecture will provide loosely coupled design. Also called as Servlet Centric approach. Struts is a Frame Work, which was designed on the basis of MODEL II Web application architecture i.e. MVC design pattern. JSF is a Frame Work, which was designed on the basis of MODEL II Web application architecture i.e. MVC design pattern.

MVC Rules and Regulations: (Design Principles) The main purpose to design MVC architecture to design Web Applications. To have a standardization for designing web applications. To have a standard flow of control while executing web applications. If you want to design web applications on the basis of MVC architecture we have to use following rules and regulations.

Srinivasa Reddy Challa

Struts 2.X Version 1.0

urtrainer.java@gmail.com

Principles: i) In MVC based web applications we have to use a Servlet as a controller and a set of JSP pages as view part, JAVA Beans components and EJB Components as a MODEL part. In this context we should not interchange the components. In MVC based web applications we have to send all the requests to the controller servlet only and we have to generate the complete response from the view part only. In this context we should not access directly a JSP Page from client.

ii)

Note: In now a days frame works are using an alternative for the servlets as controller, i.e. a Filter. Struts 1.x version has used ActionServlet, a Servlet as controller but in struts 2.x version has used FilterDispatcher, a Filter as a controller. iii) In MVC based web applications both controller and view part should not interact with the database directly, they have to interact with the database through MODEL part. In MVC based web applications controller servlet should interact with the model part to set the data only, not for the sake of getting data. View part should interact with the model part only to get the data, not for the sake of setting the data. In MVC based web applications there is no limitation for number of JSP Pages to prepare view part, but all the JSP pages should be provided without JAVA code. There are no limitations for JSP pages to prepare view part in MVC based web applications, but we should not provide page to page navigation but we should provide page-controller-page navigation.

iv)

v)

Definition of the Framework: 1) Frame work is a pre-fabricated software components that programmer can reuse, extend, share and customize to design the applications as per the developer convenience 2) Frame work is semi implemented application it will provide very good environment to design and- execute applications in simplified manner. 3) Frame work is a collection of tools and APIs to design and execute applications as per the developer customization.

Srinivasa Reddy Challa

Struts 2.X Version 1.0

urtrainer.java@gmail.com

There are two types of frame works i) Web Frame Work ii) Application Frame Work Where Web Frame Works are the frame work it will provide very good environment to design and execute web applications. Ex: STRUTS and JSF Where Application Frame Work is a frame work which will provide very good environment to design and execute any type of Enterprise Applications including web applications. Ex: SRPING Frame works. Differences between Struts 1.x and Struts 2.x version: Struts 1.x version is more API dependent but struts 2.x version is less API dependent. In Struts 1.x version testing and debugging are complex due to its more API dependent, in case of Struts 2.x version testing and debugging are simple due to its less API dependent. Struts 1.x version is heavy weight frame work because to execute Struts1.x version web applications Server has to maintain many more number of objects. Struts 2.x version is light weight because to execute Struts 2.x version web applications server has to maintain less number of objects. Struts 1.x version is not cleaner implementation of MVC but Struts 2.x version is cleaner implementation of MVC due to the availability of in built interceptors, Value Stack and model components. In case of Struts 1.x version Tag Library Could be divided into 1) HTML Tag Library 2) Bean Tag Library 3) Logic Tag Library 4) Nested Tag Library 5) Tiles Tag Library

Srinivasa Reddy Challa

Struts 2.X Version 1.0

urtrainer.java@gmail.com

But in case of Struts 2.x version Tag Library was divided into only one type i.e. Struts Tags, which was eliminated un necessary tags implementation from Struts 1.x version and adds some more new features like datetimepicker, double select, optiontranseferselect and so on. Struts 1.x version will allow up to html, jsp designing view part but struts 2.x version will allow Html, Jsp, Free marker, Velocity, OGNL (Object Graph Navigation Language) and so on as a scripting languages. In case of Struts 1.x version Annotations support is not available so that it is mandatory to use XML technology to prepare configuration file but in case of struts 2.x version Annotations Support is available to provide mapping configurations and so on so that it is optional to provide struts configuration file. Struts 1.x version was designed on the basis of J2SE, servlets, JSPs and so on. But Struts 2.x version was designed on the basis of struts 1.x version and xwork2 web frame work. The key design patterns in Struts 1.x version is MVC, Front Controller, Data Transfer Object, and so on. In struts 2.x version the key design patterns are MVC, IOC (Inverse of control), Dependency Injunction, InterfaceImpedence and so on.

Things Need in Struts 2.x version Flow: 1. 2. 3. 4. 5. 6. User Interface (view) Web.xml (deployment descriptor) FilterDispatcher (controller) Model or Action (Model) Struts.xml (configuration file) Interceptor Internal Flow of Struts 2.x version applications:

Step-0: When we start the server automatically container will recognize FilterDispatcher configuration in web.xml and perform FilterDispatcher loading, instantiation and initialization automatically as per the basic nature of the filters. As part of the FilterDispatcher initialization FilterDispatcher will make ready Action Mapper, Action Proxy and Configuration Manager to refer struts.xml.

Srinivasa Reddy Challa

Struts 2.X Version 1.0

urtrainer.java@gmail.com

Step-1: After accessing welcome page when we send a request from user form then container will pick up the request. Step-2: Up on receiving the request, container will identify FilterDispatcher is server side resource through web.xml. Step-3: Container will by-pass request to FilterDispatcher. Step-4: Up on receiving request, FilterDispatcher will identify ActionMapper, where ActionMapper will check the requirement of request, if the request is for any static resource like HTML page, CSS and so on, and then ActionMapper will handle that request. If ActionMapper identify the requirement of request is to perform an Action then ActionMapper will give the intimation to FilterDispatcher. Step-5: Up on getting intimation from ActionMapper, FilterDispatcher will invoke ActionProxy to identify the respective ActionClass and then prepare ActionInvocation. Step-6: Where ActionProxy ConfigurationManager. Step-7: After getting respective Action class name ActionProxy will pick up all the Interceptors from InterseptorsStack. will identify the respective Action name through

Srinivasa Reddy Challa

Struts 2.X Version 1.0

urtrainer.java@gmail.com

Step-8: After getting all the Interceptors, ActionProxy will prepare ActionInvocation. Here ActionInvocation will maintain sequence of Interceptors calls to provide pre processing and post processing of Acton. Note: ActionInocation will plan how to process the request through Interceptor calls. Step-9: After getting ActionInvocation, FilterDispather will send request through all the specified Interceptors, where all the Interceptors will provide their respective actions as part of the preprocessing of the Action. Step-10: After completing all the Interceptors Actions finally request will be reached to the respective action provided by the developer. When request reached to the respective Action class the FilterDispatcher will perform Action loading, Instantiation and Data Population on Action Object and request associated data population on ValueStack. After data population, FilterDispatcher will invoke respective Action method; receive result in struts.xml. Step-11: When FilterDispatcher identify the respective result page the FilterDispatcher forward request to the respective result page. Step-12: Upon receiving the request from Action JSP container will execute respective result page and bypass response to all the Interceptors in the reverse direction.

Srinivasa Reddy Challa

Struts 2.X Version 1.0

urtrainer.java@gmail.com

Step-13:

struts.xml

0
Action Mapper

Configuration Manager

4 5 8

Interceptor Stack

LoginAction

<S:form actoin=./login> Name Password


Login

web.xml

3
1 2

Filter 9 Dispatcher

Action Invocation

I1

I2

In

10

</s:form>

11
12
Success.jsp Failure.jsp
Values Stack

13

Srinivasa Reddy Challa

Struts 2.X Version 1.0

urtrainer.java@gmail.com

Application 1: Login Application: Folder Structure:

Srinivasa Reddy Challa

Struts 2.X Version 1.0

urtrainer.java@gmail.com

Loginform.jsp
<%@taglib uri="/struts-tags" prefix="s"%> <html><head><center><b><font color="red" size="7"> Login Form </font></b></center></head> <br><br><hr><br><br> <body bgcolor="lightgreen"> <center><b><font size="6" color="red"></font> <s:form action="/login" method="post"> <s:textfield name="uname" label="Name"/> <s:password name="upwd" label="Password"/> <s:submit value="Login"/> </s:form></font></b></center></body></html> Web.xml file: <web-app> <welcome-file-list> <welcome-file>loginform.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>fd</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filterclass> </filter> <filter-mapping> <filter-name>fd</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> Struts.xml file: <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <include file="struts-default.xml"/> <package name="mypack" extends="struts-default"> <action name="login" class="com.dss.LoginAction"> <result name="success">/success.jsp</result> <result name="failure">/failure.jsp</result> <result name="input">/loginform.jsp</result> </action> </package> </struts>

Srinivasa Reddy Challa

Struts 2.X Version 1.0

urtrainer.java@gmail.com

failure.jsp: <html><body bgcolor="lightyellow"> <center><b><font color="red" size="7"><br><br> Login Failure</font></b></center></body></html> success.jsp <html><body bgcolor="lightyellow"> <center><b><font color="red" size="7"> <br><br><br><br> U R Login Is Success</font></b></center></body></html> LoginAction.java: package com.dss; import com.opensymphony.xwork2.*; //import org.apache.struts2.convention.annotation.*; public class LoginAction extends ActionSupport { private String uname; private String upwd; public void setUname(String uname) { this.uname=uname; } public String getUname() { return uname; } public void setUpwd(String upwd) { this.upwd=upwd; } public String getUpwd() { return upwd; } public String execute() { if((uname.equals("srinu")) && (upwd.equals("srinu"))) return "success"; else return "failure"; } public void validate() { System.out.println("Hi from validate method"); if(getUname().length()==0) { addFieldError("uname","Name Is Required"); } if(getUpwd().length()==0) { addFieldError("upwd","Password Is Required"); } }

Srinivasa Reddy Challa

Struts 2.X Version 1.0

urtrainer.java@gmail.com

Application 2: DBConnections: Login.jsp: <%@ page contentType="text/html; charset=UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <html> <head> <title>Struts 2 - Login Application </title> </head> <body> <h2>Struts 2 - Login Application</h2> <s:form action="login" method="post"> <table> <tr><td>UserName:</td><td><s:textfield name="username" /></td></tr> <tr><td>EnterPwd:</td><td><s:password name="password" /></td></tr> <tr><td></td><td><s:select name="type" list="{'Admin','Employee'}" label="loginas" /></td></tr> <tr><td><s:submit value="Login" align="center"/></td></tr></table> </s:form> </body> </html> Web.xml: <?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>Struts2 Application</display-name> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.FilterDispatcher </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list> </web-app>

Srinivasa Reddy Challa

Struts 2.X Version 1.0

urtrainer.java@gmail.com

Struts.xml file: <?xml version="1.0" encoding="UTF-8"?> <!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" extends="struts-default"> <action name="login" class="com.cts.Action.LoginAction"> <result name="input">/login.jsp</result> <result name="fail">input.jsp</result> <result name="success1">display1.jsp</result> <result name="success2">display2.jsp</result> </action> </package> </struts> DataBaseConnection.java: package com.cts.DB; import java.sql.*; public class DataBaseConnection { Connection con=null; public Connection getConnection() throws Exception { try{ Class.forName("oracle.jdbc.driver.OracleDriver"); con=DriverManager.getConnection ("jdbc:oracle:thin:@10.241.47.160:1521:oracle","training","training"); }catch (ClassNotFoundException e) { // TODO: handle exception e.printStackTrace(); }catch (SQLException e) { // TODO: handle exception e.printStackTrace(); } return con; } }

Srinivasa Reddy Challa

Struts 2.X Version 1.0

urtrainer.java@gmail.com

LoginAction.java File:
package com.cts.Action; import com.opensymphony.xwork2.ActionSupport; import com.cts.DB.*; import java.sql.*; public class LoginAction extends ActionSupport { private String username,password,type; public String getType() { return type; } public void setType(String type) { this.type = type; } public String getPassword() { return password; } public void setPassword(String password) {this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String execute() { String result=""; ResultSet rs=null; PreparedStatement pst=null; System.out.print("I am in Execute Method of Login Action Class"); try{ DataBaseConnection db=new DataBaseConnection(); Connection con=db.getConnection(); System.out.println("Connection Created..........."); if(type.equals("Admin")) { System.out.println(username+"\t"+password); pst=con.prepareStatement("select *from admin111 where username=? and password=?"); pst.setString(1, username); pst.setString(2, password); rs=pst.executeQuery(); if(rs.next()) { result="success1";} else { result="fail";} } else if(type.equals("Employee")) { pst=con.prepareStatement("select *from emp1111 where username=? and password=?"); pst.setString(1, username); pst.setString(2, password); rs=pst.executeQuery(); if(rs.next()) { result="success2";} else { result="fail"; } }else { result="fail";} } catch (Exception e) { e.printStackTrace();} return result;} public void validate() { System.out.println("I am from Validate Method of LoginAction Class"); if(getUsername().length()==0) { addFieldError("username","Name Is Required"); } if(getPassword().length()==0) { addFieldError("password","Password Is Required"); } if(getType().length()==0) { addFieldError("type","Type Is Required"); }}}

Srinivasa Reddy Challa

Struts 2.X Version 1.0

urtrainer.java@gmail.com

Directory Structure for Application2:

Srinivasa Reddy Challa

Struts 2.X Version 1.0

urtrainer.java@gmail.com

Example for Using Properties file and JDBC CODE: Directory Structure: Application 3

Srinivasa Reddy Challa

Struts 2.X Version 1.0

urtrainer.java@gmail.com

Login.jsp:
<%@ page contentType="text/html; charset=UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <html> <head> <title>Struts 2 - Login Application </title> </head> <body> <h2>Struts 2 - Login Application</h2> <s:form action="login" method="post"> <s:textfield name="username" key="username" size="20" /> <s:password name="password" key="password" size="20" /> <s:submit value="Login" key="login" align="center" /> </s:form> <s:actionerror /> </body> </html>

Web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/webapp_2_4.xsd"> <display-name>Struts2 Application</display-name> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.FilterDispatcher </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>Login.jsp</welcome-file> </welcome-file-list> </web-app>

Struts.xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.custom.i18n.resources" value="ApplicationResources" /> <package name="default" extends="struts-default"> <action name="login" class="com.cts.Action.LoginAction"> <result name="success">Welcome.jsp</result> <result name="fail">Login.jsp</result> </action> <action name="reg" class="com.cts.Action.RegisterAction"> <result name="success">Login1.jsp</result> <result name="fail">register.jsp</result> </action> <action name="view" class="com.cts.Action.ViewUserAction"> <result name="success">viewuser.jsp</result> <result name="fail">accpetuser.jsp</result> </action> </package> </struts>

Srinivasa Reddy Challa

Struts 2.X Version 1.0

urtrainer.java@gmail.com

Welcome.jsp:
<%@ page contentType="text/html; charset=UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <html> <head> <title>Welcome</title> </head> <body> <h2>Hello, <s:property value="username" />...!</h2> </body> </html> LoginAction.java: package com.cts.Action; import com.opensymphony.xwork2.ActionSupport; import com.cts.DB.*; import java.sql.*; public class LoginAction extends ActionSupport { private String username,password; public String getPassword() {return password; } public void setPassword(String password) { this.password = password;} public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String execute() { String res="fail"; System.out.print("I am in Execute"); try{ DataBaseConnection db=new DataBaseConnection(); Connection con=db.getConnection(); System.out.println("Connection Created..........."); Statement st=con.createStatement(); String str="select * from reg_user where un='"+username+"' and pwd='"+password+"'"; System.out.println("Query : "+str); ResultSet rs=st.executeQuery(str); if(rs.next()) res="success"; else addActionError(getText("err.login")); System.out.println("uname : "+rs.getString("un")); }catch (Exception e) { e.printStackTrace(); } System.out.println("Result : "+res+" Username : "+username); return res; } } DataBaseConnection.java: package com.cts.DB; import java.sql.*; public class DataBaseConnection { Connection con; public Connection getConnection() throws Exception { System.out.print("Enter to Database config"); Class.forName("oracle.jdbc.driver.OracleDriver"); System.out.print("Connection Establishedd....."); con=DriverManager.getConnection("jdbc:oracle:thin:@ctsinhydvorac.cts.com:1521:oracle","tr aining","training"); System.out.print("Connection Establishedd....."); return con; } }

Srinivasa Reddy Challa

Struts 2.X Version 1.0

urtrainer.java@gmail.com

Register.jsp: <%@ page contentType="text/html; charset=UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <s:form action="reg" method="post"> <h2>Register Page</h2> <s:textfield name="username" key="username" size="20" /> <s:password name="password" key="password" size="20" /> <s:submit value="Submit" key="reg" align="center" /> </s:form> <s:actionerror /> ApplicationResources.properties username= User Name password= Password fn= First Name ln= Last Name dob= Date of Birth addr= Address login= Login reg= Register view= View User err.login= <font color=red>Invalid User Name or Password</font> err.reg= <font color=red>User Not Register</font> err.view= <font color=red>Invalid User Name</font> RegisterAction.java: package com.cts.Action; import com.opensymphony.xwork2.ActionSupport; import com.cts.DB.*; import java.sql.*; @SuppressWarnings("serial") public class RegisterAction extends ActionSupport { private String username,password; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String execute() { String res="fail"; System.out.println("I am in Register Execute: "+username+" "+password); try{ DataBaseConnection db=new DataBaseConnection(); Connection con=db.getConnection(); System.out.println("Register Connection Created..........."); Statement st=con.createStatement(); String str="insert into admin values('"+username+"','"+password+"')"; System.out.println("Query : "+str); int i=st.executeUpdate(str); if(i!=0) res="success"; else addActionError(getText("err.reg")); }catch (Exception e) { e.printStackTrace(); } System.out.println("Result : "+res+" Username : "+username); return res; } }

Srinivasa Reddy Challa

Struts 2.X Version 1.0

urtrainer.java@gmail.com

Login1.jsp: <%@ page contentType="text/html; charset=UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <html> <head> <title>Welcome</title> </head> <body> <h2>Hello, <s:property value="username" />...! added Successfully</h2> </body> </html> Acceptuser.jsp: <%@ page contentType="text/html; charset=UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <html> <head> <title>Struts 2 - Application </title> </head> <body> <h2>View User Page</h2> <s:form action="view" method="post"> <s:label/> <s:textfield name="username" key="username" size="20" /> <%-- <s:hidden name="fn" /> <s:hidden name="ln" /> <s:hidden name="dob" /> <s:hidden name="addr" /> --%> <s:submit key="view" align="center" /> </s:form> <s:actionerror /> </body> </html> ViewUserAction.java: package com.cts.Action; import com.opensymphony.xwork2.ActionSupport; import com.cts.DB.*; import java.sql.*; @SuppressWarnings("serial") public class ViewUserAction extends ActionSupport { private String username,fn,ln,dob,addr; public String getFn() { System.out.println("fn : "+fn); return fn; } public void setFn(String fn) { System.out.println("fn : "+fn); this.fn = fn; } public String getLn() { System.out.println("ln : "+ln); return ln; } public void setLn(String ln) { System.out.println("ln : "+ln); this.ln = ln; } public String getDob() { System.out.println("dob : "+dob); return dob; }

Srinivasa Reddy Challa

Struts 2.X Version 1.0

urtrainer.java@gmail.com

public void setDob(String dob) { System.out.println("don : "+dob); this.dob = dob; } public String getAddr() { System.out.println("addr : "+addr); return addr; } public void setAddr(String addr) { System.out.println("addr : "+addr); this.addr = addr; } public String getUsername() { System.out.println("UN : "+username); return username; } public void setUsername(String username) { System.out.println("UN : "+username); this.username = username; } public String execute() { String res="fail"; System.out.print("I am in Execute"); try{ DataBaseConnection db=new DataBaseConnection(); Connection con=db.getConnection(); System.out.println("Connection Created..........."); Statement st=con.createStatement(); String str="select * from reg_user1 where fn='"+username+"'"; System.out.println("Query : "+str); ResultSet rs=st.executeQuery(str); if(rs.next()) { fn=rs.getString("fn"); ln=rs.getString("ln"); dob=rs.getString("dob"); addr=rs.getString("addar"); res="success"; } else{addActionError(getText("err.view")); System.out.println("uname : "+rs.getString("un"));} System.out.println("Result : "+res+" Username : "+username); }catch (Exception e) { e.printStackTrace();}return res;}} Viewuser.jsp: <%@ page contentType="text/html; charset=UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <html> <head> <title>Welcome</title> </head> <body> <h2>Hello, <s:property value="username" />...!</h2> <table> <tr><th><s:text name="fn"/> </th><td><s:property value="fn" /></td> <tr><th><s:text name="ln"/> </th><td><s:property value="ln" /></td> <tr><th><s:text name="dob"/> </th><td><s:property value="dob" /></td> <tr><th><s:text name="addr"/> </th><td><s:property value="addr" /></td> </table> </body> </html>

</tr> </tr> </tr> </tr>

Srinivasa Reddy Challa

Struts 2.X Version 1.0

urtrainer.java@gmail.com

Example Application How to use Interceptors in Struts 2.X:


We are having 2 types of interceptors one is predefined Interceptors and Second one is User Defined Interceptors and we have to configure these in struts.xml file.

Directory Structure:

Srinivasa Reddy Challa

Struts 2.X Version 1.0

urtrainer.java@gmail.com

Add User Defined Interceptor in Src Folder and configure that in struts.xml file. MyInterceptor.java:
package com.cts.Action; import java.util.*; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; public class MyInterceptor extends AbstractInterceptor { public String intercept(ActionInvocation invocation)throws Exception{ /* let us do some pre-processing */ String output = "Pre-Processing"; System.out.println(output); /* let us call action or next interceptor */ String result = invocation.invoke(); /* let us do some post-processing */ output = "Post-Processing"; System.out.println(output); return result; } } Do changes in struts.xml file: <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.custom.i18n.resources" value="ApplicationResources" /> <package name="default" extends="struts-default"> <interceptors> <interceptor name="myinterceptor" class="com.cts.Action.MyInterceptor" /> </interceptors> <action name="login" class="com.cts.Action.LoginAction"> <interceptor-ref name="params"/> <interceptor-ref name="timer" /> <interceptor-ref name="myinterceptor" /> <result name="success">Welcome.jsp</result> <result name="fail">Login.jsp</result> </action> <action name="reg" class="com.cts.Action.RegisterAction"> <result name="success">Login1.jsp</result> <result name="fail">register.jsp</result> </action> <action name="view" class="com.cts.Action.ViewUserAction"> <result name="success">viewuser.jsp</result> <result name="fail">accpetuser.jsp</result> </action> </package> </struts>

Remaining resources are as usual and they dont change. Make use of above application. We are having around 10 to 20 predefined interceptors in Struts 2.X Frame work. Please go through the Struts 2.X documentation from Apache foundation.

Srinivasa Reddy Challa

Struts 2.X Version 1.0

urtrainer.java@gmail.com

Output on the Server Console:


INFO: Server startup in 5543 ms Pre-Processing I am in ExecuteEnter to Database configConnection Establishedd.....Connection Establishedd.....Connection Created........... Query : select * from reg_user where un='cnu' and pwd='cnu' uname : cnu Result : success Username : cnu Post-Processing Jan 5, 2013 1:46:55 PM com.opensymphony.xwork2.util.logging.commons.CommonsLogger info INFO: Executed action [//login!execute] took 785 ms.

Final Struts 2.X Architecture:

http://www.tutorialspoint.com/struts_2/index.htm refer this site for more info

Srinivasa Reddy Challa

Struts 2.X Version 1.0

urtrainer.java@gmail.com

Struts DBA APPLICATION: SQL> create table srinusame as select empno,ename from emp; Table created. SQL> select *from srinusame; EMPNO ---------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 EMPNO ---------7900 7902 7934 ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS ENAME ---------JAMES FORD MILLER

14 rows selected. Find the executable war file in the Folder I am attached... Last Remaining Topic as a Basic Struts 2 tags and Tiles framework just go through the Tutorials point and get familiar with the Struts 2 TAGS and Tiles Framework. IN Examples given above already I have covered Validation framework in Struts 2.X. We will do validations by using validate method in Action class or we are having one more alternate by using XML File also. With Regards Srinivasa Reddy Challa CATP TRAINER (COGNIZANT) 9603585810 Urtrainer.java@gmail.com

Srinivasa Reddy Challa

Struts 2.X Version 1.0

urtrainer.java@gmail.com

Struts 2.X Form Tags: Sample Program for Struts tags. Along with Struts 2.X regularly used jar files we have to use struts2dojo-plugin-2.1.2.jar. I guess some of the dojo tags were deprecated recently like datetimepicker time etc...

Form.jsp

<%@taglib uri="/struts-tags" prefix="s"%> <%@ taglib prefix="sx" uri="/struts-dojo-tags"%> <html> <head> <%-- <s:head theme="ajax"/> --%> <s:head /> <sx:head /> <font color="blue" size="6"><center><b> Registration Form </center></b></font> </head><br><hr> <body bgcolor="lightgreen"> <center><b> <s:form action="tags"> <s:textfield name="uname" label="Name"/> <s:password name="upwd" label="Password"/> <s:checkboxlist name="uqual" label="Qualification" list="{'BSC','MCA','PHD'}"/> <s:radio name="ugen" label="Gender" list="{'Male','Female'}"/>

Srinivasa Reddy Challa

Struts 2.X Version 1.0

urtrainer.java@gmail.com

<s:select name="utech" list="{'C','C++','JAVA'}" label="Technologies" size="5" multiple="true"/> <s:select name="prof" label="Profession" list="{'Student','Employee','Former','Business'}"/> <%-- <s:doubleselect name="country" label="Country & City" doubleName="city" headerKey="-1" headerValue="Select Country" list="{'India','America'}" doubleList="top=='India'?{'Hyderabad','Chennai','Banglore','Pune','Mumbai' }:{'California','Newyork','Indiana police','Chikago'}"/> --%> <sx:datetimepicker name="dob" label="Date of Birth" /> <%-- <sx:datetimepicker label="Time Of Birth" name="tob" type="time"/> -%> <s:optiontransferselect label="Servers" name="serv" doubleName="servers" list="{'Tomcat','Weblogic','Websphere','Jboss'}" doubleList="{}" size="10" doubleSize="10"/> <s:submit value="Register"/></s:form></body></html> UserAction.java: public class UserAction { private String uname; private String upwd; private String[] uqual; private String ugen;private String[] utech;private String prof; //private String country; //private String city; private String dob;//private String tob; private String serv; public String getServ() {return serv;} public void setServ(String serv) {this.serv = serv;} public void setUname(String uname){this.uname=uname;} public String getUname(){return uname;} public void setUpwd(String upwd){this.upwd=upwd;} public String getUpwd(){return upwd;} public void setUqual(String[] uqual){this.uqual=uqual;} public String[] getUqual(){return uqual;} public void setUgen(String ugen){this.ugen=ugen;} public String getUgen(){return ugen;} public void setUtech(String[] utech){this.utech=utech;} public String[] getUtech(){return utech;} public void setProf(String prof){this.prof=prof;} public String getProf(){return prof;} /*public void setCountry(String country){this.country=country;} public String getCountry(){return country;} public void setCity(String city){this.city=city;} public String getCity(){return city;} */ public void setDob(String dob){this.dob=dob;} public String getDob(){return dob;} /*public void setTob(String tob){this.tob=tob;} public String getTob(){return tob;}*/ public String execute()throws Exception{return "display";}} Display.jsp: <%@taglib uri="/struts-tags" prefix="s"%> <html> <body bgcolor="lightyellow">

Srinivasa Reddy Challa

Struts 2.X Version 1.0

urtrainer.java@gmail.com

<center><br> <table width="30%" height="30%" bgcolor="lightgreen"> <tr><td colspan="2"><font size="6" color="red"> <center><b><u>Registration Details</u></b></center></font></td></tr> <tr><td>Name:</td><td><s:property value="uname"/></td></tr> <tr><td>Password:</td><td><s:property value="upwd"/></td></tr> <tr><td>Qualifications:</td><td><s:iterator status="stat" value="uqual"> <s:property/></s:iterator></td></tr> <tr><td>Gender:</td><td><s:property value="ugen"/></td></tr> <tr><td>Technologies:</td><td><s:iterator status="stat" value="utech"> <s:property/></s:iterator></td></tr> <tr><td>Proffession:</td><td><s:property value="prof"/></td></tr> <%-- <tr><td>City:</td><td><s:property value="city"/></td></tr> <tr><td>Country:</td><td><s:property value="country"/></td></tr> --%> <tr><td>Date Of Birth:</td><td><s:property value="dob"/></td></tr> <%--<tr><td>Time Of Birth:</td><td><s:property value="tob"/></td></tr> -%> <tr><td>Servers:</td><td><s:property value="serv"/></td></tr> </table></font></center></body></html> Struts.xml: <?xml version="1.0" encoding="UTF-8" ?> <!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" extends="struts-default"> <action name="tags" class="UserAction"> <result name="display">/display.jsp</result> </action> </package> </struts> Web.xml: <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>StrutsDBAppAndFormTags</display-name> <filter> <filter-name>struts2</filter-name> <filterclass>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter </filter-class></filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>

Srinivasa Reddy Challa

Struts 2.X Version 1.0

urtrainer.java@gmail.com

Email.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="s" uri="/struts-tags"%> <%@ taglib prefix="sx" uri="/struts-dojo-tags"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html><head><s:head/><sx:head /><title>Hello World</title></head> <body bgcolor="lightgreen"> <s:div>Email Form</s:div> <s:text name="Please fill in the form below:" /> <s:form action="hello" method="post" enctype="multipart/form-data"> <s:hidden name="secret" value="abracadabra"/> <s:textfield key="email.from" name="from" /> <s:password key="email.password" name="password" /> <s:textfield key="email.to" name="to" /> <s:textfield key="email.subject" name="subject" /> <s:textarea key="email.body" name="email.body" /> <s:label for="attachment" value="Attachment"/> <s:file name="attachment" accept="text/html,text/plain" /> <s:radio label="Gender" name="gender" list="{'male','female'}" /> <s:checkboxlist label="Hobbies" name="hobbies" list="{'sports','tv','shopping'}" /> <s:select name="username" label="Username" list="{'Mike','John','Smith'}" /> <s:select label="Company Office" name="mySelection" value="%{'America'}" list="%{#{'America':'America'}}"> <s:optgroup label="Asia" list="%{#{'India':'India','China':'China'}}" /> <s:optgroup label="Europe" list="%{#{'UK':'UK','Sweden':'Sweden','Italy':'Italy'}}" /> </s:select> <s:combobox label="My Sign" name="mySign" list="#{'aries':'aries','capricorn':'capricorn'}"headerKey="-1" headerValue="--- Please Select ---" emptyOption="true" value="capricorn" /> <%-<s:doubleselect label="Occupation" name="occupation" list="{'Technical','Other'}" doubleName="occupations2" doubleList="top == 'Technical' ? {'I.T', 'Hardware'} : {'Accounting', 'H.R'}" /> --%> <sx:autocompleter label="Favourite Colour" list="{'red','green','blue'}" /><br /> <sx:datetimepicker name="deliverydate" label="Delivery Date" displayFormat="dd/MM/yyyy" /> <br /> <sx:tabbedpanel id="tabContainer"> <sx:div label="Hi">Hi</sx:div> <sx:div label="Hello">Hello</sx:div> </sx:tabbedpanel> <sx:datetimepicker name="dob" label="Date of Birth" /> <s:optiontransferselect label="Servers" name="serv" doubleName="servers" list="{'Tomcat','Weblogic','Websphere','Jboss'}" doubleList="{}" size="10" doubleSize="10"/> <s:token /> <s:submit key="submit" value="Submit"/> </s:form></body></html>

Srinivasa Reddy Challa

Struts 2.X Version 1.0

urtrainer.java@gmail.com

Vous aimerez peut-être aussi