Thursday, October 30, 2014

Java MySQL UPDATE Using PreparedStatement


Java MySQL UPDATE Using PreparedStatement

In the Java applications there are several ways to update the data base records. The more convenient way is using the PreparedStatement for update the data base records by sending the SQL statements.

In this tutorial we used the PreparedStatements for update the records available in MySQL data base.

Scope : Update the table records in MySQL with using Prepared Statement.

Objective : Update the table records in MySQL with using Prepared Statement.

Requirements :
  • Eclipse Java EE IDE
  • MySQL Server 5.5
Step 1 : Create an Java project in Eclipse and name it as "UpdateExample". 

Step 2 : Download the "mysql-connector.jar" from here and add to the project build path.

Step 3 : Create a table Student in MySQL test database with using following script.


1
2
3
4
5
6
CREATE TABLE `test`.`Students` (
  `id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
  `firstname` VARCHAR(45) NOT NULL DEFAULT '',
  `email` VARCHAR(50) NOT NULL DEFAULT '',
  PRIMARY KEY(`id`)
);

Insert the following records to the Student table which we already created with using the above script.


1
2
insert into users (firstname, email) values ('John', 'john@gmail.com');
insert into users (firstname, email) values ('Tester', 'Tester@test.com');


Step 4 : Create a class "PreparedStatementUpdate" under the "com.findanidea.update" package.

The MySql driver and the url defined as private static final instance variable at line numbers 10 and 11.

The Connection created at the line number 15 with using the getConnection method. The SQL statement for update the records specified in the line number 18. The input parameters defined in order in line numbers 20 and 21. 

Finally the prepared statement executed at line number 24 and if its executed successfully the message specified in the line number 25 will print at the application console.

/UpdateExamle/src/com/findanidea/update/PreparedStatementUpdate.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.findanidea.update;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class PreparedStatementUpdate {
 
 private static final String myDriver = "com.mysql.jdbc.Driver";
 private static final String myUrl = "jdbc:mysql://localhost:3306/test";
 public static void main(String[] args) {
  try {
   
   Connection conn = getConnection();

   // create the update preparedstatement
   String query = "update student set email = ? where firstname = ?";
   PreparedStatement preparedStmt = conn.prepareStatement(query);
   preparedStmt.setString(1, "tester@test.com");
   preparedStmt.setString(2, "John");

   // execute the preparedstatement
   preparedStmt.executeUpdate();
   System.out.println("Record updated Successfully.");
   conn.close();
  } catch (Exception e) {
   System.err.println("Exception Occurs!!!!");
   System.err.println(e.getMessage());
  }
 }
 
 private static Connection getConnection() throws ClassNotFoundException, SQLException {
  Class.forName(myDriver);
  Connection conn = DriverManager.getConnection(myUrl, "root", "1234");
  return conn;
 }
}


Step 5 : Once execute the above mentioned class in the Step 4, you able to see the below out put at your application console.


1
Record updated Successfully.

Tuesday, October 28, 2014

How to create WSDL in Eclipse


How to create WSDL in Eclipse

WSDL (Web Service Description Language) is one of the core part of the web service development. In the WSDL file we defines what are the operations going to performs, how to access the services and service url end point etc. 

In the below tutorial you able to learn that, how to create the WSDL file for simple string manipulation function.

Objective : Create a WSDL with using eclipse.

Scope : Create a WSDL in eclipse and validate which is serve welcome message as a service response.

Requirements : 
  • Eclipse Java EE IDE

Step 1 : Create a java project in eclipse and name it as "WSDL".

Step 2 : Select the "WSDL" project and create a new WSDL file as below.
 - Right click of "WSDL" project > New > Other 
 - The New Select a wizard will appear.
 - Select Web Service > WSDL and click "Next" button on the wizard.
 - You have to name the WSDL at this point. Just name it as "helloworld.wsdl".





 - From the following wizard screen, except the Target name space rest of the settings kept as it is. Further more details of the setting able to find here.



 - Finally click the finish button.

Step 3 : Change the address to "http://localhost:8181/webservice/services/helloworld/". 

In future we are going to generate a service and client based on the WSDL created in this tutorial. 

The default operation name changed to "newOperation" to "sayHello" and save it.

The WSDL source looks like below.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://localhost:8181/webservice/services/helloworld/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="helloworld" targetNamespace="http://localhost:8181/webservice/services/helloworld/">
  <wsdl:types>
    <xsd:schema targetNamespace="http://localhost:8181/webservice/services/helloworld/">
      <xsd:element name="sayHello">
        <xsd:complexType>
          <xsd:sequence>
            <xsd:element name="name" type="xsd:string"/>
          </xsd:sequence>
        </xsd:complexType>
      </xsd:element>
      <xsd:element name="sayHelloResponse">
        <xsd:complexType>
          <xsd:sequence>
            <xsd:element name="output" type="xsd:string"/>
          </xsd:sequence>
        </xsd:complexType>
      </xsd:element>
    </xsd:schema>
  </wsdl:types>
  <wsdl:message name="sayHelloRequest">
    <wsdl:part element="tns:sayHello" name="parameters"/>
  </wsdl:message>
  <wsdl:message name="sayHelloResponse">
    <wsdl:part element="tns:sayHelloResponse" name="parameters"/>
  </wsdl:message>
  <wsdl:portType name="helloworld">
    <wsdl:operation name="sayHello">
      <wsdl:input message="tns:sayHelloRequest"/>
      <wsdl:output message="tns:sayHelloResponse"/>
    </wsdl:operation>
  </wsdl:portType>
  <wsdl:binding name="helloworldSOAP" type="tns:helloworld">
    <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
    <wsdl:operation name="sayHello">
      <soap:operation soapAction="http://localhost:8181/webservice/services/helloworld/sayHello"/>
      <wsdl:input>
        <soap:body use="literal"/>
      </wsdl:input>
      <wsdl:output>
        <soap:body use="literal"/>
      </wsdl:output>
    </wsdl:operation>
  </wsdl:binding>
  <wsdl:service name="helloworld">
    <wsdl:port binding="tns:helloworldSOAP" name="helloworldSOAP">
      <soap:address location="http://localhost:8181/webservice/services/helloworld/"/>
    </wsdl:port>
  </wsdl:service>
</wsdl:definitions>


Step 4 : For validate the WSDL just right click on the WSDL source and Validate. If any errors occurs its pointed with red color.


Thursday, October 23, 2014

Send SMS via Twitter with JAVA application


Send SMS via Twitter step by step

Almost all the server monitoring systems has the "Health Check" functionality. Using that, we able to monitor the CPU performance, memory usage.. etc. If any of the server performances are reach the predefined threshold value, the system send the email or SMS alert to configured users.

In this tutorial, you can learn that, how to send the SMS message with using twitter via Java application. In additionally you can also learn how to register the application in twitter and what are the limitations if we use the twitter for send SMS.

Objective : The main Objective of the tutorial is that, register the application in twitter and develop a Java application for send SMS. 

Scope : Develop a simple Java application for send SMS via twitter.

Requirements : The following basic requirement we need to set it up in order to achieve the objective.
  • Eclipse JAVA EE IDE
  • JDK 1.6
  • Twitter related jars
Step 1 : You have to create an Twitter account and need to register the application with twitter. The registration details explained here. Once the registration is completed, the registered account will be use to send the messages to clients.

Step 2 : Once the registration process completed you able to get the following tokens\keys from the twitter page. Please note that the tokens and keys are very important, so save those details to some secure place. 

Do not share the key/tokens to public, because using that, any once can send the messages through your registered application.


Step 3 : Create a java project in Eclipse and name it as "TweetMsg". Add the following jars to build path of the project.
  • twitter4j-async-3.0.5.jar
  • twitter4j-core-3.0.5.jar
  • twitter4j-media-support-3.0.5.jar
  • twitter4j-stream-3.0.5.jar 
Step 4 : Create a java class "TweetMessage" in package "com.prem.twitter.message". The following TweetMessage class used to send the message to twitter account with using the token/keys.

/TweetMsg/src/com/prem/twitter/message/TweetMessage.java


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.prem.twitter.message;

import java.io.IOException;
import java.util.logging.Logger;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;

public class TweetMessage {
 private final Logger logger = Logger.getLogger(TweetMessage.class
   .getName());

 public void start(String message) throws TwitterException, IOException {

  Twitter twitter = new TwitterFactory().getInstance();
  try {
   RequestToken requestToken = twitter.getOAuthRequestToken();
   AccessToken accessToken = null;
   while (null == accessToken) {
    logger.fine("Open the following URL and grant access to your account:");
    logger.fine(requestToken.getAuthorizationURL());
    try {
     accessToken = twitter.getOAuthAccessToken(requestToken);
    } catch (TwitterException te) {
     if (401 == te.getStatusCode()) {
      logger.severe("Unable to get the access token.");
     } else {
      te.printStackTrace();
     }
    }
   }
   logger.info("Got access token.");
   logger.info("Access token: " + accessToken.getToken());
   logger.info("Access token secret: " + accessToken.getTokenSecret());
  } catch (IllegalStateException ie) {
   // access token is already available, or consumer key/secret is not
   // set.
   if (!twitter.getAuthorization().isEnabled()) {
    logger.severe("OAuth consumer key/secret is not set.");
    return;
   }
  }
  twitter.updateStatus(message);
 }

 public static void main(String[] args) throws Exception {
  String tweetMsg = "";
  for (String string : args) {
   tweetMsg = tweetMsg + string + " ";
  }
  new TweetMessage().start(tweetMsg);
 }
}



Please note that, you can not send the same tweet message twice to the twitter account.


Step 5 : Store the tokens and keys in to "twitter4j.properties" file. Using the properties the class mentioned in Step 4 send the message to twitter account.

/TweetMsg/twitter4j.properties

1
2
3
4
5
6
oauth.consumerSecret=elVY6ILJJTdTDnJkTdFkClzlbRsTg7jZFxDENTqOE
debug=true
oauth.accessToken=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
oauth.accessTokenSecret=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
http.prettyDebug=true
oauth.consumerKey=s1FBhBmAinYYKkX8SDHw

Step 6 : Now the time to configure the message receive option in twitter account. Once enabled the SMS notification, then only the users able to receive the SMS from twitter. You can find here for enable the SMS notification explained in the twitter site.

Step 7 : Now the time to run the "TweetMessage" class with parameters. You can find here for how to run the application with input parameters. In our example the input parameter is the string message. 

For example if you run the class with the text "Hello World" as the input parameter, then the same text message send to clients twitter account and if the twitter account enabled as SMS notification, then the same text will receive as SMS to the client mobile also.



E.E: 
- Make it sure the firewall is enable for access the twitter site.

Limitations : 
The Twitter has a set of limitations for sending SMS. You able to find the SMS limitations defined by twitter here. 


Hibernate LOAD VS GET methods


Hibernate LOAD VS GET Methods

Most of the time the developers mix use the session.get() and session.load() hibernate methods, while they develop the applications. If they know the difference between the both of the methods, its may help to them to use those method properly. Not only that but also,  most of the technical interviews the developers faced the question regarding the difference between session.get() and session.load() methods..

In this tutorial the main objective is that, developers need to understand the session.get() and session.load() methods before they going to use in future.

But before going to list down the properties, both session.get() and session.load() methods are going to use for retrieve the objects. But there are bit differences.

The below table list down the session.get() method properties.

Get
get() involves database hits if the object does not in Session Cache, and return fully initialized object.
get() method returns null if object is not found in cache as well as on database
get() method is not return the proxy, but its returns fully initialized object or null.
Use of get() is little less performance compare with load()
Execution :
1
2
Session session = SessionFactory.getCurrentSession();
Student student = (Student) session.get(Student.class, StudentID);

The below table list down the session.load() method properties.

Load
load() can return proxy in place and only initialize the object or hit the database if any method other than getId() is called on persistent or entity object.
load() method throws ObjectNotFoundException instead of null, if object is not found on cache as well as on database
load() method may return proxy, which is the object with ID but without initializing other properties
Use of load() is littel better performance compare with get()
Execution :
1
2
Session session = SessionFactory.getCurrentSession();
Student student = (Student) session.load(Student.class, StudentID);

Wednesday, October 22, 2014

Spring MVC + Hibernate CRUD Web Application


Spring (4) MVC + Hibernate (4) CRUD Web Application

Scope : Develop an web application with using Spring and Hibernate

Objective : Develop a student management application with CRUD functionality.

Requirements : 
  • Eclipe Java EE IDE
  • JDK 1.6
  • MySQL Server 5.5
Step 1 : Create a dynamic web project in eclipse and name it as "SpringSimpleStudentMVC". 

Step 2 : The data base properties defined as below. 

/SpringSimpleStudentMVC/src/database.properties


1
2
3
4
5
6
7
database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/test
database.user=root
database.password=1234
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
hibernate.dialect=org.hibernate.dialect.MySQLDialect

Step 3 : Create a "Student" domain class under the "com.prem.domain" package.

/SpringSimpleStudentMVC/src/com/prem/domain/Student.java


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package com.prem.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Student {
 @Id
 @GeneratedValue
 private int id;

 @Column(name = "FIRSTNAME")
 private String firstName;

 @Column(name = "LASTNAME")
 private String lastName;

 @Column(name = "EMAIL")
 private String email;

 @Column(name = "CONTACTNO")
 private String phone;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public String getEmail() {
  return email;
 }

 public void setEmail(String email) {
  this.email = email;
 }

 public String getPhone() {
  return phone;
 }

 public void setPhone(String phone) {
  this.phone = phone;
 }

}


Step 4 : Create "StudentDAO" and "StudentDAOImpl" interface and class file under the "com.prem.dao" package.

/SpringSimpleStudentMVC/src/com/prem/dao/StudentDAO.java


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
package com.prem.dao;

import java.util.List;
import com.prem.domain.Student;

public interface StudentDAO {

 public void saveStudent(Student student);

 public List<Student> getAllStudent();

 public Student getStudentById(int id);

 public void updateStudent(Student student);

 public void deleteStudent(int id);
}

The "StudentDAOImpl" class looks like as below.

/SpringSimpleStudentMVC/src/com/prem/dao/StudentDAOImpl.java


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package com.prem.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.prem.domain.Student;

public class StudentDAOImpl implements StudentDAO {

 @Autowired
 private SessionFactory sessionFactory;

 public void setSessionFactory(SessionFactory sessionFactory) {
  this.sessionFactory = sessionFactory;
 }

 @Override
 @Transactional
 public void saveStudent(Student student) {
  Session session = sessionFactory.openSession();
  Transaction tx = session.beginTransaction();
  session.saveOrUpdate(student);
  tx.commit();
  Serializable id = session.getIdentifier(student);
  session.close();
 }

 @Override
 public List<Student> getAllStudent() {
  Session session = sessionFactory.openSession();
  List<Student> studentList = session.createQuery("from Student").list();
  session.close();
  return studentList;
 }

 @Override
 public Student getStudentById(int id) {
  Session session = sessionFactory.openSession();
  return (Student) session.load(Student.class, new Integer(id));
 }

 @Override
 public void updateStudent(Student student) {
  Session session = sessionFactory.openSession();
  Transaction tx = session.beginTransaction();
  session.saveOrUpdate(student);
  tx.commit();
  Serializable id = session.getIdentifier(student);
  session.close();

 }

 @Override
 @Transactional
 public void deleteStudent(int id) {
  Session session = sessionFactory.openSession();  
    Transaction tx = session.beginTransaction();  
    Student student = (Student) session.load(Student.class, id);  
    session.delete(student);  
    tx.commit();  
    Serializable ids = session.getIdentifier(student);  
    session.close();  
 }

}

Step 5: Now the time to create a "StudentService" interface and the "StudentServiceManger" class under the "com.prem.service" package.

/SpringSimpleStudentMVC/src/com/prem/service/StudentService.java


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
package com.prem.service;

import java.util.List;
import com.prem.domain.Student;

public interface StudentService {
 public void saveStudentDetails(Student student);

 public List<Student> getAllStudents();

 public Student getStudentDeatilsById(int id);

 public void updateStudentDeatils(Student student);

 public void deleteStudentDetails(int id);
}

And the StudentServiceManger class as below.

/SpringSimpleStudentMVC/src/com/prem/service/StudentServiceManager.java


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.prem.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.prem.dao.StudentDAO;
import com.prem.domain.Student;
import com.prem.service.StudentService;

@Service
public class StudentServiceManager implements StudentService {
 
 @Autowired
 private StudentDAO studentDAO;

 public StudentDAO getStudentDAO() {
  return studentDAO;
 }

 public void setStudentDAO(StudentDAO studentDAO) {
  this.studentDAO = studentDAO;
 }

 @Override
 @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
 public void saveStudentDetails(Student student) {
  studentDAO.saveStudent(student);
 }

 @Override
 public List<Student> getAllStudents() {
  return studentDAO.getAllStudent();
 }

 @Override
 public Student getStudentDeatilsById(int id) {
  return studentDAO.getStudentById(id);
 }

 @Override
 public void updateStudentDeatils(Student student) {
  studentDAO.updateStudent(student);
 }

 @Override
 public void deleteStudentDetails(int id) {
  studentDAO.deleteStudent(id);
 }

}


Step 6 : Now we are going to create the "StudentController" class under the package "com.prem.controller".


/SpringSimpleStudentMVC/src/com/prem/controller/StudentController.java


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.prem.controller;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.prem.domain.Student;
import com.prem.service.StudentService;

@Controller
public class StudentController {

 @Autowired
 @Qualifier(value="studentService")
 StudentService studentService;

 public StudentService getStudentService() {
  return studentService;
 }

 public void setStudentService(StudentService studentService) {
  this.studentService = studentService;
 }

 @RequestMapping("form")
 public ModelAndView getForm(@ModelAttribute Student student) {
  return new ModelAndView("form");
 }

 @RequestMapping("register")
 @Transactional(readOnly=false)
 public ModelAndView registerUser(@ModelAttribute Student student) {
  studentService.saveStudentDetails(student);
  return new ModelAndView("redirect:list");
 }

 @RequestMapping("list")
 public ModelAndView getList() {
  List<Student> studentList = studentService.getAllStudents();
  return new ModelAndView("list", "studentList", studentList);
 }

 @RequestMapping("delete")
 public ModelAndView deleteUser(@RequestParam int id) {
  studentService.deleteStudentDetails(id);
  return new ModelAndView("redirect:list");
 }

 @RequestMapping("edit")
 public ModelAndView editUser(@RequestParam int id,
   @ModelAttribute Student student) {
  Student studentObject = studentService.getStudentDeatilsById(id);
  return new ModelAndView("edit", "studentObject", studentObject);
 }

 @RequestMapping("update")
 public ModelAndView updateUser(@ModelAttribute Student student) {
  studentService.updateStudentDeatils(student);
  return new ModelAndView("redirect:list");
 }

}


Step 7 : The spring configurations looks as below.

/SpringSimpleStudentMVC/WebContent/WEB-INF/mvc-dispatcher.xml


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
  
 <context:annotation-config />
 <context:property-placeholder location="classpath:database.properties" />
 <context:component-scan base-package="com.prem.dao.impl" />
 <context:component-scan base-package="com.prem.service.manager" />
 <context:component-scan base-package="com.prem.controller" />

 <bean id="viewResolver"
  class="org.springframework.web.servlet.view.UrlBasedViewResolver">
  <property name="viewClass"
   value="org.springframework.web.servlet.view.JstlView" />
  <property name="prefix" value="/WEB-INF/pages/" />
  <property name="suffix" value=".jsp" />
 </bean>

 <bean id="persistenceExceptionTranslationPostProcessor"
  class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

 <bean
  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="location" value="database.properties" />
 </bean>

 <bean class="org.springframework.jdbc.datasource.DriverManagerDataSource"
  id="dataSource">
  <property name="driverClassName" value="${database.driver}"></property>
  <property name="url" value="${database.url}"></property>
  <property name="username" value="${database.user}"></property>
  <property name="password" value="${database.password}"></property>
 </bean>

 <bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
  id="sessionFactory">
  <property name="dataSource" ref="dataSource"></property>
  <property name="annotatedClasses"> 
   <list> 
    <value>com.prem.domain.Student</value> 
   </list> 
  </property>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">${hibernate.dialect}</prop>
    <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
    <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}  </prop>
   </props>
  </property>
 </bean>
 
 <tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
 
 <bean class="org.springframework.orm.hibernate4.HibernateTransactionManager"
  id="hibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory"></property>
 </bean>

 <bean id="studentDAO" class="com.prem.dao.StudentDAOImpl">
 </bean> 
 <bean id="studentService" class="com.prem.service.StudentServiceManager">
 </bean> 
</beans>


Step 8 : Now the time to create the jsp files for student registration.

/SpringSimpleStudentMVC/WebContent/WEB-INF/pages/form.jsp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>  
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>  
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>  
<!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=UTF-8">  
<title>Student Registration Form</title>  
</head>  
<body >  
 <center>  
  
  <div style="color: blue; font-size: 25px">Student  Registration Form</div>  
 
  <c:url var="userRegistration" value="saveUser.html" />  
  <form:form id="registerForm" modelAttribute="student" method="post" action="register">  
   <table width="500px" height="170px">  
    <tr>  
     <td><form:label path="firstName">First Name</form:label>  
     </td>  
     <td><form:input path="firstName" />  
     </td>  
    </tr>  
    <tr>  
     <td><form:label path="lastName">Last Name</form:label>  
     </td>  
     <td><form:input path="lastName" />  
     </td>  
    </tr>  
    <tr>  
     <td><form:label path="email">Email</form:label>  
     </td>  
     <td><form:input path="email" />  
     </td>  
    </tr>  
    <tr>  
     <td><form:label path="phone">Phone</form:label>  
     </td>  
     <td><form:input path="phone" />  
     </td>  
    </tr>  
    <tr>  
     <td></td>  
     <td><input type="submit" value="Register" /></td>  
    </tr>  
   </table>  
  </form:form>  
  
  <a href="list">View All Students List</a>  
 </center>  
</body>  
</html>  

Step 9 : Now the time to run and see the behavior of the application.

The student registration screen looks like as below.





And the student details screen looks like as below.