Happy 1 year Anniversary to ELTP-19

Date : 7th January 2009
Event : ELTP-19 first Anniversary
Place : KFC at Petronas Equine
Web Gallery : Picasa Picture Gallery

7th January marked as the first day in the 2009 calendar as the starting of our second year of knowing each other. It's regrettable that some of us could not make it to this reunion. This does not mean that those individuals are any less significant. Each and everyone of us ELTP-19s have our share of ups and downs, we are far from being free of flaws and imperfections but these faults that made us individuals, that made us different from each other, that made us human with opinions, that made us apart of ELTP-19 (I know this sounds cliche but please bear with it... =p). Whatever it is ELTP-19 won't be ELTP-19 without YOU!
  1. Amin
  2. Anor
  3. Audrey
  4. Azlan
  5. Bahyah
  6. Bai
  7. Chitra
  8. Faizah
  9. Fong
  10. Hafiz
  11. Haikal
  12. Hairos
  13. Intan
  14. Izzati
  15. Jeeva
  16. Joanna
  17. Joshua
  18. Jothi
  19. Kalai
  20. Komathi
  21. Kumar
  22. Lihin
  23. Liza
  24. Mun Kit
  25. Phooi Yee
  26. Praveen
  27. Raveen
  28. Rehan
  29. Ronny
  30. Saad
  31. Safura
  32. Saha
  33. Selvan
  34. Shangiri
  35. Sharmili
  36. Suga
  37. Sumi
  38. Suren
  39. Suresh
  40. Thava
  41. VJ
  42. Wong Yee Hung
  43. Yasmin
The 1 who posted this is also human not AI so if I mistyped your name please voice it out.




HAPPY ANNIVERSARY ELTP-19!!!


PS - Sry for the late update guys! :D

0 comments:

What Tree Did You Fall From?

Apple Tree, the Love (December 23 to January 1)

Of slight build, lots of charm, appeal and attraction, pleasant aura, flirtatious, adventurous, sensitive, always in love, wants to love and be loved, faithful and tender partner, very generous, scientific talents, lives for today, a carefree philosopher with imagination.

Fir Tree, the Mysterious (January 2 to January 11)

Extraordinary taste, dignity, cultivated airs, loves anything beautiful, moody, stubborn, tends to egoism but cares for those close to it,rather modest, very ambitious, talented, industrious uncontent lover, many friends, many foes, very reliable.

Elm Tree, the noble-mindedness (January 12 to January 24)

Pleasant shape, tasteful clothes, modest demands, tends not forgive mistakes, cheerful, likes to lead but not to obey, honest unfaithful partner, tends to a know-all-attitude and making decisions for others, noble-minded, generous, good sense of humour, practical.

Cypress, the Faithfulness (January 25 to February 3)

Strong, muscular, adaptable, takes what life has to give, happy,content,optimistic, needs enough money and acknowledgment, hates loneliness, passionate lover which cannot be satisfied, faithful, quick-tempered,unruly, pedantic and careless.

Poplar, the Uncertainty (February 4 to February 8)

Looks very decorative, no self-confident behaviour, only courageous if necessary, needs goodwill and pleasant surroundings, very choosy, often lonely, great animosity, artistic nature, good organiser, tends to philosophy, reliable in any situation, takes partnership serious.

Cedar, the Confidence (February 9 to February 18)

Of rare beauty, knows how to adapt, likes luxury, of good health not in the least shy, tends to look down on others, self-confident, determined, impatient, wants to impress others, many talents, industrious, healthy, optimism, waiting for the one true love, able to make quick decisions.

Pine Tree, the Particularity (February 19 to February 28)

Loves agreeable company, very robust, knows how to make life comfortable, very active, natural, good companion, but seldom friendly, falls easily in love but its passion burns out quickly, gives up easily, many disappointments till it finds its ideal, trustworthy, practical.

Weeping Willow, the Melancholy (March 1 to March 10)

Beautiful but full of melancholy, attractive, very empathic, loves anything beautiful and tasteful, loves to travel, dreamer, restless, capricious, honest, can be influenced but is not easy to live with, demanding, good intuition, suffers in love but finds sometimes an anchoring partner.

Lime Tree, the Doubt (March 11 to March 20)

