Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Wednesday, March 5, 2014

How to Add & Remove Apache Tomcat and Creating New Server Instance/Wizard in Eclipse

Firstly you need to Download whatever version of Apache Tomcat you want to install. Three Latest version's (6.0,7.0 & 8.0) download links we are providing here
http://tomcat.apache.org/download-60.cgi
http://tomcat.apache.org/download-70.cgi
http://tomcat.apache.org/download-80.cgi

After downloading any of above versions, install setup on your system then continue with our steps. 

We are here working with Apache Tomcat 7.0
Go-to Eclipse -> Window -> Preferences

Inside Sever click on Runtime Environments (where we have already installed Tomcat 7.0)

Removing Server :
To Remove This Tomcat Server 7.0, Select it and click on Remove button.

Adding Server :
Now we are going to add Tomcat server 7.0
click on Add button

After clicking on add button you can see New Server Runtime Environments
Click on Next Button.


Now Browse your Tomcat server installed directory or go for "Download and Install" button (if you have not installed Tomcat server on your system).for JRE you can select "Workbench default JRE"
Now click on Finish Button.Then click on Ok button.

Create a New Server Instance/Wizard:
Now we are going to work with creating a new server instance/ wizard
In Eclipse go-to  Window -> Show View -> Servers
Then Click on "new server wizard"
After clicking it, you'll able to see "Define a New Server" popup window

Keep Server's host name as "localhost", select "Tomcat v7.0 Server" as type, give Server name whatever you like to see as your server name and select Apache Tomcat v7.0 from dropdownlist of Server runtime environment.

Click on Finish and you can find your given Server name in server's window.
 

Friday, November 1, 2013

How to use Struts2 Iterator tag to get Users Details from List with Oracle 10g XE and Eclipse

In this Tutorial we are retrieving users details from oracle database table USERS which is in TEST schema. We are using Struts2 Iterator tag in jsp page to show all retrieved details from List containing data from database table by clicking hyperlink on same jsp page and sending users names first letter to Action Java Class using url Rewriting.

Iterator will iterate over a value. An iterable value can be any of java.util.Collection, java.util.Iterator. 

The following example retrieves the value of the current object on the value stack and uses it to iterate over. The <s:property/> tag prints out the current value of the iterator.

Here we are using Apache Tomcat 7.0 and Java 6 (but you can use them as other versions too available on your system).
you can also Download full code with required Jars. 

Project View in Navigator

Create a table with name USERS and here we are using TEST Schema(but you can use others too for example HR Schema)
users Table
users Table Data(showing some values)
In following example the iterator tag will retrieve value object from the ActionContext and the status attribute is used to create an IteratorStatus object, which in this example, its odd() method is used to alternate row colors:

homepage.jsp
This is page for user's input as well as output.
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="ISO-8859-1"%>  
 <%@ taglib uri="/struts-tags" prefix="s"%>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>Search Users</title>  
 <script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>  
 </head>  
 <body>  
 <s:form id="adagstatus" name="adagstatus" theme="simple" method="POST">  
 <h3>Search Users with a Click on Alphabets</h3>  
      <table>  
           <tr>  
                <td>  
                     <a href="finduser.action?id=a">A</a>  
                     <a href="finduser.action?id=B">B</a>  
                     <a href="finduser.action?id=s">S</a>  
                </td>  
           </tr>  
      </table>  
      <br>  
      <table cellpadding="0" cellspacing="0" border="1" width="100%" >  
      <thead>  
           <tr>  
                <th>Column One(Users Name)</th>  
                <th>Column Two(Users ID)</th>  
           </tr>  
      </thead>  
      <s:iterator id="lstUsers" var="usr" value="lstUsers" status="counter">  
             <s:if test="#counter.odd == true">  
             <tr>  
                <td align="center" style="background: grey;"><s:property /></td>  
                </s:if>  
                <s:else>  
                <td align="center" style="background: yellow;"><s:property /></td>  
                </tr>  
                </s:else>  
      </s:iterator>  
 </table>  
 </s:form>  
 </body>  
 </html>  

