案例需求:
1`.实时从文本框获取内容.
2. 与数据库比对拿到的内容.
3. 将结果显示在前端页面.
用到的知识点:
1. JQuery, JS, Ajax.
2. 反射,servlet,tomcat.
3. 三层架构和MVC模式.
4. Jdbc,mysql
实现需求:
一:实时从文本框获取内容:
① 页面展示代码:
<body>
<form >
<div>
<font>会员注册</font>USER REGISTER<br>
<form class="form-horizontal" style="margin-top: 5px;">
用户名<input type="text" name="username" placeholder="请输入用户名" id="u">
<span id="usernameInfo" style="color:red"></span><br/>
密码<input type="password" placeholder="请输入密码"><br/>
<input type="submit" value="注册"/>
</form>
</div>
</body>
② 引入JQuery;
在js代码中给输入框绑定change事件;
在change事件方法中执行Ajax设定servlet,携带参数:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<script type="text/javascript" src="JS/jquery-3.3.1.js"></script>
<html>
<head>
<title>校验用户名是否存在</title>
<script>
$(function () {
$("#u").change(function () {
$.post("RegisterServlet","action=checkUser&name="+this.value,function (result) {
//接收servlet返回值,并根据返回值展示页面
},"text")
})
})
</script>
一:与数据库比对拿到的内容::
新建 servlet,接收方法名和参数值;
使用三层架构和mvc模式;
Web层:
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String action = request.getParameter("action");
Class<? extends RegisterServlet> clazz = this.getClass();
Method method = clazz.getMethod(action, HttpServletRequest.class, HttpServletResponse.class);
method.invoke(this, request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
public void checkUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
String name = request.getParameter("name");
RegisterUserservice userservice = new RegisterUserservice();
boolean flag = userservice.isExist(name);
response.getWriter().print(flag);
}
service层:
public class RegisterUserservice {
public boolean isExist(String name) {
RegisterUserDao registerUserDao = new RegisterUserDao();
User user= registerUserDao.findUserName(name);
return user!=null;
}
dao层:
public class RegisterUserDao {
public User findUserName(String name) {
User user = null;
try {
JdbcTemplate jdbcTemplate = new JdbcTemplate(MyDruidJDBCUtils.dataSource);
String sql="select * from user where username=?";
user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), name);
} catch (DataAccessException e) {
}
return user; }
三:将结果显示在jsp页面:
得到 booean值,用text方式返回到ajax的回调函数中执行;
<script>
$(function () {
$("#u").change(function () {
$.post("RegisterServlet","action=checkUser&name="+this.value,function (result) {
if (result == "true" ) {
$("#usernameInfo").text("用户名已存在").css("color","red");
}else {
$("#usernameInfo").text("该用户名可以使用").css("color","green");
}
},"text")
})
})
</script>