初见Ajax的认知与理解 二

AJAX(Asynchronous JavaScript And XML 异步的JavaScript和XML)


上期说要新添一个需求:新增一个修改密码的接口,前端再增加一个修改密码的页面,请求和返回都使用JSON,要求复用数据库连接,合并读取html文件。

1、新增一个修改密码的接口

UserMapper接口部分:

package com.example.mapper;

import com.example.pojo.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface UserMapper {
    User selectAll(@Param("userName")String username, @Param("passWord")String password);

    int update(User user);
}

添加UserMapper的xml文件:







    
    
        update user set password = #{passWord} where username = #{userName};
    

2、在前端新增一个修改密码的页面

创建一个ajax-demo2.html



修改密码

修改密码

要实现从ajax-demo.html页面跳转到ajax-demo2.html上的功能,就得在ajax-demo.html上增加一个修改密码按钮并实现跳转。
ajax-demo.html:






校验

在DemoApplication部分,让hello2读取ajax-demo2.html文件。

package com.example;
@SpringBootApplication
@RestController
public class DemoApplication {
    String flag = null;
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
    /*
    * 实现账号密码校验的功能
    * */
    @RequestMapping("/addUser2")
    public People addUser2( HttpServletRequest request, HttpServletResponse response) throws IOException {
        ServletInputStream is = request.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line=null;
        String result="";
        while((line=br.readLine())!=null){
            System.out.println(line); 
            result  =result + "\n" +line;
        }
        System.out.println(result);
        //提取JSON中的值
        ObjectMapper mapper = new ObjectMapper();
        People people = mapper.readValue(result,People.class);
        //登入
        String userName = people.userName;
        String passWord = people.passWord;
        //查询数据库
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.获取Mapper接口的代理对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        //4.执行方法
        User users =userMapper.selectAll(userName, passWord);
        System.out.println(users);
        //释放资源
        sqlSession.close();
        System.out.println(result);
        //数据库数据与userName、passWord做比较
        boolean flag = false;
        if (users != null) {
            flag = true;
        } else {
            flag = false;
        }
        //返回一个Boolean
        response.getWriter().write("" + flag);
        return null;
    }
    /*
    * 读取ajax-demo2.html
    * */
    @GetMapping("/hello1")
    public String hello1() {
        String str ;
        String htmlStr="";
        try {
            BufferedReader in = new BufferedReader(new FileReader("src/webapp/ajax-demo.html"));
            while ((str = in.readLine()) != null) {
                System.out.println(str);
                htmlStr  =htmlStr + "\n" +str;
            }
            System.out.print(htmlStr);
        } catch (IOException e) {
            System.out.print("错误");
        }
        return htmlStr;
    }
    @GetMapping("/hello2")
    public String hello2() {
        String str ;
        String htmlStr="";
        try {
            BufferedReader in = new BufferedReader(new FileReader("src/webapp/ajax-demo2.html"));
            while ((str = in.readLine()) != null) {
                System.out.println(str);
                htmlStr  =htmlStr + "\n" +str;
            }
            System.out.print(htmlStr);
        } catch (IOException e) {
            System.out.print("错误");
        }
        return htmlStr;
    }
}

测试一下:初见Ajax的认知与理解 二_第1张图片初见Ajax的认知与理解 二_第2张图片

3、请求和返回都使用JSON

ajax-demo2.html通过单击事件执行asd(),将浏览器的数据提交到服务端(/addUser3)。并添加返回功能返回到校验界面。
ajax-demo2.html部分



修改密码

修改密码

DemoApplication部分:
添加addUser3 实现修改密码的功能