Accepts what life dishes out in a composed way, hates fighting, stress and labour, tends to laziness and idleness, soft and relenting, makes sacrifices for friends, many talents but not tenacious enough to make them blossom, often wailing and complaining, very jealous, loyal.

Oak, robust nature (March 21)

Courageous, strong, unrelenting, independent, sensible, does not love changes, keeps its feet on the ground, person of action.

Hazelnut Tree, the Extraordinary (March 22 to March 31)

Charming, undemanding, very understanding, knows how to make an impression, active fighter for social cause, popular, moody and capricious lover, honest and tolerant partner, precise sense of judgement.

Rowan, the Sensitivity (April 1 to April 10)

Full of charm, cheerful, gifted, without egoism, likes to draw attention, loves life, motion, unrest and even complications, is both dependent and independent, good taste, artistic, passionate, emotional, good company, does not forgive.

Maple, Independence of Mind (April 11 to April 20)

No ordinary person, full imagination and originality, shy and reserved, ambitious, proud, self respect, hungers for new experiences, sometimes nervous, many complexes, good memory, learns easily, complicated love life, wants to impress.

Walnut Tree, the Passion (April 21 to April 30)

Unrelenting, strange and full of contrasts, often egoistic, aggressive, noble, broad horizon, unexpected reactions, spontaneous, unlimited ambition, no flexibility, difficult and uncommon partner, not always liked but often admired, ingenious strategist, very jealous and passionate, no compromises.

Poplar, the Uncertainty (May 1 to May 14)

Looks very decorative, no self-confident behaviour, only courageous if necessary, needs goodwill and pleasant surroundings, very choosy, often lonely, great animosity, artistic nature, good organiser, tends to philosophy, reliable in any situation, takes partnership serious.

Chestnut Tree, the Honesty (May 15 to May 24)

Of unusual beauty, does not want to impress, well-developed sense of justice, vivacious, interested, a born diplomat, but irritable and sensitive in company, often due to a lack of self-confidence, acts sometimes superior, feels not understood, loves only once, has difficulties in finding a partner.

Ash Tree, the Ambition (May 25 to June 3)

Uncommonly attractive, vivacious, impulsive, demanding, does not care for criticism, ambitious, intelligent, talented, likes to play with its fate, can be egoistic, very reliable and trustworthy, faithful and prudent lover, sometimes brains rule over heart, but takes partnership very serious.

Hornbeam, the good taste (June 4 to June 13)

Of cool beauty, cares for its looks and condition, good taste, tends to egoism, makes life as comfortable as possible, leads reasonable, disciplined life, looks for kindness, an emotional partner and acknowledgment, dreams of unusual lovers, is seldom happy with her feelings, mistrusts most people, is never sure of its decisions, very conscientious.

Fig Tree, the Sensibility (June 14 to June 23)

Very strong, a bit self-willed, independent, does not allow contradiction or arguments, loves life, its family, children and animals, a bit of a butterfly, good sense of humour, likes idleness and laziness, of practical talent and intelligence.

Birch, the Inspiration (June 24)

Vivacious, attractive, elegant, friendly, unpretentious,modest, does not like anything in excess, abhors the vulgar, loves life in nature and in calm, not very passionate, full of imagination, little ambition, creates a calm and content atmosphere.

Apple Tree, the Love (June 25 to July 4)

Of slight build, lots of charm, appeal and attraction, pleasant aura, flirtatious, adventurous, sensitive, always in love, wants to love and be loved, faithful and tender partner, very generous, scientific talents, lives for today, a carefree philosopher with imagination.

Fir Tree, the Mysterious (July 5 to July 14)

Extraordinary taste, dignity, cultivated airs, loves anything beautiful, moody, stubborn, tends to egoism but cares for those close to it,rather modest, very ambitious, talented, industrious uncontent lover, many friends, many foes, very reliable.

Elm Tree, the noble-mindedness (July 15 to July 25)

Pleasant shape, tasteful clothes, modest demands, tends not forgive mistakes, cheerful, likes to lead but not to obey, honest unfaithful partner, tends to a know-all-attitude and making decisions for others, noble-minded, generous, good sense of humour, practical.

Cypress, the Faithfulness (July 26 to August 4)

Strong, muscular, adaptable, takes what life has to give, happy,content,optimistic, needs enough money and acknowledgment, hates loneliness, passionate lover which cannot be satisfied, faithful, quick-tempered,unruly, pedantic and careless.