FindUser.java
This is a POJO class and it is working as action class for Struts.
 package blog.webideaworld.in;  
 import java.sql.Connection;  
 import java.sql.DriverManager;  
 import java.sql.ResultSet;  
 import java.sql.Statement;  
 import java.util.ArrayList;  
 import java.util.List;  
 import com.opensymphony.xwork2.ActionSupport;  
 public class FindUser extends ActionSupport {  
      List lstUsers = new ArrayList();  
      String id = "";  
      public String execute() {  
           if (id != null) {  
                lstUsers = finduser();  
           }  
           return SUCCESS;  
      }  
      public List finduser() {  
           List lst = new ArrayList();  
           Connection conn = null;  
           Statement stmt = null;  
           try {  
              Class.forName("oracle.jdbc.OracleDriver");  
              conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","test","test");  
              stmt = conn.createStatement();  
              ResultSet rs = stmt.executeQuery("SELECT * FROM USERS WHERE LOWER(USERNAME) LIKE LOWER('"+ id +"%')");  
              while (rs.next()) {  
                   lst.add(rs.getString(1));  
                   lst.add(rs.getString(2));  
              }  
           } catch (Exception e) {  
                System.out.println(e);  
           }  
           return lst;  
      }  
      public String getId() {  
           return id;  
      }  
      public void setId(String id) {  
           this.id = id;  
      }  
      public List getLstUsers() {  
           return lstUsers;  
      }  
      public void setLstUsers(List lstUsers) {  
           this.lstUsers = lstUsers;  
      }  
 }  

 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_3_0.xsd" id="WebApp_ID" version="3.0">  
  <display-name>finduser</display-name>  
  <welcome-file-list>  
   <welcome-file>jsp/homepage.jsp</welcome-file>  
  </welcome-file-list>  
  <filter>  
   <filter-name>struts2</filter-name>  
   <filter-class>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>  

struts.xml
This file contains information about which action class to be invoked. 
 <!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.enable.DynamicMethodInvocation" value="false" />  
      <constant name="struts.devMode" value="false" />  
      <constant name="struts.custom.i18n.resources" value="ApplicationResources" />  
      <constant name="struts.ui.theme" value="naveen" />  
      <constant name="struts.ui.templateDir" value="template" />  
      <package name="finduser" extends="struts-default">  
           <action name="finduser" class="blog.webideaworld.in.FindUser">  
                <result name="success">jsp/homepage.jsp</result>  
           </action>  
      </package>  
 </struts>  


output:
with +Sarthak Goel as Contributor

users data output

Friday, August 9, 2013

How to Configure methods in Action mappings with or without Wildcards using Struts2


Let take an example to understand methods in Action mappings

struts.xml
Here our action is mapped for same action class for two different methods, on place of execute() method we are calling takeForm() and addChart() methods on same action class for crossponding action names.
 <action name="takeForm" class="blog.webideaworld.in.takeAction" method="takeForm">  
 <result name="success">success.jsp</result>  
 <result name="failure">error.jsp</result>  
 </action>  
 <action name="addChart" class="blog.webideaworld.in.takeAction" method="addChart">  
 <result name="success">success.jsp</result>  
 <result name="failure">error.jsp</result>  
 </action>   

we can also perform above task with wildcards
struts.xml (With Wildcard)
 <action name="*" class="blog.webideaworld.in.takeAction" method="{1}">  
 <result name="success">success.jsp</result>  
 <result name="failure">error.jsp</result>  
 </action>  
The "*" in the path attribute allows the mapping to match the request URIs with same action and method name.
The part of the URI matched by the wildcard will then be substituted into various attributes of the action mapping and its action results replacing {1}.
For the rest of the request, the framework will see the action mapping and its action results containing the new values.

Thursday, August 8, 2013

Action Wildcards with Struts2

When we deal with a bigger Application we have to deal with more Actions.Wildcards can be used to combine similar mappings into one more generic mapping.

Let take an example to understand Action wildcards :

struts.xml (Without Wildcard)
Inside Action Tag Action name="takeForm" and result tag is rediecting to takeForm.jsp and for another Action Tag Action name="takeChart" and result tag is rediecting to takeChart.jsp
 <action name="takeForm>  
 <result>takeForm.jsp</result>  
 </action>  
 <action name="takeChart">  
 <result>takeChart.jsp</result>  
 </action>   
