1.elementui布局框架

Element,一套为开发者、设计师和产品经理准备的基于 Vue 2.0 的桌面端组件库 。

换句话说:Element它是在vue2.0的基础上,提供了各种组件(比如表单 表格 菜单导航.....),使用这些组件可以更好得完成功能和布局。

2.1 如何使用elementui组件

(1)需要再相应得网页中引入vue和elementui得文件

注意:必须先引入vue在引入element

    <!--引入element得css样式-->
    <link type="text/css" rel="stylesheet" href="css/index.css"/>
    <!--引入vue得js文件 这个必须在element之前引入-->
    <script type="text/javascript" src="js/vue.js"></script>
    <!--element得js文件-->
    <script type="text/javascript" src="js/index.js"></script>

(2)设置表格组件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--引入element得css样式-->
    <link type="text/css" rel="stylesheet" href="css/index.css"/>
    <!--引入vue得js文件 这个必须在element之前引入-->
    <script type="text/javascript" src="js/vue.js"></script>
    <!--element得js文件-->
    <script type="text/javascript" src="js/index.js"></script>
</head>
<body>
   <!--创建一个标签使vue挂载到该标签上-->
   <div id="app">
       <!--:data==绑定了vue中定义得数据tableData
           border表示设置表格边框
           el-table-column:表示列标签
              prop:该属性得名称必须和tableData中对象得属性名一致。
              label:表格得标题
              width: 设置列得宽度
       -->
       <el-table
               :data="tableData"
               border
               style="width: 100%">
           <el-table-column
                   prop="date"
                   label="日期"
                   >
           </el-table-column>
           <el-table-column
                   prop="name"
                   label="姓名"
                   >
           </el-table-column>
           <el-table-column
                   prop="address"
                   label="地址">
           </el-table-column>
           <el-table-column
                   fixed="right"
                   label="操作"
                   >
               <template slot-scope="scope">
                   <el-button type="text" size="small">查看</el-button>
                   <el-button type="text" size="small">编辑</el-button>
               </template>
       </el-table>
   </div>
</body>
<!--表示自定义得js文件-->
<script>
      var app=new Vue({
           el:"#app",
           data:{
                tableData:[
                    {"date":"2020-05-11","name":"张三","address":"北京"},
                    {"date":"2021-05-11","name":"李四","address":"郑州"},
                    {"date":"2022-05-11","name":"五五","address":"杭州"},
                    {"date":"2023-06-11","name":"六六","address":"上海"},
                ],
           }
      })
</script>
</html>

把上面的操作文字换成按钮形式:

<el-table-column
                   fixed="right"
                   label="操作"
                   >
     <template slot-scope="scope">
         <el-button type="success" size="small" icon="el-icon-edit" plain>编辑</el-button>
         <el-button type="danger"  size="small" icon="el-icon-delete" plain>删除</el-button>
     </template>
</el-table-column>

引入下面三个文件到工程中,可以使用element的图标组件

 2.查询

2.1.创建数据库文件

-- 创建数据库
create database vue01;
-- 切换数据库到vue01
use vue01;
-- 创建表
create table t_dept(
     dept_id int primary key auto_increment COMMENT '部门号',
		 dept_name varchar(20) COMMENT '部门名称',
		 loc varchar(20) COMMENT '部门所在地'
);
create table t_emp(
    emp_id int primary key auto_increment COMMENT '员工编号',
		emp_name varchar(20) COMMENT '员工姓名',
		emp_sex TINYINT COMMENT '性别 0表示男 1表示女',
		emp_age int  COMMENT '年龄',
		emp_salary DECIMAL(7,2) COMMENT '工资',
		dept_id int COMMENT '关联的部门号'
);
-- 添加数据
insert into t_dept values
(null,'研发部','郑州'),(null,'市场部','杭州'),(null,'人事部','北京')

insert into t_emp values 
(null,'张三',0,25,1666.65,1),
(null,'李四',1,26,2555.65,2),
(null,'王五',0,32,6666.65,3),
(null,'赵六',0,36,8888.65,1)

2.2.创建员工实体类

public class Emp {
    //员工编号
    private int empId;
    //员工姓名
    private String empName;
    //性别
    private int empSex;
    //年龄
    private int empAge;
    //薪水
    private Double empSalary;
    //部门号
    private int deptId;