package com.example;
@SpringBootApplication
@RestController
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
    /*
    * 实现账号密码校验的功能
    * */
    @RequestMapping("/addUser2")
    public People addUser2( HttpServletRequest request, HttpServletResponse response) throws IOException {
        ServletInputStream is = request.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line=null;
        String result="";
        while((line=br.readLine())!=null){
            System.out.println(line); 
            result  =result + "\n" +line;
        }
        System.out.println(result);
        //提取JSON中的值
        ObjectMapper mapper = new ObjectMapper();
        People people = mapper.readValue(result,People.class);
        //登入
        String userName = people.userName;
        String passWord = people.passWord;
        //查询数据库
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.获取Mapper接口的代理对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        //4.执行方法
        User users =userMapper.selectAll(userName, passWord);
        System.out.println(users);
        //释放资源
        sqlSession.close();
        System.out.println(result);
        //数据库数据与userName、passWord做比较
        boolean flag = false;
        if (users != null) {
            flag = true;
        } else {
            flag = false;
        }
        //返回一个Boolean
        response.getWriter().write("" + flag);
        return null;
    }
    /*
    * 读取ajax-demo2.html
    * */
    @GetMapping("/hello1")
    public String hello1() {
        String str ;
        String htmlStr="";
        try {
            BufferedReader in = new BufferedReader(new FileReader("src/webapp/ajax-demo.html"));
            while ((str = in.readLine()) != null) {
                System.out.println(str);
                htmlStr  =htmlStr + "\n" +str;
            }
            System.out.print(htmlStr);
        } catch (IOException e) {
            System.out.print("错误");
        }
        return htmlStr;
    }
    @GetMapping("/hello2")
    public String hello2() {
        String str ;
        String htmlStr="";
        try {
            BufferedReader in = new BufferedReader(new FileReader("src/webapp/ajax-demo2.html"));
            while ((str = in.readLine()) != null) {
                System.out.println(str);
                htmlStr  =htmlStr + "\n" +str;
            }
            System.out.print(htmlStr);
        } catch (IOException e) {
            System.out.print("错误");
        }
        return htmlStr;
    }
    /*
    * 实现修改密码的功能
    * */
    @RequestMapping("/addUser3")
    public People addUser3( HttpServletRequest request, HttpServletResponse response) throws IOException {
        String contentType = request.getContentType();
        ServletInputStream is = request.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line=null;
        String result="";
        while((line=br.readLine())!=null){
            System.out.println(line); 
            result  =result + "\n" +line;
        }
        System.out.println(contentType);
        //提取JSON中的值
        ObjectMapper mapper = new ObjectMapper();
        People people = mapper.readValue(result,People.class);
        String userName = people.userName;
        String passWord = people.passWord;
        //修改密码
        User user = new User();
        user.setUserName(userName);
        user.setPassWord(passWord);
        //查询数据库
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.获取Mapper接口的代理对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        //4.执行方法
        int update = userMapper.update(user);
        System.out.println(update);
        //提交事务
        sqlSession.commit();
        //释放资源
        sqlSession.close();
        System.out.println(result);
        //判断数据库是否做出修改
        boolean flag = false;
        if (update !=0) {
            flag = true;
        } else {//update为0则没有做出修改
            flag = false;
        }
        //返回一个Boolean
        response.getWriter().write("" + flag);
        return null;
    }
}

测试一下
初见Ajax的认知与理解 二_第3张图片初见Ajax的认知与理解 二_第4张图片
结果符合预期。
流程跑通畅了,接下来就该思考如何将两次读取文件的操作合并(hello1和hello2)。

4、合并两次读取文件的操作

为什么要合并读取文件的操作呢?别看现在的需求要读取的文件少,比较方便。那万一以后的需求要读取几十个文件呢?我得读取一个文件就得写一次,那还得了。

那该怎么实现合并这个操作呢?
拼接字符串似乎是一个不错的选择。将要拼接的部分(ajax_demo.html、ajax_demo2.html)相似的地方提取出来,不一样的地方通过传参的方式返回不就行了吗?说干就干。
我们创建一个hello3,定义一个String类型的变量a(这个变量的值通过传参的方式获得),将相似的部分用字符串写死,不一样的部分通过变量a替代("src/webapp/"+a +".html")。
DemoApplication部分:

