欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

从零开始自学微信小程序(一)

程序员文章站 2022-05-28 13:24:03
...

开发环境:MyEclipse2017 + Tomcat 8.5 + MySQL 5.7.26 + 微信开发者工具

emmmmm这些环境的搭建就不写了,网上太多了

之前通过看视频已经大概了解了微信小程序,现在开始实践

今天完成了简单的登录及登录成功后的页面跳转(还不完善,后期完善了会进行更新)

数据库设计
从零开始自学微信小程序(一)从零开始自学微信小程序(一)

前端部分代码(微信开发者工具实现):

页面结构:(其中页面 tabMembers 和页面 tabMine 只是为了实现导航栏,里面的内容只是在view组件里面写了一句话,所以下面不会写)
从零开始自学微信小程序(一)
全局配置文件 app.json

{
  "pages": [
    "pages/index/index",            //新建页面可以直接在此处加,方便又安全
    "pages/tabMembers/tabMembers",
    "pages/tabMine/tabMine",
    "pages/test/test",
    "pages/testfail/testfail",
    "pages/testsuccess/testsuccess",
    "pages/logs/logs"
  ],
  "window": {
    "navigationBarBackgroundColor": "#1296db",
    "navigationBarTitleText": "哦嚯",
    "navigationBarTextStyle": "white",
    "enablePullDownRefresh": true,               //设置下拉刷新
    "backgroundTextStyle": "dark"
  },
  "tabBar":{                                        // 底部导航栏
    "selectedColor":"#1296db",
    "list":[
      {
        "pagePath":"pages/tabMembers/tabMembers",
        "text":"签到",
        "iconPath":"images/all.png",
        "selectedIconPath":"images/all_active.png"
      },
      {
        "pagePath": "pages/tabMine/tabMine",
        "text": "我的",
        "iconPath": "images/user.png",
        "selectedIconPath": "images/user_active.png"
      }
    ]
  },
  "style": "v2",
  "sitemapLocation": "sitemap.json"
}

登录页面 index.wxml

<!--index.wxml-->
<view class="container">
  <view class="login-form">
    <form bindsubmit="formSubmit" class="form">
      <!-- 学号 -->
      <view class="stunum">
        <view class="weui-cell weui-cell_input" style="">
          <image class="stuNumImage" src="../../images/user.png"></image>
          <view class="weui-cell_bd">
            <input class="weui-input" name="stunum" bindinput="stunuminput" value="{{stunum}}" placeholder="请输入学号" />
          </view>
        </view>
      </view>

      <!-- 密码 -->
      <view class="password">
        <view class="weui-cell weui-cell_input">
          <image class="stuNumImage" src="../../images/password.png"></image>
          <view class="weui-cell_bd">
            <input class="weui-input" type="password" name="password" bindinput="passwordinput" value="{{password}}" placeholder="请输入密码"/>
          </view>
        </view>
      </view>

      <view class="loginBtnView">
        <button class="loginBtn" size="{{primarySize}}" form-type="submit" disabled="{{disabled}}">登录</button>
      </view>
    </form>

  </view>
</view>

