• Ajax技术【Ajax 实战】(二)-全面详解(学习总结---从入门到深化)


     

    目录

    Ajax 实战


    Ajax 实战

    创建项目

    创建Java项目

     

     

     点击finish完成项目创建,然后右键选择"add Framework Support..."

     勾选红框中的选项,点击"OK",完成后项目下出现web文件夹

     点击"project structure"

     点击Modules,选择"Web"模块,再按图示点击"+",按默认路径, 再点击"OK"

     配置tomcat服务器

     选择Edit Configuration...

     选择Deployment标签,点击右侧"+",选择要部署的项目,按默认就可以

     

     添加要部署的war文件,Application context设置为"/",点击ok。

    添加依赖包

     在"dependencies"标签中,点击右侧"+",选择Library...,添加 Tomcat

     根据实际情况继续添加其它必要的依赖,如fastjson,commonslang等。

     导入jquery包

    在web目录下,创建js文件夹,把jquery-3.6.0.js放到js目录下

     创建实体类User

    1. package com.itbaizhan.ajax.pojo;
    2. public class User {
    3. private Integer id;
    4. private String username;
    5. private String password;
    6. private Double salary;
    7. private String birthday;
    8. public Integer getId() {
    9. return id;
    10. }
    11. public void setId(Integer id) {
    12. this.id = id;
    13. }
    14. public String getUsername() {
    15. return username;
    16. }
    17. public void setUsername(String username)
    18. {
    19. this.username = username;
    20. }
    21. public String getPassword() {
    22. return password;
    23. }
    24. public void setPassword(String password)
    25. {
    26. this.password = password;
    27. }
    28. public Double getSalary() {
    29. return salary;
    30. }
    31. public void setSalary(Double salary) {
    32. this.salary = salary;
    33. }
    34. public String getBirthday() {
    35. return birthday;
    36. }
    37. public void setBirthday(String birthday)
    38. {
    39. this.birthday = birthday;
    40. }
    41. public User(Integer id, String username,
    42. String password, Double salary, String birthday) {
    43. this.id = id;
    44. this.username = username;
    45. this.password = password;
    46. this.salary = salary;
    47. this.birthday = birthday;
    48. }
    49. public User() {
    50. }
    51. }

    创建页面

    创建index.jsp中的静态部分

    1. <body>
    2. <div>
    3. <table align="center" width="60%" border="1">
    4. <tr>
    5. <td>ID:</td>
    6. <td><input type="text" name="id" id="id"/></td>
    7. <td>姓名:</td>
    8. <td><input type="text" name="username" id="username"/></td>
    9. <td>密码:</td>
    10. <td><input type="text" name="password" id="password"/></td>
    11. </tr>
    12. <tr>
    13. <td>收入:</td>
    14. <td><input type="text" name="salary" id="salary"/></td>
    15. <td>出生日期:</td>
    16. <td><input type="text" name="birthday" id="birthday"/></td>
    17. <td colspan="2"></td>
    18. </tr>
    19. <tr align="center">
    20. <td colspan="6">
    21. <input type="button" value="添加用户" id="add" />
    22. <input type="button" value="更新用户" id="update"/>
    23. </td>
    24. </tr>
    25. </table> <hr/>
    26. <table align="center" width="60%" bgcolor="" border="1" id="myTable">
    27. <thead>
    28. <tr align="center">
    29. <td>ID</td>
    30. <td>姓名</td>
    31. <td>密码</td>
    32. <td>收入</td>
    33. <td>生日</td>
    34. <td>操作</td>
    35. </tr>
    36. </thead>
    37. <tbody id="tBody"></tbody>
    38. </table>
    39. </div>
    40. </body>

    创建UserServlet

    1. @WebServlet("/user.do")
    2. public class UserServlet extends HttpServlet
    3. {
    4. @Override
    5. public void init() throws ServletException {
    6. }
    7. @Override
    8. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    9. this.doPost(req, resp);
    10. }
    11. @Override
    12. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    13. }
    14. }

    配置web.xml

    1. <servlet>
    2. <servlet-name>UserServlet</servlet-name>
    3. <servlet-class>
    4. com.itbaizhan.ajax.servlet.UserServlet
    5. </servlet-class>
    6. </servlet>
    7. <servlet-mapping>
    8. <servlet-name>UserServlet</servlet-name>
    9. <url-pattern>/</url-pattern>
    10. </servlet-mapping>

    查询用户列表

    页面相关

    1. $(function () {
    2. //初始化用户数据
    3. getData();
    4. });
    5. // 获取页面初始化数据
    6. function getData(){
    7. $.getJSON("user.do", {flag:"getData"},function (result) {
    8. listUser(result);
    9. });
    10. }
    11. // 遍历数据生成数据
    12. function listUser(obj){
    13. var str ="";
    14. $.each(obj,function(){
    15. str+= "" +
    16. ""+this.id +""+
    17. ""+this.username+"" +
    18. ""+this.password+"" +
    19. ""+this.salary+"" +
    20. ""+this.birthday+"" +
    21. "
    22. });
    23. $("#tBody").prepend(str);
    24. }

    servlet相关

    1. @Override
    2. public void init() throws ServletException {
    3. ArrayList<User> list = new ArrayList<>();
    4. User user1 = new User(1,"zhangsan","123",2000d,"1997-09-01");
    5. User user2 = new User(2,"lisi","123",3000d,"1998-08-23");
    6. User user3 = new User(3,"zhaoliu","123",2500d,"1996-05-16");
    7. User user4 = new User(4,"wangwu","123",2080d,"1995-10-12");
    8. User user5 = new User(5,"zhengsan","123",3200d,"1999-12-20");
    9. User user6 = new User(6,"liugang","123",4200d,"1994-04-10");
    10. list.add(user1);
    11. list.add(user2);
    12. list.add(user3);
    13. list.add(user4);
    14. list.add(user5);
    15. list.add(user6);
    16. ServletContext servletContext = this.getServletContext();
    17. servletContext.setAttribute("list",list);
    18. }
    19. // 获取页面初始化数据
    20. private void getData(HttpServletRequest req, HttpServletResponse resp) throws IOException
    21. {
    22. List<User> list = (List<User>)
    23. this.getServletContext().getAttribute("list");
    24. String s = JSON.toJSONString(list);
    25. resp.setContentType("application/json");
    26. PrintWriter pw = resp.getWriter();
    27. pw.print(s);
    28. pw.flush();
    29. pw.close();
    30. }
    31. @Override
    32. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws
    33. ServletException, IOException {
    34. String flag = req.getParameter("flag");
    35. if("getData".equals(flag)){
    36. this.getData(req,resp);
    37. }
    38. }

    添加用户

    页面相关

    1. //添加按钮绑定点击事件
    2. $("#add").click(function(){
    3. addOrUpdateUser("addUser");
    4. });
    5. // 用户添加或者用户更新
    6. function addOrUpdateUser(flag){
    7. // 从页面中获取数据
    8. var userid = $("#id").val();
    9. var username = $("#username").val();
    10. var password = $("#password").val();
    11. var salary = $("#salary").val();
    12. var birthday = $("#birthday").val();
    13. var data = {
    14. userid:userid,
    15. username:username,
    16. password:password,
    17. salary:salary,
    18. birthday:birthday,
    19. flag:flag
    20. }
    21. $.get("user.do",data,function(result){
    22. alert(result);
    23. location.reload();
    24. });
    25. }

    servlet相关

    1. /**
    2. * 处理添加用户请求
    3. * @param req
    4. * @param resp
    5. * @throws ServletException
    6. * @throws IOException
    7. */
    8. private void addUser(HttpServletRequest req, HttpServletResponse resp) throws IOException
    9. {
    10. User user = this.createUser(req);
    11. ServletContext servletContext = this.getServletContext();
    12. List<User> list = (List<User>)servletContext.getAttribute("list");
    13. list.add(user);
    14. resp.setContentType("text/plain;charset=utf-8");
    15. PrintWriter pw = resp.getWriter();
    16. pw.print("添加成功");
    17. pw.flush();
    18. pw.close();
    19. }
    20. @Override
    21. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws
    22. ServletException, IOException {
    23. String flag = req.getParameter("flag");
    24. if("getData".equals(flag)){
    25. this.getData(req,resp);
    26. }else if("addUser".equals(flag)){
    27. this.addUser(req,resp);
    28. }
    29. }
    30. // 获取请求数据
    31. private User createUser(HttpServletRequest
    32. req){
    33. String userid = req.getParameter("userid");
    34. String username = req.getParameter("username");
    35. String password = req.getParameter("password");
    36. String salary = req.getParameter("salary");
    37. String birthday = req.getParameter("birthday");
    38. User user = new User();
    39. user.setId(Integer.parseInt(userid));
    40. user.setUsername(username);
    41. user.setPassword(password);
    42. user.setSalary(Double.valueOf(salary));
    43. user.setBirthday(birthday);
    44. return user;
    45. }

    更新用户

    页面相关

    1. // 更新之前的数据选择
    2. function preUpdateUser(userid){
    3. var arr = new Array();
    4. $("#"+userid).closest("tr").children().each(
    5. function(index,ele){
    6. if(index <=4){
    7. arr[index]= ele.innerText
    8. }
    9. });
    10. $("#id").val(arr[0]);
    11. $("#id").attr("readonly",true);
    12. $("#username").val(arr[1]);
    13. $("#password").val(arr[2]);
    14. $("#salary").val(arr[3]);
    15. $("#birthday").val(arr[4]);
    16. }
    17. //更新按钮绑定点击事件
    18. $("#update").click(function(){
    19. addOrUpdateUser("updateUser");
    20. });
    21. // 用户添加或者用户更新
    22. function addOrUpdateUser(flag){
    23. // 从页面中获取数据
    24. var userid = $("#id").val();
    25. var username = $("#username").val();
    26. var password = $("#password").val();
    27. var salary = $("#salary").val();
    28. var birthday = $("#birthday").val();
    29. var data = {
    30. userid:userid,
    31. username:username,
    32. password:password,
    33. salary:salary,
    34. birthday:birthday,
    35. flag:flag
    36. }
    37. $.get("user.do",data,function(result){
    38. alert(result);
    39. location.reload();
    40. });
    41. }

    servlet相关

    1. /**
    2. * 处理更新用户请求
    3. * @param req
    4. * @param resp
    5. * @throws IOException
    6. */
    7. private void updateUser(HttpServletRequest req,
    8. HttpServletResponse resp) throws IOException{
    9. User user = this.createUser(req);
    10. ServletContext servletContext = this.getServletContext();
    11. List<User> userList = (List<User>) servletContext.getAttribute("list");
    12. //list转map
    13. Map<Integer, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
    14. //根据id获取user
    15. User user1 = userMap.get(user.getId());
    16. //删除指定的user
    17. userList.remove(user1);
    18. //添加新的user
    19. userList.add(user);
    20. //按id排序
    21. userList.sort(new Comparator<User>() {
    22. @Override
    23. public int compare(User o1, User o2)
    24. {
    25. return o1.getId() - o2.getId();
    26. }
    27. });
    28. //输出至页面
    29. resp.setContentType("text/plain;charset=utf-8");
    30. PrintWriter pw = resp.getWriter();
    31. pw.print("更新成功");
    32. pw.flush();
    33. pw.close();
    34. }
    35. @Override
    36. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws
    37. ServletException, IOException {
    38. String flag = req.getParameter("flag");
    39. if("getData".equals(flag)){
    40. this.getData(req,resp);
    41. }else if("addUser".equals(flag)){
    42. this.addUser(req,resp);
    43. }else if("updateUser".equals(flag)){
    44. this.updateUser(req,resp);
    45. }
    46. }

    删除用户

    页面相关

    1. // 删除用户
    2. function deleteUser(userid){
    3. $("#"+userid).closest("tr").remove();
    4. $.post("user.do", {userid:userid,flag:"delete"},function(result){
    5. alert(result)
    6. })
    7. }

    servlet相关

    1. @Override
    2. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws
    3. ServletException, IOException {
    4. String flag = req.getParameter("flag");
    5. if("getData".equals(flag)){
    6. this.getData(req,resp);
    7. }else if("addUser".equals(flag)){
    8. this.addUser(req,resp);
    9. }else if("updateUser".equals(flag)){
    10. this.updateUser(req,resp);
    11. }else if("delete".equals(flag)){
    12. this.deleteUser(req,resp);
    13. }
    14. }
    15. /**
    16. * 处理删除用户请求
    17. * @param req
    18. * @param resp
    19. * @throws ServletException
    20. * @throws IOException
    21. */
    22. private void deleteUser(HttpServletRequest req,
    23. HttpServletResponse resp) throws ServletException, IOException{
    24. ServletContext servletContext = this.getServletContext();
    25. List<User> userList = (List<User>)servletContext.getAttribute("list");
    26. String userid = req.getParameter("userid");
    27. //list转map
    28. Map<Integer, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
    29. //根据id获取user
    30. if(StringUtils.isNotEmpty(userid)){
    31. User user1 = userMap.get(Integer.parseInt(userid));
    32. //删除指定的user
    33. userList.remove(user1);
    34. resp.setContentType("text/plain;charset=utf-8");
    35. PrintWriter pw = resp.getWriter();
    36. pw.print("删除成功");
    37. pw.flush();
    38. pw.close();
    39. }else{
    40. resp.setContentType("text/plain;charset=utf-8");
    41. PrintWriter pw = resp.getWriter();
    42. pw.print("删除失败");
    43. pw.flush();
    44. pw.close();
    45. }
    46. }

    运行效果

    复习:

     Java对象的序列化和反序列化

     序列化和反序列化是什么

    当两个进程远程通信时,彼此可以发送各种类型的数据。 无论是何 种类型的数据,都会以二进制序列的形式在网络上传送。比如,我 们可以通过http协议发送字符串信息;我们也可以在网络上直接发 送Java对象。发送方需要把这个Java对象转换为字节序列,才能在 网络上传送;接收方则需要把字节序列再恢复为Java对象才能正常 读取。 把Java对象转换为字节序列的过程称为对象的序列化。把字节序列 恢复为Java对象的过程称为对象的反序列化。

     序列化涉及的类和接口

    ObjectOutputStream代表对象输出流,它的writeObject(Object obj)方法可对参数指定的obj对象进行序列化,把得到的字节序列写 到一个目标输出流中。

    ObjectInputStream代表对象输入流,它的readObject()方法从一个 源输入流中读取字节序列,再把它们反序列化为一个对象,并将其 返回。 只有实现了Serializable接口的类的对象才能被序列化。 Serializable接口是一个空接口,只起到标记作用。

     将对象序列化到文件

     ObjectOutputStream可以将一个内存中的Java对象通过序列化的方 式写入到磁盘的文件中。被序列化的对象必须要实现Serializable序 列化接口,否则会抛出异常。

     创建对象

    1. public class Users implements Serializable {
    2. private int userid;
    3. private String username;
    4. private String userage;
    5. public Users(int userid, String username, String userage) {
    6. this.userid = userid;
    7. this.username = username;
    8. this.userage = userage;
    9. }
    10. public Users() { }
    11. public int getUserid() {
    12. return userid;
    13. }
    14. public void setUserid(int userid) {
    15. this.userid = userid;
    16. }
    17. public String getUsername() {
    18. return username;
    19. }
    20. public void setUsername(String username)
    21. {
    22. this.username = username;
    23. }
    24. public String getUserage() {
    25. return userage;
    26. }
    27. public void setUserage(String userage) {
    28. this.userage = userage;
    29. }
    30. @Override
    31. public String toString() {
    32. return "Users{" +
    33. "userid=" + userid +
    34. ", username='" + username + '\'' +
    35. ", userage='" + userage + '\'' +
    36. '}';
    37. }

    序列化对象

    1. public class TestObjectOutputStream {
    2. public static void main(String[] args) {
    3. //创建对象输出字节流与文件输出字节流对象
    4. try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("d:/data3"))){
    5. //创建Users对象
    6. Users users = new Users(1,"Oldlu","18");
    7. //将对象序列化到文件中
    8. oos.writeObject(users);
    9. //刷新
    10. oos.flush();
    11. }catch(IOException e){
    12. e.printStackTrace();
    13. }
    14. }
    15. }

    将对象反序列化到内存中

    1. public class TestObjectInputStream {
    2. public static void main(String[] args) {
    3. //创建对象输入字节流与文件字节输入流对象
    4. try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d:/data3")))
    5. {
    6. //将对象反序列化到内存中
    7. Users users = (Users) ois.readObject();
    8. System.out.println(users);
    9. }catch(Exception e){
    10. e.printStackTrace();
    11. }
    12. }
    13. }

    File类在IO中的作用

     当以文件作为数据源或目标时,除了可以使用字符串作为文件以及 位置的指定以外,我们也可以使用File类指定。

    1. public class TestFile {
    2. public static void main(String[] args) {
    3. //创建字符缓冲流与文件字符输入流对象
    4. try(BufferedReader br = new BufferedReader(new FileReader(new File("d:/sxt.txt")));
    5. //创建字符输出流对象
    6. PrintWriter pw = new PrintWriter(new File("d:/sxt8.txt"))){
    7. //操作流
    8. String temp = "";
    9. int i=1;
    10. while((temp = br.readLine()) != null){
    11. pw.println(i+","+temp);
    12. i++;
    13. }
    14. pw.flush();
    15. }catch(IOException e){
    16. e.printStackTrace();
    17. }
    18. }
    19. }

    装饰器模式构建IO流体系

    装饰器模式简介

    装饰器模式是GOF23种设计模式中较为常用的一种模式。它可以实 现对原有类的包装和装饰,使新的类具有更强的功能。

     装饰器模式

    1. class Iphone {
    2. private String name;
    3. public Iphone(String name) {
    4. this.name = name;
    5. }
    6. public void show() {
    7. System.out.println("我是" + name + ",可以在屏幕上显示");
    8. }
    9. }
    10. class TouyingPhone {
    11. public Iphone phone;
    12. public TouyingPhone(Iphone p) {
    13. this.phone = p;
    14. }
    15. // 功能更强的方法
    16. public void show() {
    17. phone.show();
    18. System.out.println("还可以投影,在墙壁上显示");
    19. }
    20. }
    21. public class TestDecoration {
    22. public static void main(String[] args) {
    23. Iphone phone = new Iphone("iphone30");
    24. phone.show();
    25. System.out.println("===============装饰后");
    26. TouyingPhone typhone = newTouyingPhone(phone);
    27. typhone.show();
    28. }
    29. }

    IO流体系中的装饰器模式

    IO流体系中大量使用了装饰器模式,让流具有更强的功能、更强的 灵活性。比如:

    1. FileInputStream fis = new FileInputStream(src);
    2. BufferedInputStream bis = new BufferedInputStream(fis);

     显然BufferedInputStream装饰了原有的FileInputStream,让普通 的FileInputStream也具备了缓存功能,提高了效率。

  • 相关阅读:
    J2L3x 私有化部署方案详解,看看是否适合你的企业
    跨境电商去哪做好?东南亚六国电商情况一览
    Python 数组和列表:创建、访问、添加和删除数组元素
    公众号推送早安问候以及天气预报(JAVA)
    协同办公“战役”,华为输了吗?
    执行 JUnit 单元测试前,修改环境变量
    ChatGPT+Mermaid自然语言流程图形化产出小试
    [附源码]计算机毕业设计JAVAjsp医院网上预约系统
    【vue3】12.跟着官网学习vue3-侦听器,watch方法
    java基于SpringBoot+Vue+nodejs的高校自动排课系统 Element-UI
  • 原文地址:https://blog.csdn.net/m0_58719994/article/details/131647774