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: