//前台 jsp 页面
<%@ page contentType=“text/html;charset=UTF-8” language=“java” %>
<script type="text/javascript" src="../js/jquery-3.4.1.js"></script>
<script type="text/javascript">
//思路:前台 点击提交按钮,通过$.getJSON()从后台得到json对象
$(document).ready(function () {
$("#button").click(function () {
//通过定位获得输入框的值
var name=$("#name").val();
var pwd=$("#pwd").val();
//url:要访问的文件 键值对:拼接输入框的值 回调函数名
$.getJSON("/servlet","name="+name+"&pwd="+pwd,dologin)
function dologin(data) {
$("#textJson").html(data)
}
})
})
</script>
用 户 名: |
//后台servlet
@WebServlet(name =“Servlet”,value = “/servlet”)
public class Servlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取前台表单值
String name=request.getParameter(“name”);
String pwd=request.getParameter(“pwd”);
//给user设值
User user=new User();
user.setUserName(name);
user.setPassword(pwd);
//将user对象转换为JSON格式
String newsJson=JSON.toJSONString(user);
//将JSON通过流给jsp页面响应
PrintWriter out=response.getWriter();
out.print(newsJson);
out.flush();
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
doGet(request,response);
}
}