Poplar, the Uncertainty (August 5 to August 14)

Looks very decorative, no self-confident behaviour, only courageous if necessary, needs goodwill and pleasant surroundings, very choosy, often lonely, great animosity, artistic nature, good organiser, tends to philosophy, reliable in any situation, takes partnership serious.

Cedar, the Confidence (August 15 to August 23)

Of rare beauty, knows how to adapt, likes luxury, of good health not in the least shy, tends to look down on others, self-confident, determined, impatient, wants to impress others, many talents, industrious, healthy, optimism, waiting for the one true love, able to make quick decisions.

Pine Tree, the Particularity (August 24 to September 2)

Loves agreeable company, very robust, knows how to make life comfortable, very active, natural, good companion, but seldom friendly, falls easily in love but its passion burns out quickly, gives up easily, many disappointments till it finds its ideal, trustworthy, practical.

Weeping Willow, the Melancholy (September 3 to September 12)

Beautiful but full of melancholy, attractive, very empathic, loves anything beautiful and tasteful, loves to travel, dreamer, restless, capricious, honest, can be influenced but is not easy to live with, demanding, good intuition, suffers in love but finds sometimes an anchoring partner.

Lime Tree, the Doubt (September 13 to September 22)

Accepts what life dishes out in a composed way, hates fighting, stress and labour, tends to laziness and idleness, soft and relenting, makes sacrifices for friends, many talents but not tenacious enough to make them blossom, often wailing and complaining, very jealous, loyal.

Olive Tree, the Wisdom (September 23)

Loves sun, warmth and kind feelings, reasonable, balanced, avoids aggression and violence, tolerant, cheerful, calm, well-developed sense of justice, sensitive, empathic, free of jealousy, loves to read and the company of sophisticated people.

Hazelnut Tree, the Extraordinary (September 24 to October 3)

Charming, undemanding, very understanding, knows how to make an impression, active fighter for social cause, popular, moody and capricious lover, honest and tolerant partner, precise sense of judgement.

Rowan, the Sensitivity (October 4 to October 13)

Full of charm, cheerful, gifted, without egoism, likes to draw attention, loves life, motion, unrest and even complications, is both dependent and independent, good taste, artistic, passionate, emotional, good company, does not forgive.

Maple, Independence of Mind (October 14 to October 23)

No ordinary person, full imagination and originality, shy and reserved, ambitious, proud, self-respect, hungers for new experiences, sometimes nervous, many complexes, good memory, learns easily, complicated love life, wants to impress.

Walnut Tree, the Passion (October 24 to November 11)

Unrelenting, strange and full of contrasts, often egoistic, aggressive, noble, broad horizon, unexpected reactions, spontaneous, unlimited ambition, no flexibility, difficult and uncommon partner, not always liked but often admired, ingenious strategist, very jealous and passionate, no compromises.

Chestnut Tree, the Honesty (November 12 to November 21)

Of unusual beauty, does not want to impress, well-developed sense of justice, vivacious, interested, a born diplomat, but irritable and sensitive in company, often due to a lack of self-confidence, acts sometimes superior, feels not understood, loves only once, has difficulties in finding a partner.

Ash Tree, the Ambition (November 22 to December 1)

Uncommonly attractive, vivacious, impulsive, demanding, does not care for criticism, ambitious, intelligent, talented, likes to play with its fate, can be egoistic, very reliable and trustworthy, faithful and prudent lover, sometimes brains rule over heart, but takes partnership very serious.

Hornbeam, the good taste (December 2 to December 11)

Of cool beauty, cares for its looks and condition, good taste, tends to egoism, makes life as comfortable as possible, leads reasonable, disciplined life, looks for kindness, an emotional partner and acknowledgment, dreams of unusual lovers, is seldom happy with her feelings, mistrusts most people, is never sure of its decisions, very conscientious.

Fig Tree, the Sensibility (December 12 to December 21)

Very strong, a bit self-willed, independent, does not allow contradiction or arguments, loves life, its family, children and animals, a bit of a butterfly, good sense of humour, likes idleness and laziness, of practical talent and intelligence.

Beech, the Creative (December 22)

Has good taste, concerned about its looks, materialist, good organisation of life and career, economical, good leader, takes no unnecessary risks, reasonable, splendid lifetime companion, keen on keeping fit (diets, sports, etc.).

0 comments:

