axios+vue+servlet实现简易留言板功能(一)


(一):

登录功能:

1.创建工程,配置tomcat,创建数据库

2.建包

3.创建实体类

User.java

package stu.adam.entity;

import lombok.*;

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class User {

    private Integer uid;
    private String uname;
    private String upassword;

    public User(String uname, String upassword) {
        this.uname = uname;
        this.upassword = upassword;
    }
}

util工具类:

package stu.adam.until;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * @Author:liulei
 * @Version:1.0
 * @Date:2021/10/18-14:45
 * @Since:jdk1.8
 * @Description:
 */
public class JDBCUtils {

    /**
     * 获取数据库连接
     *
     * @return
     */
    public static Connection getConnection() {
        Connection connection = null;
        //加载文件
        Properties properties = new Properties();
        try {
            InputStream inputStream = JDBCUtils.class.getClassLoader().getResourceAsStream("stu/adam/resources/jdbc.properties");
            properties.load(inputStream);
            //加载驱动
            Class.forName(properties.getProperty("driver"));
            //驱动管理器获取数据库连接
            connection = DriverManager.getConnection(properties.getProperty("url"), properties.getProperty("user"), properties.getProperty("password"));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * 增删改
     *
     * @param sql
     * @param params
     * @return 受影响的行数
     */
    public static int update(String sql, Object... params) {
        int i = 0;
        Connection connection = getConnection();
        //修改
        try {
            i = new QueryRunner().update(connection, sql, params);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DbUtils.closeQuietly(connection);
        }
        return i;
    }

    /**
     * 修改(事务)
     *
     * @param connection
     * @param sql
     * @param params
     * @return
     */
    public static int update(Connection connection, String sql, Object... params) {
        int i = 0;
        //修改
        try {
            i = new QueryRunner().update(connection, sql, params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return i;
    }

    /**
     * 新增返回自增id
     *
     * @param sql
     * @param params
     * @return
     */
    public static int insert(String sql, Object... params) {
        int id = 0;
        Connection connection = getConnection();
        try {
            id = new QueryRunner().insert(connection, sql, new ScalarHandler(), params).intValue();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DbUtils.closeQuietly(connection);
        }
        return id;
    }

    /**
     * 新增(事务)
     *
     * @param connection
     * @param sql
     * @param params
     * @return
     */
    public static int insert(Connection connection, String sql, Object... params) {
        int id = 0;
        try {
            id = new QueryRunner().insert(connection, sql, new ScalarHandler(), params).intValue();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return id;
    }

    /**
     * 查询
     *
     * @param sql
     * @param clazz
     * @param params
     * @param 
     * @return 返回集合
     */
    public static  List query(String sql, Class clazz, Object... params) {
        List list = new ArrayList<>(10);
        Connection connection = getConnection();
        try {
            list = new QueryRunner().query(connection, sql, new BeanListHandler(clazz), params);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DbUtils.closeQuietly(connection);
        }
        return list;
    }

    /**
     * 查询单个实体
     *
     * @param sql
     * @param clazz
     * @param params
     * @param 
     * @return 单个实体
     */
    public static  T get(String sql, Class clazz, Object... params) {
        T t = null;
        Connection connection = getConnection();
        try {
            t = new QueryRunner().query(connection, sql, new BeanHandler(clazz), params);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DbUtils.closeQuietly(connection);
        }
        return t;
    }

    /**
     * 统计结果条数
     *
     *
     * @param sql
     * @param params
     * @return
     */
    public static Integer count(String sql, Object... params) {
        Integer count = null;
        Connection connection = getConnection();
        try {
            count = new QueryRunner().query(connection, sql, new ScalarHandler(), params).intValue();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }
}

dataconvert.uitl

package stu.adam.until;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author:liulei
 * @Version:1.0
 * @Date:2021/11/10-16:39
 * @Since:jdk1.8
 * @Description:
 */
public class DataConvertUtil {

    public static Integer stringConvertInteger(String value) {
        return value != null && !"".equals(value) ? Integer.valueOf(value) : 0;
    }

    public static Float stringConvertFloat(String value) {
        return value != null && !"".equals(value) ? Float.valueOf(value) : 0;
    }

    public static Boolean stringConvertBoolean(String value) {
        return value != null && !"".equals(value) ? Boolean.valueOf(value) : true;
    }

    public static Date stringConvertUtilDate(String value) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.parse(value);
    }

    public static java.sql.Date stringConvertSqlDate(String value) throws ParseException {
        return java.sql.Date.valueOf(value);
    }


}

dao层:

package stu.adam.dao;

import stu.adam.entity.User;

public interface UserLoginDao {

    User login(User user);

}

daoimpl层:

package stu.adam.dao.Impl;

import stu.adam.dao.UserLoginDao;
import stu.adam.entity.User;
import stu.adam.until.JDBCUtils;

public class UserLoginDaoImpl implements UserLoginDao {
    @Override
    public User login(User user) {
        String sql="select * from user where uname=? and upassword = ?";
        return JDBCUtils.get(sql,User.class,user.getUname(),user.getUpassword());
    }
}

service层:

package stu.adam.service;

import stu.adam.dao.UserLoginDao;
import stu.adam.entity.User;

public interface UserLoginService {
    User UserLogin(User user);
}

serviceImpl层:

package stu.adam.service;

import stu.adam.dao.UserLoginDao;
import stu.adam.entity.User;

public interface UserLoginService {
    User UserLogin(User user);
}

依赖:

## 账号 密码 驱动地址 连接地址
user=root
password=123456
url=jdbc:mysql://localhost:3306/board?useSSL=false
driver=com.mysql.jdbc.Driver

servlet层:

package stu.adam.web;

import stu.adam.entity.User;
import stu.adam.service.Impl.UserLoginServiceImpl;
import stu.adam.service.UserLoginService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "LoginServlet",urlPatterns = "/login.Do")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String userName=request.getParameter("userName");
        String pwd=request.getParameter("pwd");
        User user=new User(userName,pwd);
        UserLoginService userLoginService=new UserLoginServiceImpl();
//        if(userLoginService.UserLogin(user)!=null){
//            System.out.println("登录成功");
//
//        }else {
//            System.out.println("登录失败");
//        };
        String message="登录失败";
        User user1=userLoginService.UserLogin(user);
        if(user!=null){
            message="登陆成功";
            request.getSession().setAttribute("userLogin",user1);
        }
        PrintWriter out=response.getWriter();
        out.write(message);
        out.flush();
        out.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);

    }
}

jsp层:

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2021/11/21
  Time: 15:52
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    session.setAttribute("path", path);
%>


    
    登录
    
    
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    

class="box-card mydiv">
class="clearfix"> 登录
登录 取消
<script type="text/javascript"> new Vue( { el:"#base", data:{ myform:{ userName:"", pwd:"" } }, methods: { onSubmit() { axios.get( "${path}/login.Do",{ params:{ "userName":this.myform.userName, "pwd":this.myform.pwd }}).then(function (response) { alert(response.data); if(response.data == "登陆成功"){ location.href="${path}/index.jsp" } }).catch(function (error) { console.log(error) }) } } }); </script>

效果:

 

登录后跳转到index.jsp

小总结:主要难度在servlet编写与jsp编写上面

servlet编写需要注意:

通过后台获取查询的用户是否存在,改变message的值,前台判断message的值决定是否跳转。

(二)、主页面功能及实现

二、1 显示数据库数据

maincontent.jsp

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2021/11/21
  Time: 21:02
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    
    
    
    
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>





    <%--对应的是数据库字段--%>
    
        

欢迎 ${sessionScope.userLogin.uname},来到留言板

<%----%>

新建留言

<script type="text/javascript"> var dataListObject = { data() { return { deliverList: [] } }, methods: { //限制显示字数 dataformate(row, column, cellValue) { if (!cellValue) return ""; if (cellValue.length > 100) { //最长固定显示10个字符 return cellValue.slice(0, 100) + "..."; } return cellValue; }, queryDeliver() { var vm=this; axios.get( "${path}/Deliver.Dao", { params: { "type": "showDeliver", } }).then( function (response) { vm.deliverList = response.data.dataList; } ).catch(function (error) { console.log(error); }) } }, mounted() { var vm = this; this.queryDeliver(); axios.get("${path}/Deliver.Dao", { params: { "type": "showDeliver", } }).then(function (response) { //response取到的是page //查詢信息賦值 vm.deliverList = response.data; }).catch(function (error) { console.log(error); }) } }; var vueObject = Vue.extend(dataListObject); new vueObject().$mount("#vue"); </script>

思路,创建方法

queryDeliver()
通过axios进行前后端数据交互,
使用hook函数
mounted(){}调用querydeliver方法
效果:

 



------------恢复内容结束------------