Showing posts with label Struts2. Show all posts
Showing posts with label Struts2. Show all posts

Friday, 10 July 2015

Struts 2 Fetching all records of a table

To fetch all the records, we have stored all the records in a collection (using List), and displaying the data of the collection using the iterator tag of struts2.
Here, we assume that you have a table in oracle database named user3333 that contains records. The table query is:
  1. CREATE TABLE  "USER3333"   
  2.    (    "ID" NUMBER,   
  3.     "NAME" VARCHAR2(4000),   
  4.     "PASSWORD" VARCHAR2(4000),   
  5.     "EMAIL" VARCHAR2(4000),   
  6.      CONSTRAINT "USER3333_PK" PRIMARY KEY ("ID") ENABLE  
  7.    )  

Example to fetch all the records of the table

In this example, we are creating 5 pages :
  1. index.jsp invoking action.
  2. Register.java for storing data of the table in the collection.
  3. User.java for representing table.
  4. struts.xml for defining the action and result.
  5. welcome.jsp for the view component to display records.

1) Create index.jsp for invoking action (optional)

This jsp page creates a link to invoke the action. But you can direct invoke the action class.
index.jsp
  1. <a href="viewrecords">View All Records</a>  

2) Create the action class

This action class contains ArrayList object as the datamember and execute method.
Register.java
  1. package com.javatpoint;  
  2. import java.sql.*;  
  3. import java.util.ArrayList;  
  4.   
  5. public class FetchRecords {  
  6. ArrayList<User> list=new ArrayList<User>();  
  7.   
  8. public ArrayList<User> getList() {  
  9.     return list;  
  10. }  
  11. public void setList(ArrayList<User> list) {  
  12.     this.list = list;  
  13. }  
  14. public String execute(){  
  15.  try{  
  16.   Class.forName("oracle.jdbc.driver.OracleDriver");  
  17.   Connection con=DriverManager.getConnection(  
  18.     "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
  19.               
  20.   PreparedStatement ps=con.prepareStatement("select * from user3333");  
  21.   ResultSet rs=ps.executeQuery();  
  22.   
  23.   while(rs.next()){  
  24.    User user=new User();  
  25.    user.setId(rs.getInt(1));  
  26.    user.setName(rs.getString(2));  
  27.    user.setPassword(rs.getString(3));  
  28.    user.setEmail(rs.getString(4));  
  29.    list.add(user);  
  30.   }  
  31.   
  32.   con.close();  
  33.  }catch(Exception e){e.printStackTrace();}  
  34.           
  35.  return "success";  
  36. }  
  37. }  

3) Create the class to represent table

This is the simple bean class containing 4 fields.
User.java
  1. package com.javatpoint;  
  2.   
  3. public class User {  
  4. private int id;  
  5. private String name,password,email;  
  6. //getters and setters  
  7. }  

4) Create struts.xml

This xml file defines action and result.
struts.xml
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD   
  3. Struts Configuration 2.1//EN"   
  4. "http://struts.apache.org/dtds/struts-2.1.dtd">  
  5. <struts>  
  6.   
  7. <package name="anbc" extends="struts-default">  
  8. <action name="viewrecords" class="com.javatpoint.FetchRecords">  
  9. <result name="success">displayrecords.jsp</result>  
  10. </action>  
  11. </package>  
  12.   
  13. </struts>      

5) Create view component

It is the simple jsp file displaying the information of the user.
welcome.jsp
  1. <%@ taglib uri="/struts-tags" prefix="s" %>  
  2.   
  3. <h3>All Records:</h3>  
  4. <s:iterator  value="list">  
  5. <fieldset>  
  6. <s:property value="id"/><br/>  
  7. <s:property value="name"/><br/>  
  8. <s:property value="password"/><br/>  
  9. <s:property value="email"/><br/>  
  10. </fieldset>  
  11. </s:iterator>  

Struts 2 Login and Logout Example

Before creating the login and logout application using struts 2, you must clear the concepts of aware interfaces in struts 2. In this example, we have used the SessionAware interface to put the information in the session scope and ServletActionContext class to get the information from the session scope.
This example contains three links loginlogout and profile. The end user cannot click on the profile page until he/she is logged in. After getting logged in, he/she may go the profile page. If the end user clicks on the logout page, he will not be able to access the profile page.
Here, we assume that you have a table in oracle database named user3333 that contains records. The table query is:
  1. CREATE TABLE  "USER3333"   
  2.    (    "ID" NUMBER,   
  3.     "NAME" VARCHAR2(4000),   
  4.     "PASSWORD" VARCHAR2(4000),   
  5.     "EMAIL" VARCHAR2(4000),   
  6.      CONSTRAINT "USER3333_PK" PRIMARY KEY ("ID") ENABLE  
  7.    )  
  8. /  

Example of creating login and logout application using struts 2

In this example, we are need following pages
  1. index.jsp for providing links to the login, logout and profile.
  2. struts.xml for defining the result and action.
  3. Login.java for defining login and logout logic.
  4. LoginDao.java for matching username and password in the database.
  5. Profile.java for checking if the user is logged in or not.
  6. View components for the displaying results.

1) Create index.jsp for input

This jsp page creates three links for login, logout and profile.
index.jsp
  1. <hr/>  
  2. <a href="login">login</a>|  
  3. <a href="logout">logout</a>|  
  4. <a href="profile">profile</a>  

2) Define action and result in struts.xml