Spring MVC : Database Connectivity

Another way to access database without using applicationContext.xml is as follows :

DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");
dataSource.setUrl("jdbc:oracle:thin:@localhost:1521:XE");
dataSource.setUsername("username");
dataSource.setPassword("pwd");
JdbcTemplate jt = new JdbcTemplate(dataSource);

Just place it in your controller and you're done. ;)

0 comments:

Spring MVC : Login App Part 3

Alright, now we'll move on to database connectivity. First create a table for our login, we only need 2 attributes, username and password, name the table as login or any name you like. In this example, i used Oracle. Basically its the same with any other database, MySQL..etc.. The difference is the class driver name and such. Here we'll simplify things by NOT using validator..and use javascript to validate fields. Much much easier..unless we're familiar with validators.

This example is done as per my understanding. You might approach this example in different way, which im sure there are lots. So if you think there's another way to do this, please feel free to comment. Share the knowledge :P

We're dropping off validator class, so you can dereference it from your bean by removing the <property name="validator"><ref bean="loginValidator"/></property> line from dispatcher-servlet.xml. Theres no further changes in that xml file. Create a simple jsp, name it as failure. jsp.

There's 2 ways to database connectivity, one is by normal JDBC, the other using Hibernate. This example uses JDBC (i'm too lazy to learn hibernate now, so i use JDBC :P) This connectivity using Springs is slightly different from Struts. So whatever you learnt in Struts u can forget it temporarily. Spring uses JDBC template in handling data access. This is not the only way. There are other ways, but so far ive found the template to be most used. Just remember to keep SpringSource website as your best friend.

One advantage of JdbcTemplate is it cleans-up the resources automatically, e.g. release the database connections. The template class of Spring is JdbcTemplate. A dataSource is provided inside JdbcTemplate.

We'll create 2 java classes, one interface and the other implementing it. We can also use just one class instead of 2. But i'll show that in the Part 4 series. So for now i'll stick to 2 classes.

Create a package called Connection. Create datacon.java in that package. (Actually this is not really the way to declare classes or packages. But for our understanding's sake we differentiate it this way) Add these lines :

public interface datacon {
public DataSource dbcon(); //don't forget to import javax.sql.DataSource

}

Create dataconimpl.java inside the same package. Add the following lines :

public class dataconimpl implements datacon{
private DataSource dataSource; //don't forget to import javax.sql.DataSource
public void setDataSource(DataSource ds) {
dataSource = ds;
}
public DataSource dbcon() {
return dataSource;
}
}


These 2 classes are referred from this page.

Now we'll see on applicationContext.xml. If you notice in that file, theres few lines of code commented. For some reason those codes are not working properly, so ive tried different way. That will be explained later once ive managed to run the application successfully. So in this file, add these lines,

<bean id="datacon" class="Connection.dataconimpl">
<property name="dataSource">
<ref local="dataSource"/>
</property>
</bean>

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:@localhost:1521:XE"/> <!-- XE - Oracle express edition -->
<property name="username" value="system"/> <!-- according to your local Oracle name, password -->
<property name="password" value="123456"/>
</bean>

Notice the highlighted dataSource? Both name are the same. We're goin to refer that datacon bean in our controller, and that datacon bean is referring to dataSource. Now let's update our LoginFormController.java. Remember we're not using validator in this example. Create your own javascript for field validation.

Now we'll see both database connectivity as well as linking failure page. Create a string variable to hold your jsp page name. .jsp extension has already resolved in the dispatcher-servlet.xml. (bean id="viewResolver") So you dont need to specify .jsp. The code will be short as we're just goin to check whether the record exists or not. If you have any other logic besides this, let me know :)

Comment out the previous codes. Then add the following codes :

