Ajax应用举例
一.异步校验用户名
1.页面
2.html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户注册</title>
</head>
<body>
<div>
<span>会员注册</span>USER REGISTER
<form class="form-horizontal" style="margin-top: 5px;">
<table>
<tr>
<td>用户名</td>
<td>
<input type="text" id="username" name="username" placeholder="请输入用户名">
<span id="usernameInfo"></span>
</td>
</tr>
<tr>
<td>密码</td>
<td>
<input type="password" placeholder="请输入密码">
</td>
</tr>
</table>
<input type="submit" value="注册"/>
</form>
</div>
<script src="./js/jquery-3.3.1.min.js"></script>
<script>
$("#username").change(function () {
var params = "action=isExist&name=" + this.value;
//发Ajax请求到服务端,判断用户名是否存在
$.post("user",params,function(result){
//result的值是字符串。如果存在就是"true";否则就是"false"
if (result === "true") {//用户名已存在,不可用
$("#usernameInfo").html("用户名已存在").css("color","red");
}else{
$("#usernameInfo").html("用户名可用").css("color","green");
}
},"text");
});
</script>
</body>
</html>
二.异步校验搜索填充
1.页面
2.html代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
.content{
width:643px;
margin:50px auto;
text-align: center;
}
input[type='text']{
width:530px;
height:40px;
font-size: 14px;
}
input[type='button']{
width:100px;
height:46px;
background: #38f;
border: 0;
color: #fff;
font-size: 15px
}
.result{
/*position: absolute;*/
width: 535px;
border: 1px solid #999;
border-top: 0;
display: none;
}
.result div:hover{
background-color: #ccc;
cursor: pointer;
}
</style>
</head>
<body>
<div class="content">
<img alt="" src="img/logo.png"><br/><br/>
<input type="text" name="word" id="searchWord">
<input type="button" value="搜索一下">
<div class="result"></div>
</div>
<script type="text/javascript" src="./js/jquery-3.3.1.js"></script>
<script type="text/javascript">
$("#searchWord").keyup(function () {
//如果搜索框里没有值,不需要发Ajax进行查询
if (this.value === "") {
//隐藏结果列表
$(".result").hide();
return;
}
var params = "action=search&name=" + this.value;
//发Ajax请求,搜索用户,把搜索结果显示出来
$.post("user",params,function(result){
//清除之前的结果
$(".result").empty();
//如果搜索结果了,就循环遍历显示出来
if (result !== null && result.length > 0) {
//result = [{"id":1,"name":"张三","password":"123"},{},{},...]
for(var user of result){
//user: {"id":1,"name":"张三","password":"123"}
$("<div></div>").html(user.name).appendTo(".result");
}
$(".result").show();
}else{
//没有搜索到结果,隐藏结果列表
$(".result").hide();
}
},"json");
});
$(".result").on("click","div",function(){
//alert(this.innerHTML);
//把当前元素的内容,设置到搜索框里
$("#searchWord").val(this.innerHTML);
//把结果列表隐藏掉
$(".result").hide();
});
</script>
</body>
</html>
三.后端代码实现
项目结构
1.web层
1.1 filter
@WebFilter(filterName = "EncodingFilter",urlPatterns = "/*")
public class EncodingFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
//在放行之前,解决请求和响应的中文乱码
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
chain.doFilter(request, response);
}
public void init(FilterConfig config) throws ServletException {
}
}
1.2 servlet
@WebServlet(urlPatterns = "/user", name = "UserServlet")
public class UserServlet extends HttpServlet {
private UserService userService = new UserService();
public void search(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.接收参数
String name = request.getParameter("name");
//2.封装实体:略
//3.完成功能
List<User> userList = userService.search(name);
//4.处理结果
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(userList);
response.getWriter().print(json);
}
public void isExist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.接收参数
String name = request.getParameter("name");
//2.封装实体:略
//3.完成功能
boolean isExist = userService.isExist(name);
//4.处理结果
response.getWriter().print(isExist);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//接收参数action:是要执行的方法名称
String action = request.getParameter("action");
//反射执行名称为action的方法
Class clazz = this.getClass();
Method method = clazz.getMethod(action, HttpServletRequest.class, HttpServletResponse.class);
method.invoke(this, request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
2.service层
public class UserService {
private UserDao dao = new UserDao();
/**
* 判断数据库里name是否存在
* @param name
* @return
* 存在,则返回true;不存在,则返回false
*/
public boolean isExist(String name) {
User user = dao.findByName(name);
return user!=null;
}
public List<User> search(String name) {
return dao.search(name);
}
}
3.dao层
public class UserDao {
private JdbcTemplate jdbcTemplate = new JdbcTemplate(JdbcUtils.getDataSource());
public User findByName(String name) {
User user = null;
try {
user = jdbcTemplate.queryForObject("select * from user where name = ?", new BeanPropertyRowMapper<>(User.class), name);
} catch (EmptyResultDataAccessException e) {
System.out.println("找不到用户User[name="+name+"]");
}
return user;
}
public List<User> search(String name) {
return jdbcTemplate.query("select * from user where name like ?", new BeanPropertyRowMapper<>(User.class), "%" +name+"%");
}
}
4.util
4.1 jdbcUtils
public class JdbcUtils {
/**c3p0连接池被创建时,会自动从src下加载c3p0-config.xml*/
private static DataSource dataSource = new ComboPooledDataSource();
/**
* 获取连接
*/
public static Connection getConnection() throws Exception {
//获取连接
Connection connection = dataSource.getConnection();
return connection;
}
/**
* 释放资源
*/
public static void close(ResultSet resultSet, Statement statement, Connection connection){
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static DataSource getDataSource() {
return dataSource;
}
}
4.2 beanUtils
package com.itheima.util;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
public class BeanUtils {
/**
* 封装实体<br>
* 再次封装BeanUtils.populate方法,提供更简单的操作<br/>
* 使用示例:<br>
* User user = BeanUtil.populate(map, User.class);
* @param properties Map keyed by property name, with the corresponding (String or String[]) value(s) to be set
* @param clazz The class of JavaBean whose properties are being populated
* @return 封装后的JavaBean实例
*/
public static <T> T populate(Map<?,?> properties, Class<T> clazz){
T instance = null;
try {
instance = clazz.newInstance();
org.apache.commons.beanutils.BeanUtils.populate(instance, properties);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return instance;
}
}
5.domain
public class User {
private Integer id;
private String name;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}