package com.example;
@SpringBootApplication
@RestController
public class DemoApplication {
    String flag = null;
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
    @RequestMapping("/hello3")
    public String hello3( HttpServletRequest request) throws IOException {
        String flag = request.getParameter("flag");
        String a = "";
        System.out.println(flag);
        if (flag == null){//只会执行一次,做为变量a没有传递回来之前的默认值。
            a ="ajax-demo";
        }else{
            a = flag;
        }
        System.out.println(a);
        String str ="";
        String htmlStr="";
        try {
            BufferedReader in = new BufferedReader(new FileReader("src/webapp/"+a +".html"));
            while ((str = in.readLine()) != null) {
                htmlStr  =htmlStr + "\n" +str;
            }
        } catch (IOException e) {
            System.out.print("错误");
        }
        System.out.println(htmlStr);
        return htmlStr;
    }
    /*
    * 实现账号密码校验的功能
    * */
    @RequestMapping("/addUser2")
    public People addUser2( HttpServletRequest request, HttpServletResponse response) throws IOException {
        ServletInputStream is = request.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line=null;
        String result="";
        while((line=br.readLine())!=null){
            System.out.println(line); 
            result  =result + "\n" +line;
        }
        System.out.println(result);
        //提取JSON中的值
        ObjectMapper mapper = new ObjectMapper();
        People people = mapper.readValue(result,People.class);
        //登入
        String userName = people.userName;
        String passWord = people.passWord;
        //查询数据库
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.获取Mapper接口的代理对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        //4.执行方法
        User users =userMapper.selectAll(userName, passWord);
        System.out.println(users);
        //释放资源
        sqlSession.close();
        System.out.println(result);
        //数据库数据与userName、passWord做比较
        boolean flag = false;
        if (users != null) {
            flag = true;
        } else {
            flag = false;
        }
        //返回一个Boolean
        response.getWriter().write("" + flag);
        return null;
    }
    /*
    * 实现修改密码的功能
    * */
    @RequestMapping("/addUser3")
    public People addUser3( HttpServletRequest request, HttpServletResponse response) throws IOException {
        String contentType = request.getContentType();
        ServletInputStream is = request.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line=null;
        String result="";
        while((line=br.readLine())!=null){
            System.out.println(line); 
            result  =result + "\n" +line;
        }
        System.out.println(contentType);
        //提取JSON中的值
        ObjectMapper mapper = new ObjectMapper();
        People people = mapper.readValue(result,People.class);
        String userName = people.userName;
        String passWord = people.passWord;
        //修改密码
        User user = new User();
        user.setUserName(userName);
        user.setPassWord(passWord);
        //查询数据库
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.获取Mapper接口的代理对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        //4.执行方法
        int update = userMapper.update(user);
        System.out.println(update);
        //提交事务
        sqlSession.commit();
        //释放资源
        sqlSession.close();
        System.out.println(result);
        //判断数据库是否做出修改
        boolean flag = false;
        if (update !=0) {
            flag = true;
        } else {//update为0则没有做出修改
            flag = false;
        }
        //返回一个Boolean
        response.getWriter().write("" + flag);
        return null;
    }
}

html部分:
以ajax-demo.html举例:
在tz()下将ajax-demo2.html使用post请求将数据传递给/hello3.



    
    
    
        

校验

ajax-demo2.html同上。
测试一下!
在浏览器上输入http://localhost:8080/hello3;
初见Ajax的认知与理解 二_第5张图片初见Ajax的认知与理解 二_第6张图片初见Ajax的认知与理解 二_第7张图片初见Ajax的认知与理解 二_第8张图片初见Ajax的认知与理解 二_第9张图片初见Ajax的认知与理解 二_第10张图片
ok,功能没有问题,接下来就是复用数据库连接了。咱只要把加载数据库等信息放入构造函数中,然后在需要使用的时候引用这个构造函数即可。

