对于很多JavaEE新手来说,如何使用Ajax来实现http请求,是件非常棘手的事情。今天我就这块给大家写一个简单的案例。我所写的案例都是经过我自身的一个测试,比较简单,希望能帮上大家。下面就是我的代码分解:
jdk7.0+tomcat7.0+MyEclipse2014+MySql5.7
/*
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', '西安');
在MyEclipse中新建JavaWeb工程“SSM_JSON_DEMO”,并进行如下配置:
开发所涉及的jar,大家需要去官网下载,要求将下载的jar拷贝进工程的WEB-INF/lib文件夹下【自动关联】:
src:该目录下主要存放java代码,其中:
config:该目录下主要存放配置文件,其中:
db.driver=com.mysql.jdbc.Driver
db.url=jdbc\:mysql\://localhost\:3306/mybatis?characterEncoding\=utf-8
db.username=root
db.password=root
#\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
text/html;charset=UTF-8
application/json;charset=UTF-8
最后我们再来配置一下工程WEB-INF下的web.xml文件:
SSM_JSON_DEMO
login.jsp
contextConfigLocation
classpath:spring-*.xml
org.springframework.web.context.ContextLoaderListener
SSM_JSON_DEMO
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:springmvc.xml
SSM_JSON_DEMO
*.action
characterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
forceEncoding
true
characterEncodingFilter
/*
写到这里,文件配置算是完成了,接下来我们将进入到编码阶段。
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 + "]";
}
}
package com.byzx.ssm.dao;
import com.byzx.ssm.bean.User;
public interface UserDao {
/**
* 登录用户
* @return
*/
public User login(User u);
}
dao层的配置完成了,这一层就是对数据库进行相应的增删改查操作,并提供相关的接口给外部使用。接下来我们来完成service层中代码的设计。
package com.byzx.ssm.service;
import com.byzx.ssm.bean.User;
public interface IUserService {
/**
* 登录用户
* @return
*/
public User login(User u);
}
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层代码的设计。
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 map也是可以的,接收前台传过来的参数
//返回用户信息,要使用@ResponseBody将返回值转换为JSON
return userService.login(user);
}
}
所有的代码设计到这里就完成了,接下来我们来看下jsp界面的设计。
示例代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
登录
好了,ssm项目中如何使用ajax实现http请求响应的例子就到这里了,对于get请求和post请求差不多,大家可以借助官方文档进行相关学习。
输入地址:http:// localhost:8080/SSM_JSON_DEMO/
Bootstrap学习推荐网站:http://www.runoob.com/bootstrap/bootstrap-tutorial.html
JQuery学习推荐网站:http://www.runoob.com/jquery/jquery-tutorial.html