String status = "success";
Resource res = new ClassPathResource("../applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(res);
datacon bean1 = (datacon) factory.getBean("datacon");
DataSource ds = bean1.dbcon();
JdbcTemplate jt = new JdbcTemplate(ds);

status variable is to hold the name of the jsp page. success is the success.jsp. you can initialise it with any string. ClassPathResource reads the applicationContext.xml. It'll read the connections defined inside. Some codes online refers the xml file without the "../" before applicationContext.xml. So improvise to see which suits you best. datacon in the getBean() is the bean that you've defined in applicationContext.xml. JdbcTemplate will be used as our data access method.

Add these lines after the ones above :

LoginFormBean loginBean = (LoginFormBean) command;

int count = jt.queryForInt("select count(*) from login where username = ? and password=?", new Object[]{loginBean.getName(), loginBean.getPassword()});
if (count==0){
status = "failure";
}else{
status = "success";
}
return new ModelAndView(status);


count will keep the number of records according to that username and password. What this code does is merely checking if there's any record based on the username and password given. Like i said, you can use any logic to check for login details. I used counting records. The select statement is somewhat same as PreparedStatement. ? as the wildcard to get user input or values. new Object[]{} is like setXXX() (e.g setString) within those curly braces, you add as many parameters you want according to the number of question marks. failure is failure.jsp. So this onSubmit() function will return the view according to the status whether it's failure or success. Same like our execute() in Struts :P So you can remove the successView property from dispatcher-servlet.xml as we don't really need them.

Your imports for this LoginFormController.java is like below :

import Bean.LoginFormBean;
import Connection.datacon;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

No changes required for index.jsp page except adding on javascript validation if you want to. Run the application and see the results. :)

0 comments:

Softwares: PhotoScape - Free Photo Editing Software

For those seeking for a FREE & EASY software to edit your images, seek no further! Here comes PhotoScape (I think it's only approx. 14 MB).

Features include:

  • Viewer : Slideshow, Fullscreen, Wallpaper, Lossless Rotation, Exif
  • Editor : Frames, Resize, Rotate, Brightness, Color, Contrast, Auto Level, Auto Contrast, Whitebalance, Curves, Sepia, Negative, Sharpen, Blur, Noise Reduction, Vignetting, Bloom, Gradient, Texture, Fisheye, Clipart, Balloon, Text, Figures, Crop, Red Eye Removal, Mosaic
  • Batch Editor : Frames, Resize, Filters, Objects
  • Page : Make one photo by merging multiple photos at the page frame
  • Combine : Make one photo by attaching multiple photos vertically or horizontally
  • Animated GIF: Make one animation photo with multiple photos
  • Print: Print portrait shot, carte de visite, passport photo
  • Screen Capture: Capture your screenshot and save it
  • Splitter: Divide a photo into multiple parts
  • Color Picker: Zoom in screen on images, search and pick the color
  • Raw Converter : Convert RAW to JPG
  • Rename: Change photo file names in batch mode
O_o loh bnyk giler... hahha i just cut and paste from their website actually. To view the screenshot just go visit PhotoScape webbies! :D Best gune software ni! hehe

0 comments:

Spring MVC : Login App Part 2

Now let's try some validation for our dummy project. Use back the same project from the previous post. Remember the validation that we used for our Struts before? (Hope u do :P) Its somewhat same as this one.

First of all, get the spring-form.tld file from the spring.jar file. Extract it and you should be able to see that file residing inside the META-INF folder. Create a folder under WEB-INF in your project, name it as tld. Copy the tld file and paste it inside the tld folder. If you want to know more about the file, visit this. So your directory should be somewhat like below.


Let's update our web.xml file. Add the following code :

<taglib>

<taglib-uri>/spring</taglib-uri>

<taglib-location>/WEB-INF/tld/spring-form.tld</taglib-location>

</taglib>


Next we'll update our bean file and our controller and we'll also add a new file for vaildation. Let's start off with our LoginFormBean.java. This is our bean file, as you all know bean file consists of getters and setters. Since this is a login application, we'll add getters and setters for username and password. So create some functions as below :


public class LoginFormBean {

String name;

String password;
public String getName() {

return name;

}
public void setName(String name) {

this.name = name;

}
public String getPassword() {

return password;

}
public void setPassword(String password) {

this.password = password;

}

}



Now add these lines to LoginFormController.java under onSubmit function. System.out.println is optional :P

LoginFormBean loginBean = (LoginFormBean) command;

System.out.println("Username: " + loginBean.getName());

System.out.println("Password: " + loginBean.getPassword());

return new ModelAndView("success"); //success here is the success.jsp

Now for our validator file. Create LoginFormValidator.java under Validator package. Add this code. Make sure you implement Validator. (LoginFormValidator implements Validator)

LoginFormBean loginBean;
@Override

public boolean supports(Class clazz) {

return clazz.equals(LoginFormBean.class);

}
@Override

public void validate(Object commandObject, Errors errors) {
loginBean = (LoginFormBean) commandObject;

ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "name", "Name is required.");

ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "password", "Password is required.");

