Saturday, 5 October 2013

creating a simple struts application

Struts is a java framework used to implement the MVC  architecture more effectively.  In this post i explain some simple steps to create a java web application using the struts framework. For this demonstration i use the Netbeans IDE.

Here i am going to create a simple login validation web application. In the login page there are two fields, first one is the name field and second one is an email field. If user enter any improper contents for any of these fields then  display an error message on the same login page using struts framework. You have to follow the steps given bellow for creating this simple strut application by yourself.

Step 1:
Create a java web application with name "StrutDemo" and choose the Struts framework from the frameworks window on the netbeans ide and click finish.
Now the IDE creates the project and a welcomeStruts.jsp page will appear on the editor window of the ide. The project hierarchy  is shown bellow.
Step 2:
Create the login.jsp page. (Right click the project choose new option and select jsp. ) Name the jsp page as "login.jsp". At the top of the login.jsp page add the following tag libraries. 
 <%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>  
<%@taglib uri="http://struts.apache.org/tags-html" prefix="html" %>

Now create the following html form in the body tag of  login.jsp page. Make sure that the action of the html form is "/login".
  <html:form action="/login">  
<table>
<tr>
<td>Enter Name :</td>
<td><html:text name="LoginForm" property="name" /></td>
</tr>
<tr>
<td>Enter Email :</td>
<td><html:text name="LoginForm" property="email" /></td>
</tr>
<tr>
<html:submit value="Login" />
</tr>
</table>
</html:form>

Notice that the value provided for the name attribute in the html text tag is the name of the Struts ActionForm Bean that we are going to create in this application. Property is the name of the variables in the ActionForm Bean class.

Step 3:
Create the Struts ActionForm Bean.  Right click the project, choose new and select other. Form the categories select Struts. From Struts choose the Struts ActionFrom Bean and click next.

Provide LoginForm for class name and choose the package and click finish.

By default the IDE creates two variables on the Bean class name and number. Also there is setter and getter methods for name and number. We have to add two additional String variables email and error. The email variable is for getting the value of email from the html form and the error variable is for setting the error message when user enter wrong data on the input form in the login.jsp. Now you need to add getter and setter for email and error variables. For adding this methods just place your cursor on the variable name and press alt + insert on the keyboard and choose getter and setter. We do't need the number variable. So you may have to delete it. After doing all these above steps the LoginForm.java look like this.

LoginForm.java
 package com.myapp.struts;  
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
/**
*
* @author prabeesh
*/
public class LoginForm extends org.apache.struts.action.ActionForm {
private String name;
private String email;
private String error;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getError() {
return error;
}
public void setError() {
this.error = "<span style='color:red'>Please enter valid data for both fields</span>";
}
public String getName() {
return name;
}
public void setName(String string) {
name = string;
}
public LoginForm() {
super();
// TODO Auto-generated constructor stub
}
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if (getName() == null || getName().length() < 1) {
errors.add("name", new ActionMessage("error.name.required"));
// TODO: add 'error.name.required' key to your resources
}
return errors;
}
}

Note that we set the error message on the setError() method.
 public void setError()  
{
this.error = "<span style='color:red'>Please enter valid data for both fields</span>";
}

Step 4:
 Make the success.jsp . Right click the project choose new option and  select jsp. Name the file as success. On the same window choose  folder by click browse and select WEB-INF folder and click finish.

Now edit the success.jsp file as shown bellow.
 <%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>  
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Login Success</h1>
<p>Your Name :<bean:write name="LoginForm" property="name" /></p>
<p>Your Email :<bean:write name="LoginForm" property="email" /></p>
</body>
</html>

Don't forget to add the bean tag library at the top of success.jsp.  We print the values for name and email by using the <bean:wrie /> tag.

Step 5:
Create Struts Action class. Right click the project choose new select other and select Struts in the categories and choose Struts Action and click next.

Provide LoginAction for class name, choose the package and type /login for action path and click next.

Remove the forward slash from the Input Resource field and dis select the validate ActionForm Bean and click finish.

We are going to done the validation on the execute() method of the Action class as shown bellow.

LoginAction.java
 public class LoginAction extends org.apache.struts.action.Action {  
private static final String SUCCESS = "success";
private static final String FAILURE = "failure";
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
LoginForm loginBean = (LoginForm)form;
String name,email;
name = loginBean.getName();
email = loginBean.getEmail();
if(name==null || email==null || name.equals("")||email.indexOf("@")==-1)
{
loginBean.setError();
return mapping.findForward(FAILURE);
}
return mapping.findForward(SUCCESS);
}
}