This xml file defines one package and 4 actions. Each action defines at least one result page.
For the loginprocess and logout actions, we are using the same action class but there invocation methods are different.
struts.xml
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD  
  3.  Struts Configuration 2.1//EN"   
  4. "http://struts.apache.org/dtds/struts-2.1.dtd">  
  5. <struts>  
  6. <package name="abc" extends="struts-default">  
  7.   
  8. <action name="login">  
  9. <result >login.jsp</result>  
  10. </action>  
  11.   
  12. <action name="loginprocess" class="com.javatpoint.Login">  
  13. <result name="success"  >loginsuccess.jsp</result>  
  14. <result name="error" >loginerror.jsp</result>  
  15. </action>  
  16.   
  17. <action name="logout" class="com.javatpoint.Login" method="logout">  
  18. <result name="success" >logoutsuccess.jsp</result>  
  19. </action>  
  20.   
  21. <action name="profile" class="com.javatpoint.Profile">  
  22. <result name="success" >profilesuccess.jsp</result>  
  23. <result name="error" >profileerror.jsp</result>  
  24. </action>  
  25.   
  26. </package>  
  27. </struts>      

3) Create the action class for login and logout

This action class implements the SessionAware interface and overrides the setSession method to store the information in the session scope.
For logout, we are simply calling the invalidate() method of SessionMap.
Login.java
  1. package com.javatpoint;  
  2.   
  3. import java.util.Map;  
  4. import org.apache.struts2.dispatcher.SessionMap;  
  5. import org.apache.struts2.interceptor.SessionAware;  
  6.   
  7. public class Login implements SessionAware{  
  8. private String username,userpass;  
  9. SessionMap<String,String> sessionmap;  
  10.   
  11. public String getUsername() {  
  12.     return username;  
  13. }  
  14.   
  15. public void setUsername(String username) {  
  16.     this.username = username;  
  17. }  
  18.   
  19. public String getUserpass() {  
  20.     return userpass;  
  21. }  
  22.   
  23. public void setUserpass(String userpass) {  
  24.     this.userpass = userpass;  
  25. }  
  26.   
  27. public String execute(){  
  28.     if(LoginDao.validate(username, userpass)){  
  29.         return "success";  
  30.     }  
  31.     else{  
  32.         return "error";  
  33.     }  
  34. }  
  35.   
  36. public void setSession(Map map) {  
  37.     sessionmap=(SessionMap)map;  
  38.     sessionmap.put("login","true");  
  39. }  
  40.   
  41. public String logout(){  
  42.     sessionmap.invalidate();  
  43.     return "success";  
  44. }  
  45.   
  46. }  

4) Create the Dao class to authenticate user

This class simply validates the user from the table stored in the oracle database.
LoginDao.java
  1. package com.javatpoint;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.DriverManager;  
  5. import java.sql.PreparedStatement;  
  6. import java.sql.ResultSet;  
  7.   
  8. public class LoginDao {  
  9.   
  10. public static boolean validate(String username,String userpass){  
  11.  boolean status=false;  
  12.   try{  
  13.    Class.forName("oracle.jdbc.driver.OracleDriver");  
  14.    Connection con=DriverManager.getConnection(  
  15.    "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
  16.      
  17.    PreparedStatement ps=con.prepareStatement(  
  18.      "select * from user3333 where name=? and password=?");  
  19.    ps.setString(1,username);  
  20.    ps.setString(2,userpass);  
  21.    ResultSet rs=ps.executeQuery();  
  22.    status=rs.next();  
  23.   }catch(Exception e){e.printStackTrace();}  
  24.  return status;  
  25. }  
  26. }  

5) Create the Profile class

This class gets the information from the session scope, if any information is found in the session scope with login name, it returns success otherwise false.
Profile.java
  1. package com.javatpoint;  
  2.   
  3. import javax.servlet.http.HttpServletRequest;  
  4. import javax.servlet.http.HttpSession;  
  5. import org.apache.struts2.ServletActionContext;  
  6.   
  7. public class Profile {  
  8.   
  9. public String execute(){  
  10. HttpServletRequest request=ServletActionContext.getRequest();  
  11. HttpSession session=request.getSession();  
  12.   
  13. String s=(String)session.getAttribute("login");  
  14. if(s!=null && !s.equals("")){  
  15.     return "success";  
  16. }  
  17. else{  
  18.     return "error";  
  19. }  
  20.   
  21. }  
  22. }  

6) Create view components

There are many view components:
  • login.jsp
  • loginsuccess.jsp
  • loginerror.jsp
  • logoutsuccess.jsp
  • profilesuccess.jsp
  • profileerror.jsp

view components for login

login.jsp
This page creates the login form.
  1. <jsp:include page="index.jsp"></jsp:include>  
  2. <hr/>  
  3. <%@ taglib uri="/struts-tags" prefix="s" %>  
  4.   
  5. <s:form action="loginprocess">  
  6. <s:textfield name="username" label="Name"></s:textfield>  
  7. <s:password name="userpass" label="Password"></s:password>  
  8. <s:submit value="login"></s:submit>  
  9. </s:form>  
loginsuccess.jsp
This page prints the welcome message with the username.
  1. <jsp:include page="index.jsp"></jsp:include>  
  2. <hr/>  
  3. <%@ taglib uri="/struts-tags" prefix="s" %>  
  4.   
  5. <br/>Welcome, <s:property value="username"/>  
loginerror.jsp
This page displays the error message.
  1. Sorry username or password error!  
  2. <jsp:include page="login.jsp"></jsp:include>  

view components for logout

logoutsuccess.jsp
This page simply displays the successfully logged out message.
  1. <jsp:include page="index.jsp"></jsp:include>  
  2. <hr/>  
  3. You are successfully logged out!  

view components for profile

profilesuccess.jsp
This page prints the welcome to profile message.
  1. <jsp:include page="index.jsp"></jsp:include>  
  2. <hr/>  
  3. <br/>Welcome to profile  
profileerror.jsp
This page prints the message to login first and includes the login.jsp page.
  1. Please login first to see profile  
  2. <jsp:include page="login.jsp"></jsp:include>