if (!errors.hasFieldErrors("name") && !errors.hasFieldErrors("password")) {

if ((loginBean.getPassword().equals("password") == false) && (loginBean.getName().equals("admin") == false)) {

errors.rejectValue("name", "name", "Incorrect Login Details!");

}

}

}

The validator class has 2 functions, supports() and validate() method. supports() is used to check whether the validator supports the class and validate() is used to validate the object of the supported class. rejectValue() takes in few arguments, in this example, it takes 3 arguments. First argument is for the bean property, second is the key value of the error message that exists in a resource file (here Ive ommited the resource file) so for this just keep it the same as the bean property, and third argument is the default error message in case the resource file is not found. (Resource file is the *.properties file)

Next we're going to update our index.jsp page. Add this line right before the <html> tag. This is to use the tags from spring-form.tld.

<%@ taglib prefix="spring" uri="/spring" %>

The uri "spring" is the same as the one in <taglib> inside web.xml. Make sure the name is same :P

Start using the tags we have imported in the index.jsp. Its as follows :

<spring:form method="post" action="" commandName="login">

<p>

User name :

<spring:input path="name"/>

</p>

<p>

Password :

<spring:password path="password" />

</p>

<p>

<spring:errors cssClass="error" path="*"/><br>

</p>

<p>

<p>
<spring:errors cssClass="error" path="*"/><br>
</p>
<p>
<input type="submit" name="Submit" value="Submit" />
</p>
</spring:form>

and under the head tag we add the following css :


<style>
.error { color: red; }
</style>

cssClass="error" is referring to that css above. For path="*" , the * is a wildcard. Its referring to all the path (bean property) tag from the jsp . You can even specify one by one like this :

<spring:errors cssClass="error" path="name"/>

<spring:errors cssClass="error" path="password"/>

commandName="login" here is the same as the commandName specified in the dispatcher-servlet.xml.

Next we'll update our dispatcher-servlet.xml file. Since we have created a validator class, we'll make the validator being referred as well. Under the bean id = "loginForm" add the following line :

<property name="validator"><ref bean="loginValidator"/></property>

Create a new bean id for the loginValidator ref bean above.

<bean id="loginValidator" class="Validator.LoginFormValidator" />

Now try to run the application. You should be able to get the errors if its entered wrongly or submitting without entering anything.

0 comments:

Spring MVC : Login App Part 1

Let's continue with Spring by trying out a new application - Login. We'll enhance this all the way. Adding on sessions and etc... for now, lets create a dummy login.

Create project as shown before. Don't forget to change the *.htm to *.do when creating a new project. Edit the dispatcher-servlet.xml to become .do. We use back the index.jsp as our login page. Create another jsp namely success.jsp in WEB-INF/jsp.

Add the following code to index.jsp. This is our login page.

<html>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<form id="form1" name="form1" method="post" action="">
<p>
User name :
<input type="text" name="name"/>
</p>
<p>
Password :
<input type="password" name="password" />

</p>
<p>
<input type="submit" name="Submit" value="Submit" />
</p>
</form>
</html>


Create 3 packages - Bean, Controller, Validator ( will be used in next tutorial). Under Bean package, create a java class - LoginFormBean.java. Leave it empty (empty class). Under Controller package, create a java class - LoginFormController.java. You can create this file by doing the following. Right click the project or from the file menu -> New File -> Spring Framework -> Simple Form Controller . The codes will be generated for you.





Remove the doSubmitAction and uncomment onSubmit function. Leave it as it is. Edit dispatcher-servlet.xml. Add the following code.

<bean id="loginForm" class="Controller.LoginFormController">
<property name="sessionForm"><value>true<value></property>
<property name="commandName"><value>login</value></property>
<property name="commandClass"><value>Bean.LoginFormBean</value></property>
<property name="formView"><value>index</value></property>
<property name="successView"><value>success</value></property>
</bean>

<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<map>
<entry key="/index.do">
<ref bean="loginForm"/>
</entry>
</map>
</property>
</bean>