登录功能的 index.js 部分代码

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    disabled:false,
    stunum:"",
    password:"",
    stunuminput:false,
    passwordinput:false
  },

  stunuminput:function(e){
    this.setData({ stunum: e.detail.value });  //将input框里面的数据赋值给页面初始数据stunum
    this.setData({stunuminput:true});
    if (this.data.stunuminput==true && this.data.passwordinput==true){
      this.setData({disabled:false});
    }
  },

  passwordinput: function (e) {
    this.setData({ password: e.detail.value });
    this.setData({ passwordinput: true });
    if (this.data.stunuminput == true && this.data.passwordinput == true) {
      this.setData({ disabled: false });
    }
  },

  formSubmit:function(e){
    console.log(e);
    this.setData({disabled:true});
    wx.request({
      url: 'http://localhost:8080/wechat/TestServlet',      //后端的url地址,这里是本地地址
      data:{         //传给后端的数据
        stunum:e.detail.value.stunum,
        password:e.detail.value.password
      },
      method: 'GET',
      header:{
        'content-type':'application/json'
      },
      success:function(res){
        console.log(res);
        if(res.statusCode==200){      // HTTP状态码,200表示已经获取到数据
          if(res.data=="error"){
            wx.navigateTo({
              url: '../testfail/testfail'          //不带tabBar的页面跳转到不带tabBar的页面
            })
          }else{
            wx.switchTab({
              url: '../tabMembers/tabMembers'           //不带tabBar的页面跳转到带tabBar的页面
            })
          }
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({disabled:false});
  },
  
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.stunum == '' || this.data.password == '') {
      this.setData({ disabled: true });
    } else {
      this.setData({ disabled: false });
    }
  },

登录页面的样式 index.wxss,登录页面还应用了weui的样式,可以下载了之后直接在app.wxss中导入:@import ‘weui.wxss’;

/**index.wxss**/

page {
  height: 100%;
  background-size: 100%;
}

.container {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 0;
  box-sizing: border-box;
}

/* 表单内容 */

.login-form {
  margin-top: 50%;
  flex: auto;
  height: 100%;
}

/* 输入框 */

.stunum {
  width: 90%;
  height: 80rpx;
  margin: 0 auto;
  border: 1px solid #ccc;
  border-radius: 50rpx;
}

.password {
  width: 90%;
  height: 80rpx;
  margin: 0 auto;
  border: 1px solid #ccc;
  border-radius: 50rpx;
  margin-top: 20rpx;
}

/* 按钮 */

.loginBtnView {
  margin-top: 0px;
  margin-bottom: 0px;
  padding-bottom: 0px;
}

.loginBtn {
  width: 90%;
  height: 80rpx;
  line-height: 80rpx;
  margin-top: 35rpx;
  color: #fff;
  background-color: #1296db;
  border: 0.1rpx solid #ccc;
  border-radius: 40rpx;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}

.stuNumImage{
  margin-right: 10px;
  width: 20px;
  height: 20px;
}

然后是后台,在myeclipse中新建应该web项目,目录结构如下
从零开始自学微信小程序(一)
先建立实体 User.java

package model;

public class User {
	private String stunum;
    private String password;
	public String getStunum() {
		return stunum;
	}
	public void setStunum(String stunum) {
		this.stunum = stunum;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}


数据库操作 DB.java (不规范又怎么样呢,又不是不能用hhhhh)

package db;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import model.User;

public class DB {
	Connection ct=null;
    Statement stmt=null;
    public DB(){
    	try{	
    		Class.forName("com.mysql.jdbc.Driver");
    		ct=DriverManager.getConnection("jdbc:mysql://localhost:3306/aperson","root","root");
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
    public User checkUser(String stunum,String password) throws SQLException{
    	try{
    		stmt=ct.createStatement();
    		String sql = "select * from user where stunum='"+stunum+"' and password='"+password+"'";
    		ResultSet rs=stmt.executeQuery(sql);
    		User user=new User();
    		while(rs.next()){
    			user.setStunum(rs.getString(1));////////////第一个属性
    			user.setPassword(rs.getString(2));/////////第二个属性
    			return user;	///////////查到就返回对象
    		}
            return null;
    	}catch(Exception e){
     		e.printStackTrace();
    		return null;
    	}finally{
    		ct.close();
    		stmt.close();
    	}

    }
}


然后是 TestServlet.java 创建在默认的包下面

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.User;
import db.DB;

public class TestServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		// 设置响应头允许ajax跨域访问
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "GET,POST");

		// 获取微信小程序get的参数值并打印
		String stunum = request.getParameter("stunum");
		String password = request.getParameter("password");
		System.out.println(stunum);
		System.out.println(password);

		DB db = new DB();/// 建立完成判断对象
		HttpSession session = request.getSession();// 创建保存信息对象
		User user = (User) session.getAttribute("user");

		if (user == null) {// 第一次进入
			try {
				user = db.checkUser(stunum, password);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} /// 如果账户密码正确,把返回的对象抛给user,不正确对象则为空
		}
		session.setAttribute("user", user);/// 保存对象
		Writer out = response.getWriter();

		if (user != null) {/// 有对象,用户名密码正确
			out.write("success");////////////////////// 向小程序返回结果
		} else {// 对象为空
			out.write("error");
		}
		out.flush();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);

	}

}

然后记得在 web.xml 配置 servlet

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name></display-name>
  <servlet>
    <servlet-name>TestServlet</servlet-name>
    <servlet-class>TestServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>TestServlet</servlet-name>
    <url-pattern>/TestServlet</url-pattern>
  </servlet-mapping>
</web-app>

最后的实现效果:
从零开始自学微信小程序(一)
从零开始自学微信小程序(一)
从零开始自学微信小程序(一)
从零开始自学微信小程序(一)
从零开始自学微信小程序(一)