but we want to perform both actions with only one action and one result tag which is possible through wildcards.

struts.xml (With Wildcard)
 <action name="take*>  
 <result>take{1}.jsp</result>  
 </action>  

struts.xml (with multiple Wildcards)
If page names are taSomekeThing.jsp or taAnykeWhat.jsp and action name are taSomekeThing or taAnykeWhat respectively.
 <action name="ta*ke*>  
 <result>ta{1}ke{2}.jsp</result>  
 </action>  
In the action mapping and action results, the wildcard-matched values can be accessed with the token {N} where N is a number from 1 to 9 indicating which wildcard-matched value to substitute.

strut.xml ( Wildcard for Action Class)
If action name is takeEdit and action class is takeEditAction
 <action name="take*" class="blog.webideaworld.in.take{1}Action">  
 <result>success.jsp</result>  
 </action>  

The "*" in the path attribute allows the mapping to match the request URIs /takeSummer, takeWinter, or any other URI that starts with /take, however /takeSummer/bad would not be matched.
The part of the URI matched by the wildcard will then be substituted into various attributes of the action mapping and its action results replacing {1}.
For the rest of the request, the framework will see the action mapping and its action results containing the new values.

Mappings are matched against the request in the order they appear in the framework's configuration file.
If more than one pattern matches the last one wins, so less specific patterns must appear before more specific ones.
However, if the request URL can be matched against a path without any wildcards in it, no wildcard matching is performed and order is not important.
 Also, note that wildcards are not greedy, meaning they only match until the first occurrence of the following string pattern. 

For example, consider the following mapping:
struts.xml
If page names are taSomeke.jsp or taAnyke.jsp and action name are taSomeke or taAnyke respectively.
 <action name="ta*ke>  
 <result>ta{1}ke.jsp</result>  
 </action>  

This mapping would work correctly for the URI taSomethingke but not for taSomekeThingke, because the latter would turn into this configuration:

struts.xml
 <action name="taSomeke>  
 <result>taSomeke.jsp</result>  
 </action>  
