前言
对于很多JavaEE新手来说,如何使用Ajax来实现http请求,是件非常棘手的事情。今天我就这块给大家写一个简单的案例。我所写的案例都是经过我自身的一个测试,比较简单,希望能帮上大家。下面就是我的代码分解:
1、开发环境
jdk7.0+tomcat7.0+MyEclipse2014+MySql5.7
2、数据库表结构
/*
Navicat MySQL Data Transfer
Source Host : localhost:3306
Source Database : mybatis
Target Host : localhost:3306
Target Database : mybatis
Date: 2018-08-08 14:17:03
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) NOT NULL COMMENT '用户名称',
`password` varchar(255) DEFAULT NULL,
`birthday` date DEFAULT NULL COMMENT '生日',
`sex` char(1) DEFAULT NULL COMMENT '性别',
`address` varchar(256) DEFAULT NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', '王五', '123', '2014-07-10', '2', '西安市');
INSERT INTO `user` VALUES ('10', '张三', '123', '2014-07-10', '1', '北京市');
INSERT INTO `user` VALUES ('16', '张小明', '123', '2014-07-10', '1', '河南郑州');
INSERT INTO `user` VALUES ('22', '陈小明', '133', '2014-07-10', '1', '河南郑州');
INSERT INTO `user` VALUES ('24', '张三丰', '222', '2014-07-10', '1', '河南郑州');
INSERT INTO `user` VALUES ('25', '陈小明', '222', '2014-07-10', '1', '河南郑州');
INSERT INTO `user` VALUES ('26', '王五', '222', '2014-07-10', '2', '天津');
INSERT INTO `user` VALUES ('28', '赵四', '222', '2017-05-03', '1', '辽宁');
INSERT INTO `user` VALUES ('29', '小灰灰', '222', '2017-05-03', '2', '西安');
3、工程配置
在MyEclipse中新建JavaWeb工程“SSM_JSON_DEMO”,并进行如下配置:
3.1 工程结构
3.2、jar包管理
开发所涉及的jar,大家需要去官网下载,要求将下载的jar拷贝进工程的WEB-INF/lib文件夹下【自动关联】:
3.3、配置说明
src:该目录下主要存放java代码,其中:
- com.byzx.ssm.bean:管理java实体类;
- com.byzx.ssm.dao:持久层代码管理,主要完成对数据库的CRUD;
- com.byzx.ssm.service:业务层代码管理,主要完成相关的业务处理;
- com.byzx.ssm.action:控制层代码管理,主要完成模型跟视图之间的交互;
- com.byzx.ssm.test:一般用来进行单元测试;
config:该目录下主要存放配置文件,其中:
- db.properties:配置数据库的driver、url、username、password;
-
db.driver=com.mysql.jdbc.Driver db.url=jdbc\:mysql\://localhost\:3306/mybatis?characterEncoding\=utf-8 db.username=root db.password=root
- log4j.properties:配置框架日志输出;
#\u5B9A\u4E49LOG\u8F93\u51FA\u7EA7\u522B log4j.rootLogger=DEBUG,Console,File #\u5B9A\u4E49\u65E5\u5FD7\u8F93\u51FA\u76EE\u7684\u5730\u4E3A\u63A7\u5236\u53F0 log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.Target=System.out #\u53EF\u4EE5\u7075\u6D3B\u5730\u6307\u5B9A\u65E5\u5FD7\u8F93\u51FA\u683C\u5F0F\uFF0C\u4E0B\u9762\u4E00\u884C\u662F\u6307\u5B9A\u5177\u4F53\u7684\u683C\u5F0F log4j.appender.Console.layout = org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n #\u6587\u4EF6\u5927\u5C0F\u5230\u8FBE\u6307\u5B9A\u5C3A\u5BF8\u7684\u65F6\u5019\u4EA7\u751F\u4E00\u4E2A\u65B0\u7684\u6587\u4EF6 log4j.appender.File = org.apache.log4j.RollingFileAppender #\u6307\u5B9A\u8F93\u51FA\u76EE\u5F55 log4j.appender.File.File = logs/ssm.log #\u5B9A\u4E49\u6587\u4EF6\u6700\u5927\u5927\u5C0F log4j.appender.File.MaxFileSize = 10MB # \u8F93\u51FA\u6240\u4EE5\u65E5\u5FD7\uFF0C\u5982\u679C\u6362\u6210DEBUG\u8868\u793A\u8F93\u51FADEBUG\u4EE5\u4E0A\u7EA7\u522B\u65E5\u5FD7 log4j.appender.File.Threshold = ALL log4j.appender.File.layout = org.apache.log4j.PatternLayout log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
- mybatis-config.xml:主要进行mybatis框架的配置,我们一般会配置别名、mapper映射等。
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 给bean包起别名 --> <typeAliases> <package name="com.byzx.ssm.bean" /> </typeAliases> <!-- 搭建数据库环境交给spring执行 --> <!-- 映射配置 --> <mappers> <package name="com.byzx.ssm.dao" /> </mappers> </configuration>
- spring-beans.xml:spring框架配置文件,主要用来配置dataSource、sqlSessionFactory、MapperScannerConfigurer等。
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <!-- 引用外部db文件 --> <context:property-placeholder location="classpath:db.properties" /> <!-- 1、配置db的数据源引用mybatis-config.xml --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${db.driver}"></property> <property name="url" value="${db.url}"></property> <property name="username" value="${db.username}"></property> <property name="password" value="${db.password}"></property> <property name="maxActive" value="10"></property> <property name="maxIdle" value="5"></property> </bean> <!-- 2、配置sqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 配置数据库:连接数据源 --> <property name="dataSource" ref="dataSource"></property> <!-- 关联配置mybati-config.xml --> <property name="configLocation" value="classpath:mybatis-config.xml"></property> </bean> <!-- 3、配置sqlSession --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 关联外部的sqlSessionFactory 创建sqlSession --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> <!-- 配置和sqlSession关联的Dao接口 --> <property name="basePackage" value="com.byzx.ssm.dao"></property> </bean> <!-- 通过扫描包的方式配置service --> <context:component-scan base-package="com.byzx.ssm.service"></context:component-scan> </beans>
- springmvc.xml:springmvc框架配置文件,主要用来配置我们自身的Controller和视图解析器等。
-
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <!-- 使用 mvc:annotation-driven代替注解映射器和注解适配器配置 mvc:annotation-driven默认加载很多的参数绑定方法, 比如json转换解析器就默认加载了,如果使用mvc:annotation-driven不用配置上边的RequestMappingHandlerMapping和RequestMappingHandlerAdapter 实际开发时使用mvc:annotation-driven --> <mvc:annotation-driven> <mvc:message-converters register-defaults="false"> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 配置controller的一个扫包,后续通过注解标签来管理类 --> <context:component-scan base-package="com.byzx.ssm.action"></context:component-scan> <!-- 配置视图解析器 进行jsp解析,默认使用jstl标签,classpath下得有jstl的包 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 前缀 --> <property name="prefix" value="/WEB-INF/jsp/" /> <!-- 后缀 --> <property name="suffix" value=".jsp" /> </bean> <!-- 配置json --> <!-- <bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="jsonConverter" /> </list> </property> </bean> --> </beans>
- spring-tx.xml:主要用来配置数据库事物,在service层的实现类添加@Transactional即可。
-
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <!-- 事务管理器 对mybatis操作数据库事务控制,spring使用jdbc的事务控制类 --> <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager"> <!-- 数据源 dataSource在applicationContext-dao.xml中配置了 --> <property ref="dataSource" name="dataSource" /> </bean> <!--使用基于注解方式配置事务 --> <tx:annotation-driven transaction-manager="transactionManager" /> <!-- 通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 传播行为 --> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="find*" propagation="SUPPORTS" read-only="true" /> <tx:method name="query*" propagation="SUPPORTS" read-only="true" /> <tx:method name="get*" propagation="SUPPORTS" read-only="true" /> <tx:method name="select*" propagation="SUPPORTS" read-only="true" /> </tx:attributes> </tx:advice> <!-- 要扫描的service包 --> <aop:config> <aop:advisor pointcut="execution(* com.byzx.ssm.service.impl.*.*(..))" advice-ref="txAdvice" /> </aop:config> </beans>
最后我们再来配置一下工程WEB-INF下的web.xml文件:
-
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>SSM_JSON_DEMO</display-name> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list> <!-- 配置spring容器,也就是配置:spring-beans.xml等 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 配置前端控制器,也就是配置:springmvc.xml进来 --> <servlet> <servlet-name>SSM_JSON_DEMO</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <!-- 配置拦截器 --> <servlet-mapping> <servlet-name>SSM_JSON_DEMO</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> <!-- 解决数据库响应中文乱码的问题,主要是针对post请求的数据 --> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
写到这里,文件配置算是完成了,接下来我们将进入到编码阶段。
- User.java
在com.byzx.ssm.bean下新建User.java,要求跟数据库表字段一一对应(我们案例中使用的是resultType),示例如下: -
package com.byzx.ssm.bean; import java.io.Serializable; import java.util.Date; /** * pojo类,需要跟对应表的字段映射【名字一致,类型基本一致】 * * @author guigu2012 * */ public class User implements Serializable{ private static final long serialVersionUID = -6384316775494692203L; private int id;//用戶ID private String username;//用户名称 private Date birthday;//生日 private String sex;//性别 private String address;//住址 private String password;//密码 public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "User [id=" + id + ", username=" + username + ", birthday=" + birthday + ", sex=" + sex + ", address=" + address + ", password=" + password + "]"; } }
- UserDao.java
在com.byzx.ssm.dao下新建UserDao.java,主要对外提供操作数据库的接口,示例如下: -
package com.byzx.ssm.dao; import com.byzx.ssm.bean.User; public interface UserDao { /** * 登录用户 * @return */ public User login(User u); }
- UserDao.xml
在com.byzx.ssm.dao下新建UserDao.xml,主要用来配置对数据库的操作,示例如下:<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.byzx.ssm.dao.UserDao"> <!-- 登录用户 --> <select id="login" parameterType="User" resultType="User"> select * from user where username = #{username} and password = #{password} </select> </mapper>
dao层的配置完成了,这一层就是对数据库进行相应的增删改查操作,并提供相关的接口给外部使用。接下来我们来完成service层中代码的设计。
- IUserService.java
在com.byzx.ssm.service下新建IUserService.java,主要用来提供service对外访问接口,示例代码如下:package com.byzx.ssm.service; import com.byzx.ssm.bean.User; public interface IUserService { /** * 登录用户 * @return */ public User login(User u); }
- UserService.java
在com.byzx.ssm.service.impl下新建UserService.java,实现IUserService接口,主要完成对dao层的访问以及对相关业务的处理,示例代码如下: -
package com.byzx.ssm.service.impl; 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.byzx.ssm.bean.User; import com.byzx.ssm.dao.UserDao; import com.byzx.ssm.service.IUserService; @Service @Transactional public class UserService implements IUserService { @Autowired private UserDao userDao; @Override @Transactional(propagation = Propagation.NOT_SUPPORTED)//如果是查询,事务挂起 public User login(User u) { // TODO Auto-generated method stub return userDao.login(u); } }
-
App.java
在com.byzx.ssm.test下新建App.java,单元测试类,主要是对到层的功能进行相关测试,示例代码如下: -
package com.byzx.ssm.test; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.byzx.ssm.bean.User; import com.byzx.ssm.service.IUserService; public class App { @Test public void findUsers(){ ApplicationContext context = new ClassPathXmlApplicationContext("spring-bean.xml"); IUserService userService = (IUserService) context.getBean("userService"); User u = new User(); u.setUsername("王五"); u.setPassword("123"); User user =userService.login(u); System.out.println(user.toString()); } }
service层完成并经过了单元测试。在此,service层主要负责跟dao层进行交互,并进行相关业务逻辑的处理。同时提供接口给controller层进行访问,那么接下来我们进行controller层代码的设计。
- UserController.java
在com.byzx.ssm.controller下新建UserController.java,主要负责模型(service)和视图(jsp)的交互,代码示例如下:package com.byzx.ssm.action; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.byzx.ssm.bean.User; import com.byzx.ssm.service.IUserService; @Controller public class UserController { @Autowired private IUserService userService; /** * 登录 * @param user */ @RequestMapping("login") @ResponseBody public User login(@RequestBody User user){//使用@RequestBody Map<String,String> map也是可以的,接收前台传过来的参数 //返回用户信息,要使用@ResponseBody将返回值转换为JSON return userService.login(user); } }
所有的代码设计到这里就完成了,接下来我们来看下jsp界面的设计。
- login.jsp
这是关于登录界面的设计,我引用了bootstrap框架和JQuery框架【大家自行去网上下载】:
示例代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>登录</title>
<script src="bootstrap-3.3.7-dist/js/bootstrap.js"></script>
<script src="bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
<script src="js/jquery-1.8.0.min.js"></script>
<script src="js/jquery-1.8.0.js"></script>
<link rel="stylesheet" type="text/css"
href="bootstrap-3.3.7-dist/css/bootstrap.css" />
<link rel="stylesheet" type="text/css"
href="bootstrap-3.3.7-dist/css/bootstrap.min.css" />
<style type="text/css">
td {
padding: 10px;
}
</style>
<script type="text/javascript">
var state = 0;//默认登录成功
$(document).ready(
function() {
//登录
$("#login").click(
function() {
$.ajax({
url : "login.action",
type : "POST",
/* data : "json", */
contentType : "application/json;charset=utf-8",
//向后端传输的数据
data : JSON.stringify({
username : $("#username").val(),
password : $("#password").val(),
}),
//处理后端返回的数据
success : function(result) {
//将得到的前台数据转换为json
/*var message = JSON.stringify(result);*/
alert("接受到的数据是:" + result);//输出默认的json字符串
if (result != null && result != "") {
var message = eval("(" + result + ")");//万能转换,拿到对象
//alert("接受到的数据是:" + message.username);
var username = message.username;
var password = message.password;
//在前台做验证
if (username != null && username != ""
&& password != null
&& password != "") {
alert("用户登录成功");
window.location.href="findUser.action";
} else {
alert("用户登录失败");
}
}else{
alert("用户登录失败");
}
//alert("接受到的数据是:" + message);
},
//处理失败返回的数据
error : function(result) {
alert("用户登录失败");
}
});
});
});
</script>
</head>
<body>
<form action="${pageContext.request.contextPath }/user/login.action"
method="post">
<div class="panel panel-default" style="width:400px; margin:40px auto">
<div class="panel-heading"
style="text-align:center;font-weight:bold;">用户登录</div>
<div class="panel-body">
<table style="width: 100%;">
<tr>
<td style="width: 30%; ">用户名:</td>
<td style="width: 70%; "><input type="text"
class="form-control" id="username" placeholder="请输入用户名"></td>
</tr>
<tr>
<td style="width: 30%; ">密 码:</td>
<td style="width: 70%; "><input type="password"
class="form-control" id="password" placeholder="请输入密码"></td>
</tr>
<tr>
<td colspan="2" style="text-align:center;">
<button type="button" class="btn btn-primary"
data-toggle="button" id="register">注册</button>
<button type="button" class="btn btn-primary"
data-toggle="button" id="login">登录</button>
</td>
</tr>
</table>
</div>
</div>
</form>
</body>
</html>
好了,ssm项目中如何使用ajax实现http请求响应的例子就到这里了,对于get请求和post请求差不多,大家可以借助官方文档进行相关学习。
4、部署项目
输入地址:http:// localhost:8080/SSM_JSON_DEMO/
5、附录
Bootstrap学习推荐网站:http://www.runoob.com/bootstrap/bootstrap-tutorial.html
JQuery学习推荐网站:http://www.runoob.com/jquery/jquery-tutorial.html