Remove the indexcontroller part. Notice that loginForm in the urlMapping bean is the same as the one above. Quoting from here.
  • commandClass—the class of the object that will be used to represent the data in this form. (tht is the bean)
  • commandName—the name of the command object. (bean name)
  • sessionForm—if set to false, Spring uses a new bean instance (i.e. command object) per request, otherwise it will use the same bean instance for the duration of the session.
  • validator—a class that implements Spring's Validator interface, used to validate data that is passed in from the form.
  • formView—the JSP for the form, the user is sent here when the controller initially loads the form and when the form has been submitted with invalid data. (input)
  • successView—the JSP that the user is routed to if the form submits with no validation errors. (success)
Try and run your application. Make sure the login page appears. Next part of the tutorial will be the using validator..(like our struts)

0 comments:

Another basic Spring tutorial

After hours of figuring out how this Spring thingy works..finally came up with one simple app using controllers and stuff. So lets create an app to display values entered by user.

Jar files usually needed for Spring are :


  • spring. jar
  • standard.jar
  • jstl.jar
  • taglibs-string. jar
  • commons-lang.jar
  • commons-logging-1.1.jar
  • spring-webmvc-2.5.jar
  • log4j-1.2.14.jar
You can get the jar files you need here.

Create a new project, here I've used the name springtest. So far no jar files are needed except the one which comes together with the netbeans project file. While creating new project, change the *.htm to *.do coz we want to use it the .do way :P (refer below)





Create a jsp file under WEB-INF/jsp. Name it as test.jsp. (or any other name u like :P) Inside this test.jsp add the following code :

<html>
<head>
<meta equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<form method="POST" action="/springtest/dispatcher/saveform.do">
First Name:
<input name="firstName" type="text" value="">
Last Name:
<input name="lastName" type="text" value="">
<input type="submit" value="Save Changes">
</form>
</html>

springtest here is the project name. dispatcher here is the "dispatcher"-servlet.xml. if you give the name as name-servlet.xml then your action will look like this :: /springtest/name/saveform.do.


Now we're goin to edit dispatcher-servlet.xml.

change this "<prop key="/index.htm">indexController</prop>" to this "<prop key="/test.do">indexController</prop>" coz we're goin to connect it to test.jsp. well practically u can give it any name. Its just like the name of ur .do in struts :P So your code should look like this.




<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/index.do">indexController</prop>
</props>
</property>
</bean>


and that code is related to this one.. see the word "index" above? its the same index in the code below. How it works and all..will be figured out soon :P

<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" /
>

So if you want to load any file, just replace the word index with the file name. In this case, change them to test. so it becomes test.do. In redirect.jsp, change the url to "test.do". Try running the project and see if it runs correctly
. For some reason its not possible to run the specific file. It only works by running the whole project. This will be figured out soon as well..lol so patience!

So the final code :

<bean id="defaultHandlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>


<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/test.do">indexController</prop>
</props>
</property>
</bean>

<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="test" /
>

Create a success page. Name it as testsuccess.jsp for instance. Under this file, add the following code:

<%@ taglib uri='http://java.sun.com/jsp/jstl/core' prefix='c'%>
//dont forget to add this at the top!

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h2>Name <c:out value="${name}"/></h2>

</body>
</html
>


c:out here is somewhat the same as our bean write in struts. Here the name is the attribute name that we have passed from controller. We will see that below.

Create a package under source packages. Name it as controller.

Under controller package, create java class called FormController.java. Inside this class, add the following codes :

package controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class FormController implements Controller {

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
return new ModelAndView("test");
//RequestDispatcher that will send the request to /WEB-INF/jsp/test.jsp
}
}

Create second file under the controller package called SaveController.java. Add the following code:

package controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class SaveController implements Controller {

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
return new ModelAndView("testsuccess", "name" , firstName + lastName);
//RequestDispatcher that will send the request to /WEB-INF/jsp/testsuccess.jsp
}
}

In this code, testsuccess is the jsp file. name is the attribute name which will be accessed by getParameter(), and firstName+lastName is the name that is sent thru that name attribute.

Then lastly add these last 2 lines inside the dispatcher-servlet.xml.

<bean name="/dispatcher/displayform.do" class="controller.FormController"/>
<bean name="/dispatcher/saveform.do" class="controller.SaveController"/
>

these lines are similar to our struts-config.xml. bean name is the action name in struts. class is your java class (package.javaclassname)

Try running the whole application again. The output should be something like below :









This app is done without using form bean. That will be another tutorial :P

Posted By - Lakshmi

2 comments: