vue技术文档

1、用户注册

2020-03-04  本文已影响0人  wqjcarnation

预备知识(备查):
1)element-ui使用手册
2)vue+servlet
3 ) axios

建表语句

    CREATE TABLE `t_user` (
      `user_id` int(11) NOT NULL AUTO_INCREMENT,
      `user_name` varchar(255) DEFAULT NULL,
      `user_pwd` varchar(255) DEFAULT NULL,
      `user_email` varchar(255) DEFAULT NULL,
      `user_idcard` varchar(255) DEFAULT NULL,
      `user_power` int(255) DEFAULT NULL,
      PRIMARY KEY (`user_id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
    SET FOREIGN_KEY_CHECKS=1;

目标

本章制作前后端分离的项目,前后端实现跨域访问

项目位置

前台vue:d:\vue\web-vue
后台servlet:D:\study\my12306_vue

框架选择

前端框架选择element-ui
跨域请求选择axios

第一步:新建工程web-vue,并导入常用的包

1.1 d:\vue进入命令行状态,输入以下命令

vue init webpack web-vue

注意:中间有一项eslint选n
1.2 进入d:\vue\web-vue目录,输入以入命令

cnpm install 
cnpm install vue-router vue-resource --save
cnpm install element-ui -S
cnpm install axios --save
cnpm install --save vue-axios
cnpm install qs 
cnpm install vuex  --save

1.3 确认是否安装成功(axios同理)
查看配置文件package.json,是否有element-ui组件的版本号 如下图:

在node_modules中可以看到 element-ui的文件夹 ,所有安装的源文件可以在这里面找到

第二步 编码

参考官网:https://element.eleme.cn/#/zh-CN/component/quickstart

在main.js文件中引入 element 组件

以下步骤皆可查看element手册

step 1 引入

引入方式有两种 1)完整引入 2)按需引入 初学者可以选择完整引入,以后熟练了再按需引入
完整引入
在 main.js 中写入以下内容:

import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import App from './App.vue';

Vue.use(ElementUI);

new Vue({
  el: '#app',
  render: h => h(App)
});

注意,如有与原有引入重复的,要出重复。比如vue,app就不需要重复引入

国际化(了解)

Element 组件内部默认使用中文,若希望使用其他语言,则需要进行多语言设置。以英文为例,在 main.js 中:

import lang from 'element-ui/lib/locale/lang/en'
import locale from 'element-ui/lib/locale'
// 设置语言
locale.use(lang)

经过上述两步,完成了element-ui的引入

引入qs备用

    import qs from 'qs';
    Vue.prototype.$qs = qs;

axios vuex 引入略,直接上main.js完整代码

1)main.js完整的代码如下

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import lang from 'element-ui/lib/locale/lang/en'
import locale from 'element-ui/lib/locale'
//以下4行引入axios
import axios from 'axios'
import VueAxios from 'vue-axios'
  axios.defaults.withCredentials = true//这个默认即为false,如果改为true,可以传递session信息,后端要做相应修改来放行,

Vue.prototype.$axios = axios //在vue中使用axios
//vuex组件,用于state管理
import Vuex from 'vuex';
// 设置语言 
locale.use(lang)
Vue.use(ElementUI);
Vue.use(Vuex);
import qs from 'qs';
Vue.prototype.$qs = qs;


/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

测试

进入命令行状态运行

    npm run dev

浏览器输入http://localhost:8080/#/,出现如下页面即为成功

image.png

2)编写注册页面Register.vue

https://element.eleme.cn/#/zh-CN/component/form
页面里找到如下表单,

image.png

在src/components目录下新建user目录
后在目录下新建Register.vue文件
拷贝element-ui对应页面的内容到Register.vue里
如图:


image.png

3)路由文件router/index.js

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Register from '@/components/reg/Register.vue'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    },{
      path: '/reg',
      name: 'Register',
      component: Register
    }
  ]
})

启动并测试:

  npm run dev
  http://localhost:8080/#/reg
image.png

继续完成界面开发

<template>
  <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
    <el-form-item label="用户名" prop="username">
      <el-input v-model="ruleForm.username"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="pass">
      <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="确认密码" prop="checkPass">
      <el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="ruleForm.email"></el-input>
    </el-form-item>
    <el-form-item label="身份证号" prop="idcard">
      <el-input v-model="ruleForm.idcard"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
      <el-button @click="resetForm('ruleForm')">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
  export default {
    data() {
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.ruleForm.checkPass !== '') {
            this.$refs.ruleForm.validateField('checkPass');
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.ruleForm.pass) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        ruleForm: {
          username: '',
          pass: '',
          checkPass: '',
          email: '',
          idcard: ''
        },
        rules: {
          username: [{
              required: true,
              message: '请输入活动名称',
              trigger: 'blur'
            },
            {
              min: 6,
              max: 20,
              message: '长度在 6 到 20 个字符',
              trigger: 'blur'
            }
          ],
          pass: [{
            required: true,
            validator: validatePass,
            trigger: 'blur'
          }],
          checkPass: [{
            required: true,
            validator: validatePass2,
            trigger: 'blur'
          }]
        }
      };
    },
    methods: {
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            alert('submit!');
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    }
  }
</script>

<style>
</style>

第四步:后台D:\study\my12306_vue

引入必要的包:

image.png

1)src的com.neuedu.utils包下新建一个过滤器,增加跨域权限配置CorsFilter.java内容如下

package com.neuedu.utils;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class CorsFilter
 */
@WebFilter(filterName="/CodeFilter",urlPatterns="/*")
public class CorsFilter implements Filter {
    private final int time = 20 * 24 * 60 * 60;

    /**
     * Default constructor.
     */
    public CorsFilter() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see Filter#destroy()
     */
    public void destroy() {
        // TODO Auto-generated method stub
    }

    /**
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse resp = (HttpServletResponse) response;
                
        // 允许跨域的主机地址,允许任意domain访问 
        //坑:前台axios设置withCredentials: true后,Access-Control-Allow-Origin的值不可以为*
        resp.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");
        /* 允许跨域的请求头 */
        resp.setHeader("Access-Control-Allow-Headers", "*");
        /* 允许跨域的请求方法GET, POST, HEAD 等 */
        resp.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
        /* 重新预检验跨域的缓存时间 (s) */
        resp.setHeader("Access-Control-Max-Age", time + "");
        /* 是否携带cookie,session支持 */
        resp.setHeader("Access-Control-Allow-Credentials", "true");  
        chain.doFilter(request, resp);
    }
......

}

db.properties 下增加如下设置

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/java16?characterEncoding=UTF-8&useUnicode=true
userName=root
passWord=root

数据库工具类DBUtil.java主要代码

// 用于数据库连接的方法
public static Connection getConnection() {
    Connection conn = null;
    try {
        //载入资源文件
        Properties prop=new Properties();
        prop.load(DBUtil.class.getResourceAsStream("/db.properties"));
        //读取资源文件各属性
        String driver=prop.getProperty("driver");
        String url = prop.getProperty("url");
        String UserName = prop.getProperty("userName");
        String password = prop.getProperty("passWord");
        Class.forName(driver);
        conn = DriverManager.getConnection(url, UserName, password);
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("数据库连接异常" + e.getMessage());
    }
    return conn;
}

User 实体类

package com.neuedu.pojo;

public class User {
    // 主键id,自增
    private int id;
    private String userName;
    private String userPwd;
    private String email;
    private String idCard;
        private String userPwd1;
        private int power=0;
    .......省略get/set
}

2)RegServlet

    @WebServlet("/regServlet")
    public class RegServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
           
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request,response);
        }
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //request.setCharacterEncoding("utf-8");
            //response.setCharacterEncoding("utf-8");
            //接收用户输入
            String name=request.getParameter("username");
            System.out.println(name);
            String password=request.getParameter("passwrod");
            String repassword=request.getParameter("checkPass");
            String email=request.getParameter("email");
            String idCard=request.getParameter("idcard");
            //String[] cookieFlag=request.getParameterValues("CookieYN");
            //System.out.println(cookieFlag);
            //打包user
            User user=new User();
            user.setUserName(name);
            user.setUserPwd(password);
            user.setUserPwd1(repassword);
            user.setEmail(email);
            user.setIdCard(idCard);
            //调用service进行处理
            IUserService userService=new UserServiceImpl();
            int i=userService.addUser(user);
            //返回处理结果
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out=response.getWriter();
            if(i>0){
                out.println("success");
            }else{
                out.println("failure");
            }
        }
    
    }

UserServiceImpl

public class UserServiceImpl implements IUserService {
    IUserDao userDao=new UserDaoImpl();

    @Override
    public int addUser(User user) {
        int i=0;
        
        //验证合法性
        //比如用户名是否重复
        //两次密码是否一致。。。。。。
        //如果验证通过,就存库
        User dbuser=userDao.getUser(user);
        //调用dao存库
        if(dbuser!=null){//已经被注册过了
            return 0;
        }else{
            i=userDao.add(user);
        }
        
        return i;
    }

    @Override
    public User getUser(User user) {
        return userDao.getUser(user);
    }

}

UserDaoImpl

public class UserDaoImpl implements IUserDao {
    PreparedStatement ps=null;
    Connection conn=null;
    ResultSet rs=null;
    @Override
    public int add(User user) { 
        int i=0;
        try {
            conn=DBUtil.getConnection();
            ps=conn.prepareStatement("INSERT INTO t_user VALUES(NULL,?,?,?,?,?)");
            ps.setString(1,user.getUserName());
            ps.setString(2,user.getUserPwd());
            ps.setString(3,user.getEmail());
            ps.setString(4,user.getIdCard());
            ps.setInt(5, user.getPower());
            i=ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        return i;
    }
    @Override
    public User getUser(User user) {
        User dbuser=null;
        conn=DBUtil.getConnection();
        try {
            ps=conn.prepareStatement("select * from t_user where user_name=? and user_pwd=?");
            ps.setString(1, user.getUserName());
            ps.setString(2, user.getUserPwd());
            rs=ps.executeQuery();
            if(rs.next()){//如果有该用户
                dbuser=new User();
                dbuser.setId(rs.getInt("user_id"));
                dbuser.setUserName(rs.getString("user_name"));
                dbuser.setUserPwd(rs.getString("user_pwd"));
                dbuser.setEmail(rs.getString("user_email"));
                dbuser.setIdCard(rs.getString("user_idcard"));
                dbuser.setPower(rs.getInt("user_power"));
            }
        } catch (SQLException e) {

            e.printStackTrace();
        }
        DBUtil.closeConnection(rs, ps, conn);
        return dbuser;
    }

}

页面添加axios请求

改造methods部分

        methods: {
          submitForm(formName) {
            this.$refs[formName].validate((valid) => {
              if (valid) {
                //alert('submit!');
//此处为新增加代码,用于请求后台进行注册   

        let  obj = this.$qs.stringify(this.ruleForm)
        //此处为新增加代码,用于请求后台进行注册
        this.$axios.post('http://localhost:8082/my12306_vue/regServlet', obj)
          .then(response => {
            alert(response.data);
          })

              } else {
                console.log('error submit!!');
                return false;
              }
            });
          },
          resetForm(formName) {
            this.$refs[formName].resetFields();
          }
        }

测试

npm run dev

启动服务,浏览器输入
http://localhost:8080/#/reg

image.png

点击save按钮,显示成功

image.png
上一篇下一篇

猜你喜欢

热点阅读