Pages

Affichage des articles dont le libellé est spring. Afficher tous les articles
Affichage des articles dont le libellé est spring. Afficher tous les articles

mercredi 29 mai 2013

Spring Logging with Log4J

This is very easy to use Log4J functionality inside Spring applications. The following example will take you through simple steps to explain the simple integration between Log4J and Spring.
I assume you already have log4J installation on your machine, if you do not have it then you can download it from http://logging.apache.org/ and simply extract the zipped file in any folder. We will use only log4j-x.y.z.jar in our project.
Next, let us have working Eclipse IDE in place and follow the following steps to develope a Dynamic Form based Web Application using Spring Web Framework:

Spring Web MVC Framework

The Spring web MVC framework provides model-view-controller architecture and ready components that can be used to develop flexible and loosely coupled web applications. The MVC pattern results in separating the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements.
  • The Model encapsulates the application data and in general they will consist of POJO.
  • The View is responsible for rendering the model data and in general it generates HTML output that the client's browser can interpret.

Spring Beans Auto-Wiring

You have learnt how to declare beans using the <bean> element and inject <bean> with using <constructor-arg> and <property> elements in XML configuration file.
The Spring container can autowire relationships between collaborating beans without using <constructor-arg> and <property> elements which helps cut down on the amount of XML configuration you write for a big Spring based application.

Autowiring Modes:

jeudi 23 mai 2013

How To Inject Null Value In Spring

In Spring, you can uses this special <null /> tag to pass a “null” value into constructor argument or property.

1. Constructor Argument

The wrong way to inject a null into constructor argument, a really common mistake, and nice try :)

Spring Dependency Injection

In Spring frameowork, Dependency Injection (DI) design pattern is used to define the object dependencies between each other. It exits in two major types :
  • Setter Injection
  • Constructor Injection

Spring 3 MVC And XML Example

In Spring 3, one of the feature of “mvc:annotation-driven“, is support for convert object to/from XML file, if JAXB is in project classpath.
In this tutorial, we show you how to convert a return object into XML format and return it back to user via Spring @MVC framework.
Technologies used :

Spring 3 MVC And JSON Example

In Spring 3, you can enable “mvc:annotation-driven” to support object conversion to/from JSON format, if Jackson JSON processor is existed on the project classpath.
In this tutorial, we show you how to output JSON data from Spring MVC.
Technologies used :

Ajax with Spring MVC 3 using Annotations and JQuery

Its always been fun for me to work with Ajax! Is not it ? I will make it easy for you to use Ajax with Spring MVC 3 and JQuery. This post will illustrate you how to use Ajax in real life practices of industrial coding. As usual, we will take an practical example of Ajax in Spring MVC 3 framework and will implement it and I will make the implementation easy by make you understand the topic.


Ajax with Spring MVC 3 using Annotations and JQuery

Its always been fun for me to work with Ajax! Is not it ? I will make it easy for you to use Ajax with Spring MVC 3 and JQuery. This post will illustrate you how to use Ajax in real life practices of industrial coding. As usual, we will take an practical example of Ajax in Spring MVC 3 framework and will implement it and I will make the implementation easy by make you understand the topic.


Ajax with Spring MVC 3 using Annotations and JQuery

Its always been fun for me to work with Ajax! Is not it ? I will make it easy for you to use Ajax with Spring MVC 3 and JQuery. This post will illustrate you how to use Ajax in real life practices of industrial coding. As usual, we will take an practical example of Ajax in Spring MVC 3 framework and will implement it and I will make the implementation easy by make you understand the topic.


Ajax with Spring MVC 3 using Annotations and JQuery

Its always been fun for me to work with Ajax! Is not it ? I will make it easy for you to use Ajax with Spring MVC 3 and JQuery. This post will illustrate you how to use Ajax in real life practices of industrial coding. As usual, we will take an practical example of Ajax in Spring MVC 3 framework and will implement it and I will make the implementation easy by make you understand the topic.


Ajax with Spring MVC 3 using Annotations and JQuery

Its always been fun for me to work with Ajax! Is not it ? I will make it easy for you to use Ajax with Spring MVC 3 and JQuery. This post will illustrate you how to use Ajax in real life practices of industrial coding. As usual, we will take an practical example of Ajax in Spring MVC 3 framework and will implement it and I will make the implementation easy by make you understand the topic.