    public int getEmpId() {
        return empId;
    }

    public void setEmpId(int empId) {
        this.empId = empId;
    }

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    public int getEmpSex() {
        return empSex;
    }

    public void setEmpSex(int empSex) {
        this.empSex = empSex;
    }

    public int getEmpAge() {
        return empAge;
    }

    public void setEmpAge(int empAge) {
        this.empAge = empAge;
    }

    public Double getEmpSalary() {
        return empSalary;
    }

    public void setEmpSalary(Double empSalary) {
        this.empSalary = empSalary;
    }

    public int getDeptId() {
        return deptId;
    }

    public void setDeptId(int deptId) {
        this.deptId = deptId;
    }
}

2.3.员工的dao

/**
     * 查询所有员工信息
     * @return 所有员工信息
     */
    public List<Emp> findAll(){
        List<Emp> list = new ArrayList<>();
        try {
            getConn();
            String sql="select * from t_emp";
            ps=connection.prepareStatement(sql);
            rs=ps.executeQuery();
            while(rs.next()){
                 Emp emp=new Emp();
                 emp.setEmpId(rs.getInt("emp_id"));
                 emp.setEmpName(rs.getString("emp_name"));
                 emp.setEmpAge(rs.getInt("emp_age"));
                 emp.setEmpSalary(rs.getDouble("emp_salary"));
                 emp.setEmpSex(rs.getInt("emp_sex"));
                 emp.setDeptId(rs.getInt("dept_id"));
                 list.add(emp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeAll();
        }
        return list;
    }

2.4.测试dao方法

public class TestEmpDao {
    private EmpDao empDao=new EmpDao();
    @Test
    public void testFindAll(){
        System.out.println(empDao.findAll());
    }
}

2.5.servlet

package com.aaa.controller;

import com.aaa.dao.EmpDao;
import com.aaa.entity.Emp;
import com.alibaba.fastjson.JSON;

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;
import java.util.List;

@WebServlet(name = "EmpServlet",urlPatterns = "/EmpServlet")
public class EmpServlet extends HttpServlet {
    private EmpDao empDao=new EmpDao();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         req.setCharacterEncoding("utf-8");
         resp.setContentType("text/html;charset=utf-8");
         //接受处理的标识
         String method = req.getParameter("method");
         if("delete".equals(method)){

         }else{
             //查询所有的操作
             queryAll(req,resp);
         }
    }

    private void queryAll(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
        List<Emp> list = empDao.findAll();
        //把java集合转换为json对象。---fastjson
        String result = JSON.toJSONString(list);
        PrintWriter writer = resp.getWriter();
        //输出给客户
        writer.print(result);
        //关闭资源
        writer.flush();
        writer.close();
    }
}

2.6.展示到网页

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--引入element得css样式-->
    <link type="text/css" rel="stylesheet" href="css/index.css"/>
    <!--引入vue得js文件 这个必须在element之前引入-->
    <script type="text/javascript" src="js/vue.js"></script>
    <script type="text/javascript" src="js/axios.min.js"></script>
    <!--element得js文件-->
    <script type="text/javascript" src="js/index.js"></script>
</head>
<body>
   <!--创建一个标签使vue挂载到该标签上-->
   <div id="app">
       <!--:data==绑定了vue中定义得数据tableData
           border表示设置表格边框
           el-table-column:表示列标签
              prop:该属性得名称必须和tableData中对象得属性名一致。
              label:表格得标题
              width: 设置列得宽度
       -->
       <el-table
               :data="tableData"
               border
               style="width: 100%">
           <el-table-column
                   prop="empId"
                   label="员工编号"
                   >
           </el-table-column>
           <el-table-column
                   prop="empName"
                   label="员工姓名"
                   >
           </el-table-column>
           <el-table-column
                   prop="empSex"
                   label="性别">
           </el-table-column>
           <el-table-column
                   prop="empAge"
                   label="年龄">
           </el-table-column>
           <el-table-column
                   prop="empSalary"
                   label="薪水">
           </el-table-column>
           <el-table-column
                   prop="deptId"
                   label="部门编号">
           </el-table-column>
           <el-table-column
                   fixed="right"
                   label="操作"
                   >
               <template slot-scope="scope">
                   <el-button type="success" size="small" icon="el-icon-edit" plain>编辑</el-button>
                   <el-button type="danger"  size="small" icon="el-icon-delete" plain>删除</el-button>
               </template>
           </el-table-column>
       </el-table>
   </div>
</body>
<!--表示自定义得js文件-->
<script>
      var app=new Vue({
           el:"#app",
           data:{
                tableData:[],
           },
           //页面加载完毕后执行;
           created(){
               this.initTable();
           },
           methods:{
               //初始化表格数据
               initTable(){
                    var that=this;
                    //通过axios后台服务发送异步请求
                    axios.post("EmpServlet").then(function(result){
                          if(result.data.code===2000){//===:比较值和引用是否相同
                              that.tableData=result.data.data;
                          }else{

                          }
                    })
               }
           }
      })
</script>
</html>

上面的性别显示的为数字 如何显示男和女 需要自定义列

           <el-table-column
                   prop="empSex"
                   label="性别">
               <template slot-scope="scope">
                   <el-tag size="medium"> {{ scope.row.empSex==0?"男":"女" }}</el-tag>
               </template>
           </el-table-column>

3.删除

3.1前端页面

 

var qs=Qs;               axios.post("EmpServlet",qs.stringify({"method":"delete","id":id})).then(function(result){
          that.initTable();
 })

axios底层post提交的参数会封装到request playload请求载体中,使用request.getParamter是无法接受到请求载体的参数, request.getParamter它只能接受query param参数和form data参数。我们可以借助qs把请求载体的参数转换为form data参数。转换的步骤

(1) 在网页中引入qs
    <script type="text/javascript" src="js/qs.min.js"></script>
(2) 把Qs对象重写赋值一个参数 
    var qs=Qs;
(3) 把  request playload使用 stringify方法转换
qs.stringify({"":"","":""})

3.2.servlet

private void delete(HttpServletRequest req, HttpServletResponse resp)  throws ServletException, IOException{
        String id = req.getParameter("id");
        int row=empDao.delete(id);
        PrintWriter writer = resp.getWriter();
        if(row==1){ //删除成功
            CommonResult commonResult=new CommonResult(2000,"删除成功",null);
            writer.print(JSON.toJSONString(commonResult));
        }else{ //删除失败
            CommonResult commonResult=new CommonResult(5000,"删除失败",null);
            writer.print(JSON.toJSONString(commonResult));
        }
        writer.flush();
        writer.close();
    }

3.2.dao

   //删除操作
    public int delete(String id) {
        String  sql ="delete from t_emp where emp_id=?";
        return edit(sql,id);
    }

4.添加

4.1.点击添加按钮显示一个弹出层

 

el-dialog
            title="添加员工"
            :visible.sync="addDialogVisible"
            width="30%"
           >
        <!--:model==绑定表单数据-->
        <el-form :model="addform">
            <el-form-item label="姓名" label-width="40px">
                <el-input v-model="addform.empName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="性别" label-width="40px">
                <el-radio v-model="addform.empSex" :label="0">男</el-radio>
                <el-radio v-model="addform.empSex" :label="1">女</el-radio>
            </el-form-item>
            <el-form-item label="年龄" label-width="40px">
                <el-input v-model="addform.empAge" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="薪水" label-width="40px">
                <el-input v-model="addform.empSalary" autocomplete="off"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="">确 定</el-button>
        </span>
    </el-dialog>

4.2.添加点击事件

//添加的点击事件
            addEmp(){
                 var qs=Qs;
                 var that=this;
                 axios.post("EmpServlet?method=insert",qs.stringify(this.addform)).then(function(result){
                         if(result.data.code===2000){
                               that.$message.success(result.data.msg);
                               that.initTable();//重新加载表格
                               that.addDialogVisible=false;
                         }
                 })
            }

4.3.添加servlet

//添加
    private void insert(HttpServletRequest req, HttpServletResponse resp)  throws ServletException, IOException{
        String name = req.getParameter("empName");
        String sex = req.getParameter("empSex");
        String age = req.getParameter("empAge");
        String salary = req.getParameter("empSalary");
        Emp emp = new Emp(name,Integer.parseInt(sex),Integer.parseInt(age),Double.parseDouble(salary));
        int row=empDao.add(emp);
        PrintWriter writer = resp.getWriter();
        if(row==1){ //添加成功
            CommonResult commonResult=new CommonResult(2000,"添加成功",null);
            writer.print(JSON.toJSONString(commonResult));
        }else{ //添加失败
            CommonResult commonResult=new CommonResult(5000,"添加失败",null);
            writer.print(JSON.toJSONString(commonResult));
        }
        writer.flush();
        writer.close();
    }

4.4.dao的代码

/**
     * 添加功能
     * @param emp
     * @return
     */
    public int add(Emp emp) {
        String sql="insert into t_emp(emp_name,emp_sex,emp_age,emp_salary) values(?,?,?,?)";
        return edit(sql,emp.getEmpName(),emp.getEmpSex(),emp.getEmpAge(),emp.getEmpSalary());
    }

4.5.表单校验

Form 组件提供了表单验证的功能,只需要通过 rules 属性传入约定的验证规则,并将 Form-Item 的 prop 属性设置为需校验的字段名即可

如果不符合表单的校验应该不允许表单提交

 

//添加的点击事件
            addEmp(){
                this.$refs['addRuleForm'].validate((valid) => {
                    if (valid) { //表单校验通过
                        var qs=Qs;
                        var that=this;
                        axios.post("EmpServlet?method=insert",qs.stringify(this.addform)).then(function(result){
                            if(result.data.code===2000){
                                that.$message.success(result.data.msg);
                                that.initTable();//重新加载表格
                                that.addDialogVisible=false; //隐藏弹出层
                            }
                        })
                    }
                });

            }

5.修改

5.1.点击编辑回显数据

<!--修改员工的对话框-->
    <el-dialog
            title="修改员工"
            :visible.sync="editDialogVisible"
            width="30%"
    >
        <!--:model==绑定表单数据-->
        <el-form :model="editform" :rules="addRules" ref="addRuleForm">
            <el-form-item label="姓名" label-width="80px" prop="empName">
                <el-input v-model="editform.empName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="性别" label-width="80px">
                <el-radio v-model="editform.empSex" :label="0">男</el-radio>
                <el-radio v-model="editform.empSex" :label="1">女</el-radio>
            </el-form-item>
            <el-form-item label="年龄" label-width="80px" prop="empAge">
                <el-input v-model.number="editform.empAge" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="薪水" label-width="80px">
                <el-input v-model="editform.empSalary" autocomplete="off"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editEmp">确定修改</el-button>
        </span>
    </el-dialog>

注意: :visible.sync="editDialogVisible" 一定要在vue data中定义editDialogVisible :model="editform" 保证在vue data中定义editform

 <el-button @click="edit(scope.row)" type="success" size="small" icon="el-icon-edit" plain>编辑</el-button>

  //修改按钮点击事件
            edit(row){
                  //1.显示修改弹出层
                  this.editDialogVisible=true;
                  //2.数据回显
                  this.editform=row;
            },

5.2.点击确认修改按钮

<el-button type="primary" @click="editEmp">确定修改</el-button>

 //确认修改
editEmp(){
    var that=this;
    var qs=Qs;
    this.$refs['editRuleForm'].validate((valid) => {
        if (valid) { //表单校验通过
            axios.post("EmpServlet?method=edit",qs.stringify(this.editform)).then(function(result){
                if(result.data.code===2000){
                    that.$message.success(result.data.msg);//弹出成功的消息
                    that.editDialogVisible=false; //隐藏修改对话框
                    that.initTable(); //重新加载表格数据
                }
            })
        }
    });
},

5.3.servlet

//修改操作
    private void edit(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
        String name = req.getParameter("empName");
        String sex = req.getParameter("empSex");
        String age = req.getParameter("empAge");
        String salary = req.getParameter("empSalary");
        String  id = req.getParameter("empId");
        Emp emp = new Emp(Integer.parseInt(id),name,Integer.parseInt(sex),Integer.parseInt(age),Double.parseDouble(salary));
        int row=empDao.update(emp);
        PrintWriter writer = resp.getWriter();
        if(row==1){ //删除成功
            CommonResult commonResult=new CommonResult(2000,"修改成功",null);
            writer.print(JSON.toJSONString(commonResult));
        }else{ //删除失败
            CommonResult commonResult=new CommonResult(5000,"修改失败",null);
            writer.print(JSON.toJSONString(commonResult));
        }
        writer.flush();
        writer.close();
    }

5.4.dao

 /**
     * 修改功能
     * @param emp
     * @return
     */
    public int update(Emp emp) {
        String sql = "update t_emp set emp_name=?,emp_sex=?,emp_age=?,emp_salary=? where emp_id=?";
        return edit(sql,emp.getEmpName(),emp.getEmpSex(),emp.getEmpAge(),emp.getEmpSalary(),emp.getEmpId());
    }

6.登录

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录页面</title>
    <!--引入element得css样式-->
    <link type="text/css" rel="stylesheet" href="css/index.css"/>
    <!--引入vue得js文件 这个必须在element之前引入-->
    <script type="text/javascript" src="js/vue.js"></script>
    <script type="text/javascript" src="js/qs.min.js"></script>
    <script type="text/javascript" src="js/axios.min.js"></script>
    <!--element得js文件-->
    <script type="text/javascript" src="js/index.js"></script>
    <style>
        #loginBox {
            width: 450px;
            height: 200px;
            border: 2px #ccc solid;
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            padding: 30px 20px;
        }
    </style>
</head>
<body>
<div class="box">
    <div id="loginBox">
        <el-form label-width="80px" :model="loginForm" :rules="rules" ref="loginFormRef">
            <el-form-item label="账号:" prop="username">
                <el-input v-model="loginForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码:" prop="password">
                <el-input v-model="loginForm.password"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm()">登录</el-button>
            </el-form-item>
        </el-form>
    </div>
</div>

<script>
    var app = new Vue({
        el: ".box",
        data: {
            loginForm: {},
            //校验规则
            rules: {
                username: [
                    {required: true, message: "请输入账号", trigger: "blur"},
                    {min: 5, max: 12, message: "账号的长度必须{5~12}", trigger: "blur"},
                ],
                password: [
                    {required: true, message: "请输入密码", trigger: "blur"},
                    {min: 6, max: 12, message: "密码的长度必须{6~12}", trigger: "blur"},
                ]
            }
        },
        methods: {
            submitForm() {
                var that = this;
                var qs = Qs;
                this.$refs['loginFormRef'].validate((valid) => {
                    if (valid) {
                        axios.post("LoginServlet", qs.stringify(this.loginForm)).then(function (result) {
                            if (result.data.code === 2000) {
                                that.$message.success(result.data.msg);
                                location.href = "elementui01.html"
                            } else {
                                that.$message.error(result.data.msg);
                            }
                        });
                    }
                })
            }
        }
    })