Step 6:
Add the error message on the login.jsp page using the <bean:write /> tag. Complete source of login.jsp is given bellow.

login.jsp
 <%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>  
<%@taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<html:form action="/login">
<table>
<tr>
<td><bean:write name="LoginForm" property="error" filter="false" /></td>
</tr>
<tr>
<td>Enter Name :</td>
<td><html:text name="LoginForm" property="name" /></td>
</tr>
<tr>
<td>Enter Email :</td>
<td><html:text name="LoginForm" property="email" /></td>
</tr>
<tr>
<html:submit value="Login" />
</tr>
</table>
</html:form>
</body>
</html>

Step 7:
Open struts-config.xml right click anywhere in it from strut choose the add forward option.

Type success as Forward name, choose success.jsp in the WEB-INF folder as Resource file by clicking the browse button. Provide /login as action and click add button.

In the same way you need to add Action Forward for failure also. After adding action Forwards for both success and failure  you can see the following forward tags on the strut-config.xml file.
 <action-mappings>  
<action name="LoginForm" path="/login" scope="session" type="com.myapp.struts.LoginAction" validate="false">
<forward name="success" path="/WEB-INF/success.jsp"/>
<forward name="failure" path="/login.jsp"/>
</action>
<action path="/Welcome" forward="/welcomeStruts.jsp"/>
</action-mappings>

Step 8 :
Open the web.xml file under the WEB-INF folder. Select pages and type login.jsp for welcome files.

Step 9:
Save the project and run. You go the following outputs.


Thursday, 3 October 2013

Imagemap creation for SEO purposes

It's not a kind of doing, what you can use on each corner. But such hint could help you to diversify and enrich your assets and to gain the spreading of your source. But don't misuse - you could be just quickly abused;) Google doesn't like if you become oversmart. I'm talking about imagemaps, the links inside of imagemaps and making use of imagemaps for SEO purposes.
Read full article »

Wednesday, 2 October 2013

pass by reference in java

In java there is no pointer concepts. So pass by reference using pointer is not possible in java. In java pass by reference is achieved by passing objects as arguments. It is possible to pass objects as argument to a function in java. In this post i am going to explain how to pass an object as reference in java.
Ads by Google


For better understanding consider the code segment given bellow. 
      class TestClass  
{
String msg;
public TestClass(String msg)
{
this.msg = msg;
}
public boolean checkObject(TestClass obj)
{
if(obj.msg.equals(msg))
return true;
else
return false;
}
}
public class ObjectPassing
{
public static void main(String args[])
{
TestClass test1 = new TestClass("Apple");
TestClass test2 = new TestClass("Orange");
TestClass test3 = new TestClass("Apple");
System.out.println("test1 = test2 :"+test1.checkObject(test2));
System.out.println("test1 = test3 :"+test1.checkObject(test3));
}
}

In this example the TestClass contain a method called checkObject, which accept an object as argument. Here you can see that the type of the argument is the name of the class.
     public boolean checkObject(TestClass obj)  
{
if(obj.msg.equals(msg))
return true;
else
return false;
}

Here we check the value of the variable "msg" for the three objects test1, test2 and test3. In this method if the value of the variable "msg" corresponding  to the two objects is found to be true, then it return true otherwise false.
Here is the output of the program.



Constructor Overloading                                        Index                 

Tuesday, 1 October 2013

constructor overloading in java

Like method overloading you can also overload a constructor in java. A constructor is a special purpose class member function for initializing the objects of a class.  A constructor is overloaded on the basis of the arguments or parameters available with it.
Ads by Google


Consider the following class.
     class ConstructorTest  
{
int a,b;
public ConstructorTest()
{
a = 10;
b = 20;
System.out.println("From the default constructor a = "+a+ " and b ="+b);
}
public ConstructorTest(int a,int b)
{
this.a = a;
this.b = b;
System.out.println("From the parameterised constructor a = "+a+ " and b ="+b);
}
}


In this class you can see that there is two constructors present. One is with no arguments and other is with two integer parameters. The compiler will invoke the appropriate constructor when a compatible object initialization found.