Wildcard patterns can contain one or more of the following special tokens:
* Matches zero or more characters excluding the slash ('/') character.
** Matches zero or more characters including the slash ('/') character.
\character The backslash character is used as an escape sequence. Thus '\*' matches the character asterisk ('*'), and '\\' matches the character backslash ('\').

In the action mapping and action results, the wildcard-matched values can be accessed with the token {N} where N is a number from 1 to 9 indicating which wildcard-matched value to substitute.
The whole request URI can be accessed with the {0} token.

Sunday, June 9, 2013

How to Search and Replace Text in eclipse IDE with Search and Replace Option

whenever we have to replace large amount  of similar text then its takes so much our precious time to replace it manually(one by one) that's why Eclipse IDE has Search and Replace Option to save our time from searching a text.
Search & replace option makes manual process more interesting and easy so below you can see step by step way to use it. 

Step 1: Go to Search -> File
Step 2: Write Text inside Containing Text to replace it.
click on Replace button.

Step 3: screen after Replace button click.
then click ok to replace it.

Thursday, May 16, 2013

Session Tracking using SessionAware Interface with Struts2, Oracle Database and Eclipse IDE

In this Tutorial we are performing Session Tracking using SessionAware Interface and this interface is used by actions that want to access user's http session which will give them access to a Map where they can put objects that can be made available to subsequent requests.



Here we are not Performing any type of Validation so for validation part go for other Tutorials.

Project Structure in Project Explorer:

Download Struts2 Jars

Struts2 jars setting, for More Details Read How to set Struts2 Environment
Java Build Path Libraries
you can't see struts2 jar here because we directly put it inside lib folder.
Deployment Assembly
Download Oracle JDBC jars

Create a Database Table and make two rows entry in it as shown below:
Login to oracle database and create table using GUI
Register Table
Register Table Data
login.jsp
create a user Login page.
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
      pageEncoding="ISO-8859-1"%>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>welcome page</title>  
 </head >  
 <body>  
 <h4 align=right><a href=login>Login</a></h4>  
     <h5 align=right><a href=login.jsp>Home</a>&nbsp&nbsp  
     <a href=#>FeedBack</a>&nbsp&nbsp  
     <a href=#>Contact Us</a></h5><hr>  
 <center><h1>Login</h1>  
 <form action="login">  
           <table>  
                <tr>  
                     <td>UserName</td>  
                     <td><input type="text" name="uname" /></td>  
                </tr>  
                <tr>  
                     <td>Password</td>  
                     <td><input type="password" name="upass" /></td>  
                </tr>  
                </table>  
           <input type="submit" value="Login" /><br/>  
           </form></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="log" namespace="/" extends="struts-default">  
   <action name="login" class="in.blog.webideaworld.LoginAction" method="execute">  
   <result name="success">/user.jsp</result>  
   <result name="error">/login.jsp</result>  
   </action>  
   <action name="logout" class="in.blog.webideaworld.Logout" method="logout">  
   <result name="success">/login.jsp</result>  
   </action>  
   <action name="profile" class="in.blog.webideaworld.Profiledirect" method="execute">  
   <result name="success">/profile.jsp</result>  
   </action>  
   <action name="profile1" class="in.blog.webideaworld.Profiledirect" method="execute">  
   <result name="success">/update.jsp</result>  
   </action>  
   <action name="home" class="in.blog.webideaworld.Profiledirect" method="execute">  
   <result name="success">/user.jsp</result>  
   </action>  
   <action name="update" class="in.blog.webideaworld.UpdateProfile" method="execute">  
   <result name="success">/success.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>Struts2_SessionTracking</display-name>  
  <welcome-file-list>  
   <welcome-file>/login.jsp</welcome-file>  
    </welcome-file-list>  
    <filter>  
    <filter-name>struts2</filter-name>  
    <filter-class>  
      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>  

DBconn.java
 package in.blog.webideaworld.dao;  
 import java.sql.Connection;  
 import java.sql.DriverManager;  
 import java.sql.Statement;  
 public class DBconn {  
      Statement st;  
      public Statement getSt()throws Exception {  
           Class.forName("oracle.jdbc.OracleDriver");  
            Connection conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","hr","hr");  
          st=conn.createStatement();  
          return st;  
      }  
 }  

LoginAction.java
create a Action java class for Login. SessionAware interface has a setSession(Map m) method which sets the Map of session attributes in the implementing class.
 package in.blog.webideaworld;  
 import java.sql.ResultSet;  
 import java.sql.Statement;  
 import java.util.Map;  
 import in.blog.webideaworld.dao.DBconn;  
 import org.apache.struts2.interceptor.SessionAware;  
 import com.opensymphony.xwork2.ActionSupport;  
 @SuppressWarnings("serial")  
 public class LoginAction extends ActionSupport implements SessionAware {  
      private String upass;  
      private String uname;  
      Map m;  
      public String getUpass() {  
           return upass;  
      }  
      public void setUpass(String upass) {  
           this.upass = upass;  
      }  
      public String getUname() {  
           return uname;  
      }  
      public void setUname(String uname) {  
           this.uname = uname;  
      }  
      public void setSession(Map m)  
      {  
           this.m=m;  
      }  
       public String execute() throws Exception{  
        try{  
            Statement st=new DBconn().getSt();  
            ResultSet rs=st.executeQuery("select * from register where uname='"+uname+"' and upass='"+upass+"'");  
            if(rs.next())  
            {    
                 m.put("id", rs.getInt(1));  
                 m.put("uname",rs.getString(2));  
                   m.put("upass", rs.getString(3));  
                 return SUCCESS;  
            }  
           }  
           catch (Exception e) {}  
          return ERROR;  
      }  
      }  

user.jsp
create a user welcome page.
 <%@page import="com.opensymphony.xwork2.ActionContext"%>  
 <%@page import="in.blog.webideaworld.LoginAction"%>  
 <%@page import="java.util.Map" %>  
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="ISO-8859-1" session="false"%>  
  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>Valid page</title>  
 </head>  
 <body>  
 <h4 align=right><a href=logout.action>Logout</a></h4>  
    <h5><a href=profile.action>Profile</a>&nbsp&nbsp  
     <a href=#>FeedBack</a>&nbsp&nbsp  
     <a href=#>Contact Us</a></h5><hr>  
     <center>  
     <%   
 Map m=ActionContext.getContext().getSession();  
 String s1=(String)m.get("uname");  
 String s2=(String)m.get("upass");  
 if(s1==null && s2==null){  
   response.sendRedirect("notvalid.jsp");  
   }  
 %>   
 --------Welcome to WebIdeaWorld---------<br/>  
 Hello: <%=s1 %>  
 </center>  
 </body>  
 </html>  

notvalid.jsp
create a page for Person not Authorized.
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="ISO-8859-1"%>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>Not Valid User</title>  
 </head>  
 <body>  
 <h4 align=right><a href=login>Login</a></h4>  
     <h5 align=right><a href=login.jsp>Home</a>&nbsp&nbsp  
     <a href=#>FeedBack</a>&nbsp&nbsp  
     <a href=#>Contact Us</a></h5><hr>  
     <center>  
 You are not Authorized Person to this Website.</center>  
 </body>  
 </html>  

Profiledirect.java
create a setSession() method to make session object available to subsequent requests.Evey time when there is a request for session objects you need to pass it through setSession() method.
 package in.blog.webideaworld;  
 import java.util.Map;  
 import org.apache.struts2.interceptor.SessionAware;  
 import com.opensymphony.xwork2.ActionSupport;  
 public class Profiledirect extends ActionSupport implements SessionAware {  
      Map m;  
      public void setSession(Map m)  
      {  
           this.m=m;  
      }  
      public String execute() throws Exception{  
           return SUCCESS;  
      }  
 }  

profile.jsp
create a user's profile page.
 <%@page import="java.sql.*"%>  
 <%@page import="com.opensymphony.xwork2.ActionContext"%>  
 <%@page import="java.util.Map" %>  
 <%@page import="in.blog.webideaworld.dao.DBconn"%>  
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="ISO-8859-1" session="false"%>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>Profile</title>  
 </head>  
 <body>  
 <h4 align=right><a href=logout.action>Logout</a></h4>  
     <a href=home.action>Home</a>&nbsp&nbsp  
     <a href=profile.action>Profile</a>&nbsp&nbsp  
     <a href=#>FeedBack</a>&nbsp&nbsp  
     <a href=#>Contact Us</a></h5><hr>  
      <%        
          Map m=ActionContext.getContext().getSession();  
     String s1=(String)m.get("uname");  
     String s2=(String)m.get("upass");  
     if(s1==null && s2==null){  
     response.sendRedirect("notvalid.jsp");  
     }  
     try{  
     Statement st=new DBconn().getSt();  
     ResultSet rs=st.executeQuery("select * from register where uname='"+s1+"' and upass='"+s2+"'");  
           while(rs.next()) {  
                %>  
          <center>  
          <form action='profile1' method='post'>  
       <h1><%=rs.getString(4)%>'s Profile</h1>  
       <table><tr><td>UserName:</td><td><%=rs.getString(2)%></td></tr>  
       <tr><td>Password:</td><td><%=rs.getString(3) %></td></tr>  
       <tr><td>First Name:</td><td><%=rs.getString(4) %></td></tr>  
       <tr><td> Last Name:</td><td><%=rs.getString(5) %></td></tr>  
       </table><br/><input type='Submit' value='update'><br></form>  
       </center>  
       <%}  
     }  
     catch(Exception e){}  
       %>  
 </body>  
 </html>  

update.jsp
create a user's profile update page.
 <%@page import="java.sql.*"%>  
 <%@page import="com.opensymphony.xwork2.ActionContext"%>  
 <%@page import="java.util.Map" %>  
 <%@page import="in.blog.webideaworld.dao.DBconn"%>  
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="ISO-8859-1" session="false"%>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>Update Profile</title>  
 </head>  
 <body>  
 <h4 align=right><a href=logout.action>Logout</a></h4>  
     <a href=profile.action>Profile</a>&nbsp&nbsp  
     <a href=#>FeedBack</a>&nbsp&nbsp  
     <a href=#>Contact Us</a></h5><hr>  
     <%      
     Map m=ActionContext.getContext().getSession();  
      String s1=(String)m.get("uname");  
      String s2=(String)m.get("upass");  
      if(s1==null && s2==null){  
        response.sendRedirect("notvalid.jsp");  
        }  
     try  
     {  
       Statement st=new DBconn().getSt();  
       ResultSet rs=st.executeQuery("select * from register where uname='"+s1+"' and upass='"+s2+"'");  
       while(rs.next())  
       {out.println("<center><h1>"+rs.getString(4)+"'s Profile</h1></center>");%>  
     <center>  
     <form action="update" method="post">  
       <h1>Update your Profile</h1>  
       <table><tr><td>UserName:</td><td><input type="text" name="t1" value="<%=rs.getString(2)%>" ></td></tr>  
       <tr><td>Password:</td><td><input type="text" name="t2" value="<%=rs.getString(3)%>" ></td></tr>  
       <tr><td>Re-Type Password:</td><td><input type="text" value="<%=rs.getString(3)%>"></td></tr>  
       <tr><td>First Name:</td><td><input type="text" name="t3" value="<%=rs.getString(4)%>" ></td></tr>  
       <tr><td> Last Name:</td><td><input type="text" name="t4" value="<%=rs.getString(5)%>" ></td></tr>  
       </table>  
       *all fields are mandatory!<br>  
       <input type="Submit" value="Update" ><br>  
     </form>  
     </center>  
     <%  
        }  
     }  
     catch(Exception e){}  
 %>  
 </body>  
 </html>  

UpdateProfile.java
 package in.blog.webideaworld;  
 import java.sql.Statement;  
 import java.util.Map;  
 import in.blog.webideaworld.dao.DBconn;  
 import org.apache.struts2.interceptor.SessionAware;  
 import com.opensymphony.xwork2.ActionSupport;  
 public class UpdateProfile extends ActionSupport implements SessionAware {  
      private String t1;  
      private String t2;  
      private String t3;  
      private String t4;  
      Map m;  
      public void setSession(Map m)  
      {  
           this.m=m;  
      }  
   public String getT1() {  
           return t1;  
      }  
      public void setT1(String t1) {  
           this.t1 = t1;  
      }  
      public String getT2() {  
           return t2;  
      }  
      public void setT2(String t2) {  
           this.t2 = t2;  
      }  
      public String getT3() {  
           return t3;  
      }  
      public void setT3(String t3) {  
           this.t3 = t3;  
      }  
      public String getT4() {  
           return t4;  
      }  
      public void setT4(String t4) {  
           this.t4 = t4;  
      }  
 public String execute() throws Exception{  
           try{  
               int s1=(Integer)m.get("id");  
                  Statement st=new DBconn().getSt();  
            int i=st.executeUpdate("update register set uname='"+t1+"',upass='"+t2+"',fname='"+t3+"',lname='"+t4+"'"  
                               +"where id="+s1+"");  
            if(i!=0)  
            {  
                 m.put("uname", t1);  
                 m.put("upass", t2);  
                 return SUCCESS;  
            }  
           }  
           catch (Exception e) {}  
          return ERROR;  
      }  
 }  

success.jsp
create a user's profile successfully updated page.
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="ISO-8859-1"%>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>Success</title>  
 </head>  
 <body>  
 <h4 align=right><a href=logout.action>Logout</a></h4>  
     <a href=profile.action>Profile</a>&nbsp&nbsp  
     <a href=#>FeedBack</a>&nbsp&nbsp  
     <a href=#>Contact Us</a></h5><hr>  
     <center>  
 Your Profile's record(s) updated successfully.</center>  
 </body>  
 </html>  

Logout.java
 package in.blog.webideaworld;  
 import java.util.Map;  
 import com.opensymphony.xwork2.ActionContext;  
 import com.opensymphony.xwork2.ActionSupport;  
 public class Logout extends ActionSupport{  
      public String logout() throws Exception{  
           Map session=ActionContext.getContext().getSession();  
           session.remove("id");  
           session.remove("uname");  
           session.remove("upass");  
           return SUCCESS;  
      }  
 }  

Download Code

View in Browser: 

Login Screen


Welcome Page


User's Profile


User's Profile Update Page

 
User's Profile After Update

Saturday, May 4, 2013

AJAX validation using Struts2 Framework and XML file with Eclipse Indigo

In this tutorial we are performing Server Side Validation using AJAX validation which will lead to the page to show validation errors without reloading the page.
To perform AJAX Validation we need to use  Struts2-dojo-plugin jar in our project.

so firstly download all Required Jars Without dojo-plugin

Download only Struts2-dojo-plugin-2.3.8.jar if you have already downloaded other jars from previous tutorials
or you can also download source code which is available in the end of this tutorial that contains all jars(with dojo-plugin) including source code



Project Structure in Project Explorer:
reg_form.jsp
create a user input page. 
To work with AJAX, <sx:head> must be in the page. Don't use validate="true" in the form tag because it invokes client side validation(Javascript) before Server Side Validation(AJAX validation) but use validate="true" in the submit tag to perform AJAX validation.
 <%@ 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>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>Ajax-Registration-form</title>  
 <sx:head />  
 </head>  
 <body bgcolor="skyblue">  
      <h1>Ajax Registration Form</h1>  
      <hr>  
                  <s:form action="register.action" method="post" >  
            <s:textfield name="Name" label="Name" size="20" />  
            <s:radio name="Gender" label="Gender" list="{'Male', 'Female'}" />  
            <s:select name="Course" label="Course" list="{'Select-Option','B.Tech', 'MCA', 'MSC'}" />  
            <sx:submit align="center" validate="true" />  
         </s:form>  
 </body>  
 </html>  

success.jsp
create a user's success page.
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="ISO-8859-1"%>  
   <%@ taglib prefix="s" uri="/struts-tags"%>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>success</title>  
 </head>  
 <body bgcolor="lightblue">  
 <center><h3>  
 Hello! <s:property value="name"/></h3></center>  
 </body>  
 </html>  

ContactAction.java
create a Action java class.
 package in.blog.webideaworld;  
 import com.opensymphony.xwork2.ActionSupport;  
 @SuppressWarnings("serial")  
 public class ContactAction extends ActionSupport {  
      private String name;  
      private String gender;  
      private String course;  
      public String getName() {  
           return name;  
      }  
      public void setName(String name) {  
           this.name = name;  
      }  
      public String getGender() {  
           return gender;  
      }  
      public void setGender(String gender) {  
           this.gender = gender;  
      }  
      public String getCourse() {  
           return course;  
      }  
      public void setCourse(String course) {  
           this.course = course;  
      }  
      public String execute() throws Exception{  
           return SUCCESS;  
      }  
 }  

ContactAction-validation.xml
Create validators in XML file and the format for the validatiors xml file is <ActionClassName>-validation.xml
 <!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN"  
           "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">  
 <validators>  
      <field name="Name">  
           <field-validator type="requiredstring">  
                <message>Name is Required.</message>  
           </field-validator>  
           <field-validator type="regex">  
       <param name="expression">[a-zA-Z]{2,20}</param>  
       <message>Please enter valid name.</message>  
     </field-validator>  
      </field>  
      <field name="Gender">  
           <field-validator type="requiredstring">  
                <message>Gender is Required.</message>  
           </field-validator>  
      </field>  
      <field name="Course">  
           <field-validator type="regex">  
       <param name="expression">B.Tech|MCA|MSC</param>  
       <message>Course is required.</message>  
     </field-validator>  
      </field>  
 </validators>  

struts.xml
set result name="success" for success.jsp and name="input" for reg_form.jsp for validation messages to show up on input page.
 <?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" namespace="/" extends="struts-default">  
     <action name="register" class="in.blog.webideaworld.ContactAction" method="execute" >  
     <result name="success">success.jsp</result>  
     <result name="input">reg_form.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>Struts2_Ajax_Validate</display-name>  
  <welcome-file-list>  
     <welcome-file>reg_form.jsp</welcome-file>  
  </welcome-file-list>  
  <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>  
 </web-app>  

Download Code

View in Browser: 


Registration form:

checking validation without input values:


success page:

Popular Posts