5、复用数据库连接

创建一个构造函数Sql

package com.example;
public class Sql {
    SqlSessionFactory Sql() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        return sqlSessionFactory;
    }
}

然后将DemoApplication中配置数据库的部分一一替代:

package com.example;
@SpringBootApplication
@RestController
public class DemoApplication {
    String flag = null;
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
    @RequestMapping("/hello3")
    public String hello3( HttpServletRequest request) throws IOException {
        String flag = request.getParameter("flag");
        String a = "";
        System.out.println(flag);
        if (flag == null){//只会执行一次,做为变量a没有传递回来之前的默认值。
            a ="ajax-demo";
        }else{
            a = flag;
        }
        System.out.println(a);
        String str ="";
        String htmlStr="";
        try {
            BufferedReader in = new BufferedReader(new FileReader("src/webapp/"+a +".html"));
            while ((str = in.readLine()) != null) {
                htmlStr  =htmlStr + "\n" +str;
            }
        } catch (IOException e) {
            System.out.print("错误");
        }
        System.out.println(htmlStr);
        return htmlStr;
    }
    /*
    * 实现账号密码校验的功能
    * */
    @RequestMapping("/addUser2")
    public People addUser2( HttpServletRequest request, HttpServletResponse response) throws IOException {
        ServletInputStream is = request.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line=null;
        String result="";
        while((line=br.readLine())!=null){
            System.out.println(line); 
            result  =result + "\n" +line;
        }
        System.out.println(result);
        //提取JSON中的值
        ObjectMapper mapper = new ObjectMapper();
        People people = mapper.readValue(result,People.class);
        //登入
        String userName = people.userName;
        String passWord = people.passWord;
        //查询数据库
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SqlSession对象
        Sql sql = new Sql();
        SqlSession sqlSession = sql.Sql().openSession();
        //3.获取Mapper接口的代理对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        //4.执行方法
        User users =userMapper.selectAll(userName, passWord);
        System.out.println(users);
        //释放资源
        sqlSession.close();
        System.out.println(result);
        //数据库数据与userName、passWord做比较
        boolean flag = false;
        if (users != null) {
            flag = true;
        } else {
            flag = false;
        }
        //返回一个Boolean
        response.getWriter().write("" + flag);
        return null;
    }
    /*
    * 实现修改密码的功能
    * */
    @RequestMapping("/addUser3")
    public People addUser3( HttpServletRequest request, HttpServletResponse response) throws IOException {
        String contentType = request.getContentType();
        ServletInputStream is = request.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line=null;
        String result="";
        while((line=br.readLine())!=null){
            System.out.println(line);
            result  =result + "\n" +line;
        }
        System.out.println(contentType);
        //提取JSON中的值
        ObjectMapper mapper = new ObjectMapper();
        People people = mapper.readValue(result,People.class);
        String userName = people.userName;
        String passWord = people.passWord;
        //修改密码
        User user = new User();
        user.setUserName(userName);
        user.setPassWord(passWord);
        //查询数据库
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SqlSession对象
        Sql sql = new Sql();
        SqlSession sqlSession = sql.Sql().openSession();
        //3.获取Mapper接口的代理对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        //4.执行方法
        int update = userMapper.update(user);
        System.out.println(update);
        //提交事务
        sqlSession.commit();
        //释放资源
        sqlSession.close();
        System.out.println(result);
        //判断数据库是否做出修改
        boolean flag = false;
        if (update !=0) {
            flag = true;
        } else {//update为0则没有做出修改
            flag = false;
        }
        //返回一个Boolean
        response.getWriter().write("" + flag);
        return null;
    }
}

大功告成,可以使用 show ststus like 'Threads%'; 可以在MySQL命令行中查看数据库连接的情况。

你可能感兴趣的:(ajax)