For example the statement "ConstructorTest t1 = new ConstructorTest();" will invokes the default constructor, while the statement" ConstructorTest t2 = new ConstructorTest(30,40);" will invoke a constructor with two integer parameters.

Method overloading                                           Index                                Pass by reference                                        



Dealing with the "Keyword not provided" problem in your statistics

This article explains why the proportion of "keyword not provided" visits to most websites is increasing, and gives you options for finding out what keywords people are searching for when they reach your blog.



Why the percentage of not-provided search visits to your blog has increased

If SEO is important for your blog, and if you therefore watch the Stats > Traffic Sources tab in your Blogger dashboard or your Google Analytics results, you'll probably have seen that proportion of your search-visitors whose keyword is "not provided" has gone up a lot recently, to be more-or-less 100% of your Google search traffic.   (In the Blogger Stats tab "not provided" isn't shown - but the number of visits per keyword is now massively less than the vists from Google.)

This is no accident: Google is now witholding the keywords that people use, and (says that) this to protect your visitor's privacy. The issue has been widely discussed in sites like SearchEngineLand.

Opinions vary, but many people believe that
"Not knowing keywords has big implications if you use data about what people search for to decide how to develop your blog." [tweet this quote].

For example,   I publish listings of the contents of old (ie graphical copyright expired) song-books in a particular niche on one of my blogs.  There are far too many songs for me to load the full text or sheet music of all of them. And this is a niche with lots of competition:   there are a zillion websites distributing song-lyrics (most illegally).  But by watching the search-terms that led people to arrive at certain pages, I can identify particular songs that people were looking for and not finding anywhere else (the so called "long tail" of search keywords). If these songs are now in the public domain, I can make a dedicated page for them, and share what I know - in many cases after doing more research and pulling together information from a range of different sources.    Not knowing the keywords that people use to get to the book-listing pages would totally destroy this approach.


What you can do about it

So far I've identified three alternative options for getting data about what my visitors are searching for.

Ask for user-provided information

I've used Google Docs to make a data-collection form, and invited my visitors to use it to tell me about songs they are looking for.

The advantage is that I can ask them for richer information than just the keywords, eg where / when they remembmer it from, multiple snatches of the lyrics, what style the music is, etc.

But the disadvantage - and it's a big one - is that it only works for people who actually get to my site and then go into the other page where this form is kept, and fill in the form. I don't want to go into details - but let's just say that I haven't been run off my feet!


Get data from WebMaster Central

If you have verified your blog in Google Webmaster Tools, then the Search traffic > Search Queries tab shows the queries that have caused your blog to show up in search results pages, as well as how many times this has happened and what position, on average, you had in these pages.

This is richer information than you get from Analytics or Blogger-Stats, which only tell you about people who actually visited your blog.

But the disadvantages are that data is only kept for 90 days, and it only shows the top 2000 keywords.   Both of these are issues for me - some of my song-book contents are seasonal - if something is being looked for now, then the moment (week, month) may have passed by the time that I've noticed the trend, researched the song and written it up to a standard that I'm happy to publish. So really I want to checking the logs for nine months ago, so I can research things that are likely to be popular again next year.


Get data from AdWords

Advertising campaigns are the one place where Google is passing the search-keywords through to back-end systems. And because of this, Adwords does have data about what your visitors are searching for - provided you've set it up to collect this data. To get it up:

Firstly, sign up for an AdWords account. You probably have to deposit $10 into the account to get started - but you don't actually need to set up any advertising campaigns or spend any money after that.

Then link your AdWords account to your Google Webmaster Central account.

Once this is done, Adwords will start collecting the search-keywords for your blog. To get at the data:
  • Log in to AdWords
  • Select "All Online Campaigns,"
  • Make an empty campaign (if you haven't got one already)
  • Go to the "Dimensions" tab
  • Change "View" to "Paid & organic".

AdWords will display your stats, since you signed up and linked your account. This includes the top search terms that users got to your site with, number of clicks, number of queries and some other measures too.

I'm only just starting to assess how well this will for for my song-listing site - will update this post when I have more specific information about how well it works and whether I can get actionable results from it.


What other alternatives have you found?

Leave a comment below, and I'll expand this list as we find out more options for accessing keyword-based search traffic information.




Related Articles:

Using Google Docs to put a survey questionnaire into Blogger

Six reasons why SEO doesn't matter for your blog