Ajax with Spring MVC 3 using Annotations and JQuery

Its always been fun for me to work with Ajax! Is not it ? I will make it easy for you to use Ajax with Spring MVC 3 and JQuery. This post will illustrate you how to use Ajax in real life practices of industrial coding. As usual, we will take an practical example of Ajax in Spring MVC 3 framework and will implement it and I will make the implementation easy by make you understand the topic.
Let us see what is our example’s requirement and how Spring MVC 3 Ajax facility will fulfill it :
In our example, we will make a list of students with name and highest education level, to send the list to the placement office so that the students can get chance. We will make the “Add Student Form” available to the student online so that they can submit their name online and get registered. As a lot of students will use the system, so the performance of the system may very much low. To increase to performance of the web application we will use Ajax with Spring MVC 3 Framework and JQuery.
Following steps we have to go through to implement our example :
  1. First of all, we will create a domain class (User.java) that will hold the value of student information.
  2. After that we will create our controller class (UserListController.java) to handle HTTP request. Our controller will handle three types of requests. First, to show the “Add Student Form”, second to handle Ajax request came from “Add Student Form” and add the students to a list, third to show the student information as a list.
  3. Then, we will create jsp page (AddUser.jsp) to show “Add Student Form” that will use JQuery to send Ajax request to the Spring MVC Controller. The jsp will also confirm to the user that Student has been added to the list.
  4. Then, we will create a jsp (ShowUsers.jsp) that will list all users in the list.
