`
xiaofeng_dream
  • 浏览: 6048 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

spring mvc + jquery + json + ajax的实现

    博客分类:
  • java
阅读更多
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 :

    First of all, we will create a domain class (User.java) that will hold the value of student information.
    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.
    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.
    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 :




package com.raistudies.domain;


public class User {


    private String name = null;

    private String education = null;

    // Getter and Setter are omitted for making the code short

}







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 :


package com.raistudies.controllers;


import java.util.ArrayList;

import java.util.List;


import org.springframework.stereotype.Controller;

import org.springframework.ui.ModelMap;

import org.springframework.validation.BindingResult;

import org.springframework.web.bind.annotation.ModelAttribute;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.ResponseBody;


import com.raistudies.domain.User;


@Controller

public class UserListController {

    private List<User> userList = new ArrayList<User>();


    @RequestMapping(value="/AddUser.htm",method=RequestMethod.GET)

    public String showForm(){

        return "AddUser";

    }


    @RequestMapping(value="/AddUser.htm",method=RequestMethod.POST)

    public @ResponseBody String addUser(@ModelAttribute(value="user") User user, BindingResult result ){

        String returnText;

        if(!result.hasErrors()){

            userList.add(user);

            returnText = "User has been added to the list. Total number of users are " + userList.size();

        }else{

            returnText = "Sorry, an error has occur. User has not been added to list.";

        }

        return returnText;

    }


    @RequestMapping(value="/ShowUsers.htm")

    public String showUsers(ModelMap model){

        model.addAttribute("Users", userList);

        return "ShowUsers";

    }

}


AddUser.jsp“addUsers” is same as the controller method that handle form expect that it also contain annotation@ResponseBody, which tells Spring 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 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 :



<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<!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=ISO-8859-1">

        <title>Add Users using ajax</title>

        <script src="/AjaxWithSpringMVC2Annotations/js/jquery.js"></script>

        <script type="text/javascript">

        function doAjaxPost() {

        // get the form values

        var name = $('#name').val();

        var education = $('#education').val();


        $.ajax({

        type: "POST",

        url: "/AjaxWithSpringMVC2Annotations/AddUser.htm",

        data: "name=" + name + "&education=" + education,

        success: function(response){

        // we have the response

        $('#info').html(response);

        $('#name').val('');

        $('#education').val('');

        },

        error: function(e){

        alert('Error: ' + e);

        }

        });

        }

        </script>

    </head>

    <body>

        <h1>Add Users using Ajax ........</h1>

        <table>

            <tr><td>Enter your name : </td><td> <input type="text" id="name"><br/></td></tr>

            <tr><td>Education : </td><td> <input type="text" id="education"><br/></td></tr>

            <tr><td colspan="2"><input type="button" value="Add Users" onclick="doAjaxPost()"><br/></td></tr>

            <tr><td colspan="2"><div id="info" style="color: green;"></div></td></tr>

        </table>

        <a href="/AjaxWithSpringMVC2Annotations/ShowUsers.htm">Show All Users</a>

    </body>

</html>


ShowUsers.jsp

Following are the code in ShowUsers.jsp to print all student information from a ArrayList to jsp page :




<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<%@ 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=ISO-8859-1">

        <title>Users Added using Ajax</title>

    </head>

    <body style="color: green;">

    The following are the users added in the list :<br>

        <ul>

            <c:forEach items="${Users}" var="user">

                <li>Name : <c:out value="${user.name}" />; Education : <c:out value="${user.education}"/>

            </c:forEach>

        </ul>

    </body>

</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, soitems=”${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 :




<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:mvc="http://www.springframework.org/schema/mvc"

xsi:schemaLocation="

http://www.springframework.org/schema/beans� �  � http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd

http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">


    <!-- Scans the classpath of this application for @Components to deploy as beans -->

    <context:component-scan base-package="com.raistudies" />


    <!-- Configures the @Controller programming model -->

    <mvc:annotation-driven />


    <!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">

        <property name="prefix" value="/WEB-INF/jsp/"/>

        <property name="suffix" value=".jsp"/>

    </bean>


</beans>


Deploy the war file to tomcat 6 and hit the url in browser, you will get following page displayed :

Ajax Form Using Spring MVC 3

Fill student information :
Ajax Filled Form Using Spring MVC 3

Ajax Filled Form Using Spring MVC 3

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

Ajax Form Submission Confirmation Spring MVC 3

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

Show All Users Spring MVC 3

That is all from Ajax using Spring MVC 3 and JQuery. You can download source from bellow link.


原文地址:http://www.raistudies.com/spring/spring-mvc/ajax-spring-mvc-3-annonations-jquery/
分享到:
评论

相关推荐

    【项目原型】spring+spring mvc+mybatis+shiro+maven+bootstrap+ajax+json+分页+逆向工程

    【项目原型】spring+spring mvc+mybatis+shiro+maven+bootstrap+ajax+json+分页+逆向工程 包含现在最流行的技术框架,快速部署各种应用,加入shiro权限框架,安全,美观,你值得拥有

    Spring Boot + MyBatis + thymeleaf + MySQL + jQuery +ajax图书借阅管理系统

    本系统以“Spring Boot + MyBatis + thymeleaf + MySQL + jQuery + ajax”为核心技术栈,构建了一个轻量级、易维护的图书借阅管理系统,旨在提供一套完整且实用的图书管理解决方案。 首先,Spring Boot作为Java领域...

    struts2+spring+hibernate+jquery+json

    Struts2、Spring、Hibernate、jQuery 和 JSON 是五个在IT行业中极为重要的技术组件,它们各自在Web应用开发中扮演着不同的角色。这篇文章将详细介绍这些技术的整合使用以及它们的功能。 首先,Struts2 是一个基于 ...

    Spring+Spring mvc+Hibernate+Bootstrap、企业级员工信息管理系统

    Spring mvc 返回数据格式采用统一的对象(JSONReturn)进行封装 09. 通过自定义处理器 ExceptionIntercept 实现 Spring mvc的全局异常捕获 10. 系统中包含了企业中采用的开发工具类的集合 11. AbstractDao 父类...

    SSH+jQuery+json 实现的Ajax操作,绝对精华,代码简练清晰,绝对能看明白

    这个压缩包中的资源,"SSH+jQuery+json 实现的Ajax操作,绝对精华,代码简练清晰,绝对能看明白",显然提供了一个使用这些技术实现Ajax级联操作的实例。下面将详细介绍这些技术及其在Ajax操作中的应用。 **SSH ...

    spring mvc+jquery easyui CRUD

    在本项目中,我们主要探讨的是如何利用Spring MVC框架与jQuery EasyUI库来实现一个基本的CRUD(创建、读取、更新、删除)功能。Spring MVC是Java平台上的一个强大的MVC(Model-View-Controller)框架,它提供了一个...

    springmvc + jquery + ajax + json 异步传递数据

    SpringMVC、jQuery、Ajax和JSON这四个技术的结合,为开发者提供了一种高效且灵活的方式来实现这一功能。接下来,我们将深入探讨这些技术以及它们如何协同工作。 SpringMVC是Spring框架的一部分,是一个强大的MVC...

    Spring + Hibernate + Spring mvc +Ajax 整合

    在Spring MVC中,可以通过配置Ajax处理器或使用jQuery等库来实现Ajax请求。这样,用户可以进行数据的增删查改,而界面保持不刷新,提升了交互性。 在给定的"Spring + Hibernate + Spring mvc +Ajax 整合"项目中,...

    spring mvc+ajax

    将Spring MVC与Ajax结合使用,可以实现页面的异步更新,提升用户体验,同时保持服务器负载均衡。 首先,我们需要理解Spring MVC的基本工作流程。当用户发起请求时,Spring MVC的DispatcherServlet会拦截这个请求,...

    struts2+spring+hibernate+jquery+dwr+json

    标题 "struts2+spring+hibernate+jquery+dwr+json" 描述了一个集成的Web应用程序开发框架,其中包含了多个关键技术和库。这个框架旨在提高开发效率,提供灵活的数据管理,以及用户友好的前端交互。 1. Struts2:...

    ssh2+ajax+jquery+json 登陆验证

    根据提供的文件信息,本文将详细解析“ssh2+ajax+jquery+json 登陆验证”的实现原理及技术要点。本文将围绕SSH2框架、Ajax、jQuery和JSON这些技术展开讨论,并结合给定的部分内容来深入分析如何利用这些技术进行...

    struts2+spring+ibatis+jquery+json

    Struts2、Spring、iBatis和jQuery是四个在Java Web开发中广泛应用的框架和技术,它们共同构建了一个高效、灵活的后端系统,并通过JSON进行数据交互。下面将详细阐述这些技术及其相互间的整合。 **Struts2** 是一个...

    Spring mvc+Ajax用户登录增删改查功能

    **Spring MVC + Ajax 用户登录增删改查功能详解** 在Web开发中,Spring MVC和Ajax是两种非常重要的技术。Spring MVC作为Spring框架的一部分,提供了一种模型-视图-控制器的架构模式,使得开发者能够更好地组织和...

    SSH+Ajax+JSON省市级联效果Spring+Struts+Hibernate+Jquery

    SSH+Ajax+JSON在Web开发中的应用主要集中在构建动态、响应迅速的用户界面,这里我们主要探讨Spring、Struts、Hibernate这三大框架如何与Ajax和JSON技术结合,以实现省市级联选择的效果。 首先,Spring是Java企业级...

    省市级联(采用技术==Struts+Hibernate+Spring+Jquery+Json)

    标题 "省市级联(采用技术==Struts+Hibernate+Spring+Jquery+Json)" 描述了一个基于Web的开发项目,该项目使用了多种技术来实现省市级联的动态下拉选择功能。在这个系统中,用户在选择省份后,城市列表会根据所选...

    简单的SSH+JQuery+JSON例子

    SSH指的是Struts、Spring和Hibernate这三个Java Web开发框架的缩写,而JQuery是一个强大的JavaScript库,JSON则是一种轻量级的数据交换格式。下面我们将详细探讨这些技术及其在实际项目中的应用。 首先,Struts是...

    spring mvc+ajax 文件上传

    本示例探讨的是如何利用Spring MVC后端框架与前端的Ajax技术来实现高效的文件上传,相较于传统的表单提交方式,这种方法具有无刷新、用户体验更佳的优势。以下是关于这个主题的详细讲解。 首先,我们需要理解Spring...

    Spring+SpringMVC+MyBatis+Maven+EasyUI+Ajax+Json OA项目实例

    本文将深入探讨如何利用Spring、SpringMVC、MyBatis、Maven、EasyUI、Ajax和Json技术,构建一个高效的企业级办公自动化(OA)项目实例。这个项目以"eyou"为名,体现了SSM框架在实际应用中的强大功能以及现代Web开发...

    SpringMVC+JSON+mybatis+jQuery+Ajax+Maven做的无刷新登录,注册,修改密码以及校验并且赋有详细注释,以及增删改查功能

    注:此项目是用IntelliJ IDEA 13.1.3此软件编写而成,不过和myeclipse都差不多,本项目包含SpringMVC+JSON+mybatis+jQuery+Ajax+Maven做的无刷新登录,注册,修改密码,拦截器,如果用户没有登录则不能进行相应操作...

Global site tag (gtag.js) - Google Analytics