</script>
</body>
</html>

6.2.servlet66.3

@WebServlet(name="LoginServlet",urlPatterns = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if("admin".equals(username)&&"123456".equals(password)){
            HttpSession session = req.getSession();
            session.setAttribute("username",username);
            CommonResult commonResult=new CommonResult(2000,"登录成功",null);
            writer.print(JSON.toJSONString(commonResult));
        }else{
            CommonResult commonResult=new CommonResult(5000,"账号或密码错误",null);
            writer.print(JSON.toJSONString(commonResult));
        }
        writer.flush();
        writer.close();
    }
}

6.3.登录过滤器

@WebFilter(filterName = "LoginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        //1.接受请求路径
        String path = request.getRequestURI();
        //2.设置放行的路径
        if(path.contains("login.html")
                ||path.contains("LoginServlet")
                ||path.endsWith(".js")
                ||path.endsWith(".css")
                ||path.endsWith(".jpg")
                ||path.endsWith(".gif")
                ||path.endsWith(".jpeg")
                ||path.endsWith(".png")){
             filterChain.doFilter(request,response);
             return;
        }
        //3.判断用户是否登录
        Object username = request.getSession().getAttribute("username");
        if(username!=null){
            filterChain.doFilter(request,response);
            return;
        }

        //4.跳转到登录页面
        response.sendRedirect("login.html");

    }

    @Override
    public void destroy() {

    }
}
Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