User.java
User.java has two properties name and education to store the student information. Following is the code of User.java :
1package com.raistudies.domain;
2 
3public class User {
4 
5    private String name = null;
6    private String education = null;
7    // Getter and Setter are omitted for making the code short
8}
UserListController.java
Controllers has three method to handle three request urls. “showForm” method handle the request for showing the form to the user. Bellow code shows the UserListController.java :
01package com.raistudies.controllers;
02 
03import java.util.ArrayList;
04import java.util.List;
05 
06import org.springframework.stereotype.Controller;
07import org.springframework.ui.ModelMap;
08import org.springframework.validation.BindingResult;
09import org.springframework.web.bind.annotation.ModelAttribute;
10import org.springframework.web.bind.annotation.RequestMapping;
11import org.springframework.web.bind.annotation.RequestMethod;
12import org.springframework.web.bind.annotation.ResponseBody;
13 
14import com.raistudies.domain.User;
15 
16@Controller
17public class UserListController {
18    private List<User> userList = new ArrayList<User>();
19 
20    @RequestMapping(value="/AddUser.htm",method=RequestMethod.GET)
21    public String showForm(){
22        return "AddUser";
23    }
24 
25    @RequestMapping(value="/AddUser.htm",method=RequestMethod.POST)
26    public @ResponseBody String addUser(@ModelAttribute(value="user") User user, BindingResult result ){
27        String returnText;
28        if(!result.hasErrors()){
29            userList.add(user);
30            returnText = "User has been added to the list. Total number of users are " + userList.size();
31        }else{
32            returnText = "Sorry, an error has occur. User has not been added to list.";
33        }
34        return returnText;
35    }
36 
37    @RequestMapping(value="/ShowUsers.htm")
38    public String showUsers(ModelMap model){
39        model.addAttribute("Users", userList);
40        return "ShowUsers";
41    }
42}
“addUsers” is same as the controller method that handle form expect that it also contain annotation @ResponseBody, which tellsSpring MVC that the String returned by the method is the response to the request, it does not have to find view for this string. So the retuning String will be send back to the browser as response and hence the Ajax request will work. “showUsers” method is used to show the list of the students to the user.
AddUser.jsp
AddUser.jsp contain a simple form to collect information about the student and uses JQerey JavaScript framework to generate Ajax request to the server. Following is the code in AddUser.jsp :
01<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
02pageEncoding="ISO-8859-1"%>
03<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
04<html>
05    <head>
06        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
07        <title>Add Users using ajax</title>
08        <script src="/AjaxWithSpringMVC2Annotations/js/jquery.js"></script>
09        <script type="text/javascript">
10        function doAjaxPost() {
11        // get the form values
12        var name = $('#name').val();
13        var education = $('#education').val();
14 
15        $.ajax({
16        type: "POST",
17        url: "/AjaxWithSpringMVC2Annotations/AddUser.htm",
18        data: "name=" + name + "&education=" + education,
19        success: function(response){
20        // we have the response
21        $('#info').html(response);
22        $('#name').val('');
23        $('#education').val('');
24        },
25        error: function(e){
26        alert('Error: ' + e);
27        }
28        });
29        }
30        </script>
31    </head>
32    <body>
33        <h1>Add Users using Ajax ........</h1>
34        <table>
35            <tr><td>Enter your name : </td><td> <input type="text" id="name"><br/></td></tr>
36            <tr><td>Education : </td><td> <input type="text" id="education"><br/></td></tr>
37            <tr><td colspan="2"><input type="button" value="Add Users" onclick="doAjaxPost()"><br/></td></tr>
38            <tr><td colspan="2"><div id="info" style="color: green;"></div></td></tr>
39        </table>
40        <a href="/AjaxWithSpringMVC2Annotations/ShowUsers.htm">Show All Users</a>
41    </body>
42</html>
You may be little bit confused if you are not aware of JQuery. Here is the explanation of the JQuery code :
  1. var name = $(‘#name’).val(); : – here the $ is JQuery selector that uses to select any node in HTML whose identifier is passed as argument. If the identifier is a prefix with # that means it is a id of the HTML node. Here, $(‘#name’).val() contains the value of the HTML node whose is “name’. The text box in which user will enter her/his name is with is as name. so java script variable name will contain the name of the user.
  2. $.ajax() :- It is the method in $ variable of JQuery to call Ajax. It has five arguments here. First of all “type” which indicated the request type of Ajax. It can be POST or GET. Then, “url” which indicates the url to be hit of Ajax submission. “data” will contain the raw data to be sent to the server. “success” will contain the function code that has to be call if the request get success and server sends an response to the browser. “error” will contain the function code that has to be call if the request get any error.
  3. $(‘#info’).html(response); :- will set the response of the server in to the div. In this way “Hello” + name will be shown in the div whose id is “info“.
ShowUsers.jsp
Following are the code in ShowUsers.jsp to print all student information from a ArrayList to jsp page :
01<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
02pageEncoding="ISO-8859-1"%>
03<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
04<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
05<html>
06    <head>
07        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
08        <title>Users Added using Ajax</title>
09    </head>
10    <body style="color: green;">
11    The following are the users added in the list :<br>
12        <ul>
13            <c:forEach items="${Users}" var="user">
14                <li>Name : <c:out value="${user.name}" />; Education : <c:outvalue="${user.education}"/>
15            </c:forEach>
16        </ul>
17    </body>
18</html>
Here, we have used JSTL core taglib to iterate through the ArrayList and show every value in browser.
  • <c:forEach items=”${Users}” var=”user”> : tag is used for iterate through the ArrayList. Property “items” is used to define the bean on which the List object has been stored, so items=”${Users}” says that the users list is present in “Users” bean. “var” attribute says the name of the variable in which each user will be stored.
  • <c:out value=”${user.name}” /> : As, a single user will be stored in variable name “user” so to print the name property in User object we use ${user.name}.
app-config.xml
Our Spring MVC configuration file should be able to handle annotation driven controllers. The configuration are as follows :
01<?xml version="1.0" encoding="UTF-8"?>
06xsi:schemaLocation="
10 
11    <!-- Scans the classpath of this application for @Components to deploy as beans -->
12    <context:component-scan base-package="com.raistudies" />
13 
14    <!-- Configures the @Controller programming model -->
15    <mvc:annotation-driven />
16 
17    <!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
18    <bean id="viewResolver"class="org.springframework.web.servlet.view.InternalResourceViewResolver">
19        <property name="prefix" value="/WEB-INF/jsp/"/>
20        <property name="suffix" value=".jsp"/>
21    </bean>
22 
23</beans>
Deploy the war file to tomcat 6 and hit the url in browser, you will get following page displayed :

Fill student information :


After that click on “Add Users” button, you will get message that user has been added to the list :


To show all student added to the list click on the button “Show All Users”, you will get following page :


hat is all from Ajax using Spring MVC 3 and JQuery.