简单的JQuery(AJAX)+SpringMVC的小例子(JSON)

简单的JQuery(AJAX)+SpringMVC的小例子,实现将对象以JSON的形式返回给页面。
(本例包含一个HelloWorld,一个表单参数传递,一个JSON实例)
如有时间可以在[url]http://www.verycd.com/topics/2917293/[/url]下载相关视频。

目录结构:
[img]http://dl.iteye.com/upload/attachment/0069/1516/0798fe11-d11b-35dd-b1bd-4567ec0dffb4.jpg[/img]

1.相关Jar包的引入,spring的jar包,jstl的jar包特别是jaskson相关的两个jar包

2.web.xml配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springmvc-servlet.xml</param-value>
</context-param>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

</web-app>


2.根据web.xml的配置,创建对应的xxxx-servlet.xml文件
这里是springmvc-servlet.xml
<?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:tx="http://www.springframework.org/schema/tx"
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-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<context:component-scan base-package="com.mvc"></context:component-scan>
<mvc:annotation-driven />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>

</beans>

3.Model类的编写

public class Shop {

String name;

String staffName[];
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String[] getStaffName() {
return staffName;
}
public void setStaffName(String[] staffName) {
this.staffName = staffName;
}
public Shop() {
}

}


4.Controller的编写
@Controller
public class JSONController {

@RequestMapping(value="/json", method = RequestMethod.GET)
public @ResponseBody Shop getShopInJSON() {

//测试数据
Shop shop = new Shop();
System.out.println("Shop");
shop.setName("Eric");
shop.setStaffName(new String[]{"mkyong1", "mkyong2"});

return shop;

}

}


5.jsp中的ajax代码:
<script type="text/javascript" src="jquery-1.7.2.min.js">
</script>
<script type="text/javascript">
$(function() {
getjson();
});

function getjson() {
$.ajax( {
type : "get",
url : "json.do",
dataType:"json",
success : function(msg) {
alert("Data Saved: " + msg.name+"--"+msg.staffName);
}
});
}
</script>


6.部署调试网页弹出信息。
以下是项目源码以及所需jar包
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这里提供一个简单的示例,实现基于 Spring MVC 和 Ajax 的表格查询功能,使用的前端框架是 layui 数据表格,数据库使用的是 MySQL。 1. 在 pom.xml 文件中添加以下依赖: ```xml <!-- Spring MVC --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- Jackson JSON --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <!-- MySQL JDBC --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> ``` 2. 在 Spring 配置文件中添加以下配置: ```xml <!-- 数据源配置 --> <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/test" /> <property name="username" value="root" /> <property name="password" value="password" /> </bean> <!-- MyBatis 配置 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="typeAliasesPackage" value="com.example.model" /> <property name="mapperLocations" value="classpath*:com/example/mapper/*.xml" /> <property name="configLocation" value="classpath:mybatis-config.xml" /> </bean> <!-- MyBatis Mapper 扫描 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.example.mapper" /> </bean> <!-- 开启 Spring MVC 注解支持 --> <annotation-driven/> <!-- 静态资源处理 --> <mvc:resources mapping="/static/**" location="/static/" /> <!-- 视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> ``` 3. 在 Spring MVC 配置文件中添加以下配置: ```xml <!-- 开启注解驱动 --> <mvc:annotation-driven /> <!-- 配置处理器映射器 --> <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" /> <!-- 配置控制器 --> <bean name="/ajaxTable" class="com.example.controller.AjaxTableController" /> <!-- 配置 AJAX 返回值处理器 --> <bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView" /> ``` 4. 创建一个实体类 User,对应 MySQL 数据库中的 user 表: ```java public class User { private Long id; private String username; private String email; private String phone; // getter 和 setter 方法省略 } ``` 5. 创建一个 DAO 接口 UserMapper,使用 MyBatis 进行数据库操作: ```java public interface UserMapper { List<User> selectByCondition(Map<String, Object> condition); } ``` 6. 创建一个控制器 AjaxTableController,实现搜索功能: ```java @Controller public class AjaxTableController { @Autowired private UserMapper userMapper; @RequestMapping("/ajaxTable") public ModelAndView ajaxTable() { return new ModelAndView("ajaxTable"); } @RequestMapping("/ajaxTable/search") @ResponseBody public Map<String, Object> search(HttpServletRequest request) { Map<String, Object> result = new HashMap<>(); String username = request.getParameter("username"); String email = request.getParameter("email"); String phone = request.getParameter("phone"); Map<String, Object> condition = new HashMap<>(); condition.put("username", username); condition.put("email", email); condition.put("phone", phone); List<User> userList = userMapper.selectByCondition(condition); result.put("code", 0); result.put("msg", ""); result.put("count", userList.size()); result.put("data", userList); return result; } } ``` 7. 创建一个 JSP 页面 ajaxTable.jsp,使用 layui 数据表格展示数据: ```html <!doctype html> <html> <head> <meta charset="UTF-8"> <title>Ajax Table</title> <link rel="stylesheet" href="/static/layui/css/layui.css"> </head> <body> <div class="layui-container"> <div class="layui-row layui-col-space15"> <div class="layui-card"> <div class="layui-card-body"> <form class="layui-form layui-form-pane" lay-filter="table-search"> <div class="layui-form-item layui-inline"> <label class="layui-form-label">Username</label> <div class="layui-input-inline"> <input type="text" name="username" class="layui-input" autocomplete="off"> </div> </div> <div class="layui-form-item layui-inline"> <label class="layui-form-label">Email</label> <div class="layui-input-inline"> <input type="text" name="email" class="layui-input" autocomplete="off"> </div> </div> <div class="layui-form-item layui-inline"> <label class="layui-form-label">Phone</label> <div class="layui-input-inline"> <input type="text" name="phone" class="layui-input" autocomplete="off"> </div> </div> <div class="layui-form-item"> <div class="layui-input-inline"> <button class="layui-btn" type="button" lay-submit lay-filter="table-search-btn">Search</button> <button class="layui-btn layui-btn-primary" type="reset">Reset</button> </div> </div> </form> </div> </div> <div class="layui-card"> <div class="layui-card-body"> <table id="userTable" lay-filter="userTable"></table> </div> </div> </div> </div> <script src="/static/layui/layui.js"></script> <script> layui.use(['table', 'form'], function () { var table = layui.table; var form = layui.form; table.render({ elem: '#userTable', url: '/ajaxTable/search', method: 'post', page: true, cols: [[ {field: 'id', title: 'ID', width: 80}, {field: 'username', title: 'Username', width: 120}, {field: 'email', title: 'Email', width: 200}, {field: 'phone', title: 'Phone', width: 120} ]] }); form.on('submit(table-search-btn)', function (data) { table.reload('userTable', { where: data.field }); return false; }); }); </script> </body> </html> ``` 通过访问 `/ajaxTable` 页面即可看到一个带搜索功能的数据表格。用户输入搜索条件后,点击搜索按钮即可实现异步请求,后台根据条件查询数据库,将查询结果返回给前端,前端使用 layui 数据表格展示数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值