草庐IT

【微信小程序系列】小程序简单连接后端数据库完整示例(附免费下载的源码)(Servlet)

Tuerlechat, 2023-04-25 原文

【微信小程序系列】小程序简单连接后端数据库完整示例(附免费下载的源码)(Servlet)

登录页面

login.wxml

<view class="page">
    <loading hidden="{{loadingHidden}}" bindchange="loadingChange" bindtap="tapLoading">
        加载中...
    </loading>
    <modal no-cancel="true" hidden="{{modalHidden}}" bindconfirm="modalConfirm" bindcancel="modalCancel">
        {{modalContent}}
    </modal>
    <view class="page__hd">
    </view>
    <view class="page__bd">
        <form bindsubmit="formSubmit" bindreset="formReset">
            <view class="section">
                <view class="section__title">编号</view>
                <input type="number" bindinput="inputChange" id="username" placeholder="请输入编号"/>
            </view>
            <view class="section">
                <view class="section__title">密码</view>
                <input type="number" bindinput="inputChange" id="password" placeholder="请输入密码"/>
            </view>
            <view class="btn-area">
                <view class="button-wrapper">
                    <button type="primary" formType="submit" class="primary">查询</button>
                </view>
                <view class="button-wrapper">
                    <button type="default" formType="reset">重置</button>
                </view>
            </view>
        </form>
    </view>
</view>

login.js

// pages/login/login.js
var inputs = {};
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loadingHidden: true,
    modalHidden: true,
    modalContent: '',
    inputs: {}
  },
  //input事件
  inputChange: function (e) {
    inputs[e.currentTarget.id] = e.detail.value
  },
  //loading组件的绑定事件
  tapLoading: function () {
    this.setData({
      loadingHidden: true
    })
  },

  loading: function () {
    this.setData({
      loadingHidden: false
    })
  },
  //重置按钮
  formReset: function () {
    inputs = {}
    wx.setStorageSync('username', '')
    wx.setStorageSync('password', '')
  },
  //提交按钮
  formSubmit: function () {
    var page = this
    if (inputs['username'] == null || inputs['username'] == '') {
      page.showModal('请输入编号')
      return
    }
    if (inputs['password'] == null || inputs['password'] == '') {
      page.showModal('请输入密码')
      return
    }
    page.loading()
    var that = this;
    wx.request({
      url: 'http://localhost:8080/web_servlet/LoginServlet',
      method: 'GET', //请求方式
      header: { 
          "content-type":"application/x-www-form-urlencoded"
      },
      data: {
        teano:inputs['username'],
        teapwd:inputs['password']
      },
      success: function(res) {
        // ,JSON.stringify(res.data)
         console.log("获取到的用户信息成功: " + res.data);
         that.setData({
          list : res.data,
        })
         if(res.data == "登录成功") {
 
          wx.hideNavigationBarLoading()

          wx.navigateTo({
            // 必须要序列化成字符串,URL编码自动完成
            url: '/pages/index2/index2?data=' + JSON.stringify(res.data) + '&username=' + inputs['username']
          })
         } else {
          that.setData({
            loadingHidden: true
          })
          wx.showToast({
            title: '登录失败',
            icon: 'none',
            duration: 1500,
            })
         }
      },
      
      fail: function() {
        app.consoleLog("请求数据失败");
      },
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    
  },

  //提交按钮提示
  showModal: function (msg) {
    this.setData({
      modalHidden: false,
      modalContent: msg
    })
  },
  modalCancel: function () {
    this.setData({
      modalHidden: true
    })
  },
  modalConfirm: function () {
    this.setData({
      modalHidden: true
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    // 调用应用实例的方法获取全局数据
    var that = this
    inputs['username'] = wx.getStorageSync('username')
    inputs['password'] = wx.getStorageSync('password') // 这里没有加密安全性较低
    this.setData({
      inputs: inputs
    })
  },

})

login.wxss

/**index.wxss**/
.userinfo {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.userinfo-avatar {
  width: 128rpx;
  height: 128rpx;
  margin: 20rpx;
  border-radius: 50%;
}

.userinfo-nickname {
  color: #aaa;
}

.usermotto {
  margin-top: 200px;
}

app.wxss

page {
  background-color: #fbf9fe;
  height: 100%;
}
.container {
  display: flex;
  flex-direction: column;
  min-height: 100%;
  justify-content: space-between;
}
.page-header {
  display: flex;
  font-size: 32rpx;
  color: #aaa;
  margin-top: 50rpx;
  flex-direction: column;
  align-items: center;
}
.page-header-text {
  padding: 20rpx 40rpx;
}
.page-header-line {
  width: 150rpx;
  height: 1px;
  border-bottom: 1px solid #ccc; 
}

.page-body {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  flex-grow: 1;
  overflow-x: hidden;
}
.page-body-wrapper {
  margin-top: 100rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}
.page-body-wrapper form {
  width: 100%;
}
.page-body-wording {
  text-align: center;
  padding: 200rpx 100rpx;
}
.page-body-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #fff;
  margin-bottom: 50rpx;
  width: 100%;
  padding: 50rpx 0 150rpx 0;
}
.page-body-title {
  margin-bottom: 100rpx;
  font-size: 32rpx;
}
.page-body-text {
  font-size: 30rpx;
  line-height: 26px;
  color: #ccc;
}
.page-body-text-small {
  font-size: 24rpx;
  color: #000;
  margin-bottom: 100rpx;
}
.page-body-form {
  width: 100%;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  width: 100%;
  border: 1px solid #eee;
}
.page-body-form-item {
  display: flex;
  align-items: center;
  margin-left: 30rpx;
  border-bottom: 1px solid #eee;
  height: 88rpx;
  font-size: 34rpx;
}
.page-body-form-key {
  width: 180rpx;
  color: #000;
}
.page-body-form-value {
  flex-grow: 1;
}
.page-body-form-value .input-placeholder {
  color: #b2b2b2;
}

.page-body-form-picker {
  display: flex;
  justify-content: space-between;
  height: 100rpx;
  align-items: center;
  font-size: 36rpx;
  margin-left: 20rpx;
  padding-right: 20rpx;
  border-bottom: 1px solid #eee;
}
.page-body-form-picker-value {
  color: #ccc;
}

.page-body-buttons {
  width: 100%;
}
.page-body-button {
  margin: 25rpx;
}
.page-body-button image {
  width: 150rpx;
  height: 150rpx;
}

.green{
    color: #09BB07;
}
.red{
    color: #F76260;
}
.blue{
    color: #10AEFF;
}
.yellow{
    color: #FFBE00;
}
.gray{
    color: #C9C9C9;
}

.strong{
    font-weight: bold;
}

.bc_green{
    background-color: #09BB07;
}
.bc_red{
    background-color: #F76260;
}
.bc_blue{
    background-color: #10AEFF;
}
.bc_yellow{
    background-color: #FFBE00;
}
.bc_gray{
    background-color: #C9C9C9;
}

.tc{
    text-align: center;
}

.page input,checkbox{
    padding: 20rpx 30rpx;
    background-color: #fff;
}
checkbox, radio{
    margin-right: 10px;
}

.btn-area{
    padding: 0 30px;
}
.btn-area button{
    margin-top: 20rpx;
    margin-bottom: 20rpx;
}

.page {
    min-height: 100%;
    flex: 1;
    background-color: #FBF9FE;
    font-size: 32rpx;
    font-family: -apple-system-font,Helvetica Neue,Helvetica,sans-serif;
    overflow: hidden;
}
.page__hd{
    padding: 50rpx 50rpx 50rpx 50rpx;
    text-align: center;
}
.page__title{
    display: inline-block;
    padding: 20rpx 40rpx;
    font-size: 32rpx;
    color: #AAAAAA;
    border-bottom: 1px solid #CCCCCC;
}
.page__info{
    display: inline-block;
    font-size: 38rpx;
    color: #AAAAAA;
}
.page__desc{
    display: none;
    margin-top: 20rpx;
    font-size: 26rpx;
    color: #BBBBBB;
}

.section{
    margin-bottom: 80rpx;
}
.section_gap{
    padding: 0 30rpx;
}
.section__title{
    margin-bottom: 16rpx;
    padding-left: 30rpx;
    padding-right: 30rpx;
}
.section_gap .section__title{
    padding-left: 0;
    padding-right: 0;
}

.shading{
   background-color: #eee;
    background-image: -moz-linear-gradient(45deg,#fff 25%, transparent 25%, transparent 50%,#fff 50%,#fff 75%, transparent 75%, transparent);
    background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(25%,rgba(255,255,255,0.2)),color-stop(25%,transparent),color-stop(50%,transparent),color-stop(50%,rgba(255,255,255,0.2)),color-stop(75%,rgba(255,255,255,0.2)),color-stop(75%,transparent));
    background-size: 16px 16px;

}

主页

index2.wxml

<!--pages/index2/index2.wxml-->
<view>
<text>------获取数据(单条)------\n编号:</text>
<input type="number" bindinput="teanoput" placeholder="请输入编号"/>
<text>\n------获取数据(多条)------\n是否党员:</text>
<radio-group bindchange="cppchange" class="oneline">
  <radio value="true"></radio><text decode="true">&ensp;</text>
  <radio value="false"></radio>
</radio-group>
</view>
<button bindtap="oneInfo">获取数据(单条)</button><text>\n</text>
<button bindtap="someInfo">获取数据(多条)</button><text>\n</text>
<button bindtap="addInfo">添加数据</button><text>\n</text>
<button bindtap="modInfo">修改数据</button><text>\n</text>
<button bindtap="delInfo">删除数据</button><text>\n</text>
<button bindtap="selectAll">刷新数据</button>
<view wx:for="{{list}}">
  <view>
    <text>
        编号:----------{{list[index].teano}}------------\n
        姓名:{{list[index].teaname}}\n
        密码:{{list[index].teapwd}}\n
    </text>
    <view>图片:<image src="{{list[index].photo}}"/></view>
    <text>
        性别: {{list[index].teasex}}\n
        职称: {{list[index].title}}\n
        出生日期:{{list[index].birthday}}\n
        是否党员:{{list[index].cpp}}\n
        薪水:{{list[index].salary}}
    </text>
  </view>
</view>

index2.js

// pages/index2/index2.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //用于获取的编号
    no: "",
    //用于添加信息字段
    teano: "",
    teapwd: "",
    teaname: "",
    teasex: "",
    title: "",
    photo: "",
    birthday: "",
    cpp: "",
    salary: "",
    //数据显示
    list:[],
  },
   //输入框事件
   teanoput:function(e) {
    this.setData({
      no:e.detail.value
    })
    console.log(e.detail.value);
   },
   cppchange:function(e) {
    this.setData({
      cpp:e.detail.value
    })
    console.log(e.detail.value);
   },

  //获取数据(单条)
  oneInfo:function() {
    var that = this;
    wx.request({
      url: 'http://localhost:8080/web_servlet/TeacherFindServlet',
      method: 'GET', //请求方式
      data: {
        no: this.data.no
      },
      
      header: { 
          "content-type":"application/x-www-form-urlencoded"
      },
      
      success: function(res) {
        // ,JSON.stringify(res.data)
         console.log("获取到的用户信息成功: " + res.data);
         that.setData({
          list : res.data,
        })
      },
      
      fail: function() {
        app.consoleLog("请求数据失败");
      },
    })
  },
  
  //获取数据(多条)
  someInfo:function() {
    var that = this;
    wx.request({
      url: 'http://localhost:8080/web_servlet/TeacherSomeServlet',
      method: 'GET', //请求方式
      data: {
        cpp:this.data.cpp
      },
      header: { 
          "content-type":"application/x-www-form-urlencoded"
      },
      
      success: function(res) {
        // ,JSON.stringify(res.data)
         console.log("获取到的用户信息成功: " + res.data);
         that.setData({
          list : res.data,
        })
      },
      
      fail: function() {
        app.consoleLog("请求数据失败");
      },
    })
  },

  //添加数据
  addInfo:function () {
    var that = this;
    wx.request({
      url: 'http://localhost:8080/web_servlet/TeacherAddServlet',
      method: 'GET', //请求方式
      data: {
        teano:'333',
        teapwd:'333',
        teaname:'张三',
        teasex:'男',
        title:'教授',
        photo:"http://tva3.sinaimg.cn/large/006oOWahly1fprcrxotpkj306o06ojr9.jpg",
        birthday:'1990-3-4',
        cpp:'true',
        salary:'3000.88'
      },
      header: { 
          "content-type":"application/x-www-form-urlencoded"
      },
      
      success: function(res) {
        // ,JSON.stringify(res.data)
         console.log("获取到的用户信息成功: " + res.data);
         that.setData({
          list : res.data,
        })
      },
      
      fail: function() {
        app.consoleLog("请求数据失败");
      },
    })
  },

  //修改数据
  modInfo:function() {
    var that = this;
    wx.request({
      url: 'http://localhost:8080/web_servlet/TeacherModServlet',
      method: 'GET', //请求方式
      data: {
        teano:'333',
        teaname:'李四',
        teasex:'女',
        title:'副教授',
      },
      header: { 
          "content-type":"application/x-www-form-urlencoded"
      },
      
      success: function(res) {
        // ,JSON.stringify(res.data)
         console.log("获取到的用户信息成功: " + res.data);
         that.setData({
          list : res.data,
        })
      },
      
      fail: function() {
        app.consoleLog("请求数据失败");
      },
    })
  },

  //删除数据
  delInfo: function() {
    var that = this;
    wx.request({
      url: 'http://localhost:8080/web_servlet/TeacherDelServlet',
      method: 'GET', //请求方式
      data: {
        no:"333"
      },
      header: { 
          "content-type":"application/x-www-form-urlencoded"
      },
      
      success: function(res) {
        // ,JSON.stringify(res.data)
         console.log("获取到的用户信息成功: " + res.data);
         that.setData({
          list : res.data,
        })
      },
      
      fail: function() {
        app.consoleLog("请求数据失败");
      },
    })
  },

  //刷新数据
  selectAll: function () {
    var that = this;
    wx.request({
      url: 'http://localhost:8080/web_servlet/TeacherAllServlet',
      method: 'GET', //请求方式
      header: { 
          "content-type":"application/x-www-form-urlencoded"
      },
      
      success: function(res) {
        // ,JSON.stringify(res.data)
         console.log("获取到的用户信息成功: " + res.data);
         that.setData({
          list : res.data,
        })
      },
      
      fail: function() {
        app.consoleLog("请求数据失败");
      },
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    wx.request({
      url: 'http://localhost:8080/web_servlet/TeacherAllServlet',
      method: 'GET', //请求方式
      header: { 
          "content-type":"application/x-www-form-urlencoded"
      },
      
      success: function(res) {
        // ,JSON.stringify(res.data)
         console.log("获取到的用户信息成功: " + res.data);
         that.setData({
          list : res.data,
        })
      },
      
      fail: function() {
        app.consoleLog("请求数据失败");
      },
    })
  },
 
})

index2.wxss

/* pages/index2/index2.wxss */
image {
  width: 150px;
  height: 150px;
}
input {
  display: inline-table;
}
.oneline {
  display: inline-table;
}

后端

太多了懒得粘,完整示例资源地址: (55条消息) 微信小程序用Servlet连接数据库源码.zip-Java文档类资源-CSDN文库

Dao层代码

TeacherDao.interface

package com.r.dao;

import java.util.List;

import com.r.pojo.Teacher;

/**
 * 学生dao接口
 * @author
 *
 */
public interface TeacherDao {
	//获取全部信息
	public List<Teacher> getAll();
	//按条件查询(单条)
	public List<Teacher> findInfo(String no);
	//按条件查询(多条)
	public List<Teacher> someInfo(boolean cpp);
	//添加信息
	public int addInfo(Teacher teacher);
	//修改信息
	public int modInfo(Teacher teacher);
	//删除信息
	public int delInfo(String no);
	//登录
	public Teacher selectByTeacher(String teano, String teapwd);
}

TeacherDaoImpl.java

package com.r.dao.impl;

import java.util.ArrayList;
import java.util.List;

import com.r.dao.BaseDao;
import com.r.dao.BaseDao1;
import com.r.dao.TeacherDao;
import com.r.pojo.Teacher;

/**
 * 教师dao实现类
 * @author 
 *
 */
public class TeacherDaoImpl extends BaseDao1 implements TeacherDao {
	
	List<Teacher> teachers = new ArrayList<>();
	
	/**
	 * 获取全部信息
	 */
	@Override
	public List<Teacher> getAll() {
		try {
			if (getConnection()) {
				String sql = "select * from t_teacher";
				rs = executeSQL(sql, null);
				
				while(rs.next()) {
					Teacher tea = new Teacher();
					tea.setTeano(rs.getString("teaNo"));
					tea.setTeapwd(rs.getString("teaPwd"));
					tea.setTeaname(rs.getString("teaName"));		
					tea.setTeasex(rs.getString("teaSex"));
					tea.setTitle(rs.getString("title"));
					tea.setPhoto(rs.getString("photo"));
					tea.setBirthday(rs.getString("birthday"));
					tea.setCpp(rs.getBoolean("cpp"));
					tea.setSalary(rs.getFloat("salary"));
					
					teachers.add(tea);
				}
				return teachers;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			closeResources();
		}
		return null;		
	}

	@Override
	public List<Teacher> findInfo(String no) {
		try {
			if (getConnection()) {
				String sql = "select * from t_teacher where teano=?";
				rs = executeSQL(sql, new Object[] {no});
				
				while(rs.next()) {
					Teacher tea = new Teacher();
					tea.setTeano(rs.getString("teaNo"));
					tea.setTeapwd(rs.getString("teaPwd"));
					tea.setTeaname(rs.getString("teaName"));		
					tea.setTeasex(rs.getString("teaSex"));
					tea.setTitle(rs.getString("title"));
					tea.setPhoto(rs.getString("photo"));
					tea.setBirthday(rs.getString("birthday"));
					tea.setCpp(rs.getBoolean("cpp"));
					tea.setSalary(rs.getFloat("salary"));
					
					teachers.add(tea);
				}
				return teachers;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			closeResources();
		}
		return null;		
	}

	@Override
	public List<Teacher> someInfo(boolean cpp) {
		try {
			if (getConnection()) {
				String sql = "select * from t_teacher where cpp=?";
				rs = executeSQL(sql, new Object[] {cpp});
				
				while(rs.next()) {
					Teacher tea = new Teacher();
					tea.setTeano(rs.getString("teaNo"));
					tea.setTeapwd(rs.getString("teaPwd"));
					tea.setTeaname(rs.getString("teaName"));		
					tea.setTeasex(rs.getString("teaSex"));
					tea.setTitle(rs.getString("title"));
					tea.setPhoto(rs.getString("photo"));
					tea.setBirthday(rs.getString("birthday"));
					tea.setCpp(rs.getBoolean("cpp"));
					tea.setSalary(rs.getFloat("salary"));
					
					teachers.add(tea);
				}
				return teachers;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			closeResources();
		}
		return null;		
	}

	@Override
	public int addInfo(Teacher teacher) {
		try {
			if (getConnection()) {
				String sql = "insert into t_teacher (teano,teapwd,teaname,teasex,title,photo,birthday,cpp,salary) values (?,?,?,?,?,?,?,?,?)";
				int n = executUpdate(sql, new Object[] {teacher.getTeano(),teacher.getTeapwd(),teacher.getTeaname(),teacher.getTeasex(),teacher.getTitle(),teacher.getPhoto(),teacher.getBirthday(),teacher.isCpp(),teacher.getSalary()});
				return n;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		} finally {
			closeResources();
		}
		return 0;		
	}

	@Override
	public int modInfo(Teacher teacher) {
		try {
			if (getConnection()) {
				String sql = "update t_teacher set teaname=?,teasex=?,title=? where teano=?";
				int n = executUpdate(sql, new Object[] {teacher.getTeaname(),teacher.getTeasex(),teacher.getTitle(),teacher.getTeano()});
				return n;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		} finally {
			closeResources();
		}
		return 0;	
	}

	@Override
	public int delInfo(String no) {
		try {
			if (getConnection()) {
				String sql = "	delete from t_teacher where teano=?";
				int n = executUpdate(sql, new Object[] {no});
				return n;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		} finally {
			closeResources();
		}
		return 0;	
	}

	@Override
	public Teacher selectByTeacher(String teano, String teapwd) {
		try {
			if (getConnection()) {
				String sql = "select * from t_teacher where teano=? and teapwd=?";
				rs = executeSQL(sql, new Object[] {teano,teapwd});
				Teacher teacher = null;
				while (rs.next()) {
					teacher = new Teacher();
					teacher.setTeano(rs.getString("teaNo"));
					teacher.setTeapwd(rs.getString("teaPwd"));
					if (teacher.getTeano().equals(teano) && teacher.getTeapwd().equals(teapwd)) {
						return teacher;
					}
				}			
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			closeResources();
		}
		return null;		
	}
	
}

Serlvet代码(部分)

LoginServlet.java

package com.r.servlet;

import java.io.IOException;
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 com.r.dao.TeacherDao;
import com.r.dao.impl.TeacherDaoImpl;
import com.r.pojo.Teacher;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置网页字符编码集
        response.setContentType("text/html;charset=utf-8");
        
        //设置接收参数
        String teano = request.getParameter("teano");
        String teapwd = request.getParameter("teapwd");
        
      	TeacherDao td = new TeacherDaoImpl();
        Teacher teacher = new Teacher();
        teacher = td.selectByTeacher(teano, teapwd);
		if(teacher != null){
			response.getWriter().append("登录成功");
		} else {
			response.getWriter().append("登录失败");
		}

	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

TeacherAllServlet.java

package com.r.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

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 com.alibaba.fastjson.JSON;
import com.r.dao.TeacherDao;
import com.r.dao.impl.TeacherDaoImpl;
import com.r.pojo.Teacher;

/**
 * Servlet implementation class TeacherServlet
 */
@WebServlet("/TeacherAllServlet")
public class TeacherAllServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TeacherAllServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置网页字符编码集
        response.setContentType("text/html;charset=utf-8");
        
		TeacherDao td = new TeacherDaoImpl();
		
		//查询所有学生信息
		List<Teacher> teacherlist = new ArrayList<>();
		teacherlist = td.getAll();
		//System.out.println("---------------------------------------------------------------"+ Arrays.toString(teacherlist.toArray()));
		String json = JSON.toJSONString(teacherlist);
		System.out.println(json);
		response.getWriter().append(json);
//		return teacherlist;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

TeacherDelServlet.java

package com.r.servlet;

import java.io.IOException;
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 com.r.dao.TeacherDao;
import com.r.dao.impl.TeacherDaoImpl;
import com.r.pojo.Teacher;

/**
 * Servlet implementation class TeacherDelServlet
 */
@WebServlet("/TeacherDelServlet")
public class TeacherDelServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TeacherDelServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置网页字符编码集
        response.setContentType("text/html;charset=utf-8");
        
        //设置接收参数
        String no = request.getParameter("no");

        
		TeacherDao td = new TeacherDaoImpl();
		int n = 0;
		n = td.delInfo(no);
		if(n>0){
			response.getWriter().append("删除成功");
		} else {
			response.getWriter().append("删除失败");
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

有关【微信小程序系列】小程序简单连接后端数据库完整示例(附免费下载的源码)(Servlet)的更多相关文章

  1. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  2. ruby - 无法在 60 秒内获得稳定的 Firefox 连接 (127.0.0.1 :7055) - 2

    我使用的是Firefox版本36.0.1和Selenium-Webdrivergem版本2.45.0。我能够创建Firefox实例,但无法使用脚本继续进行进一步的操作无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055)错误。有人能帮帮我吗? 最佳答案 我遇到了同样的问题。降级到firefoxv33后一切正常。您可以找到旧版本here 关于ruby-无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055),我们在StackOverflow上找到一个类

  3. ruby - 简单获取法拉第超时 - 2

    有没有办法在这个简单的get方法中添加超时选项?我正在使用法拉第3.3。Faraday.get(url)四处寻找,我只能先发起连接后应用超时选项,然后应用超时选项。或者有什么简单的方法?这就是我现在正在做的:conn=Faraday.newresponse=conn.getdo|req|req.urlurlreq.options.timeout=2#2secondsend 最佳答案 试试这个:conn=Faraday.newdo|conn|conn.options.timeout=20endresponse=conn.get(url

  4. ruby - 用 Ruby 编写一个简单的网络服务器 - 2

    我想在Ruby中创建一个用于开发目的的极其简单的Web服务器(不,不想使用现成的解决方案)。代码如下:#!/usr/bin/rubyrequire'socket'server=TCPServer.new('127.0.0.1',8080)whileconnection=server.acceptheaders=[]length=0whileline=connection.getsheaders想法是从命令行运行这个脚本,提供另一个脚本,它将在其标准输入上获取请求,并在其标准输出上返回完整的响应。到目前为止一切顺利,但事实证明这真的很脆弱,因为它在第二个请求上中断并出现错误:/usr/b

  5. ruby-on-rails - 简单的 Ruby on Rails 问题——如何将评论附加到用户和文章? - 2

    我意识到这可能是一个非常基本的问题,但我现在已经花了几天时间回过头来解决这个问题,但出于某种原因,Google就是没有帮助我。(我认为部分问题在于我是一个初学者,我不知道该问什么......)我也看过O'Reilly的RubyCookbook和RailsAPI,但我仍然停留在这个问题上.我找到了一些关于多态关系的信息,但它似乎不是我需要的(尽管如果我错了请告诉我)。我正在尝试调整MichaelHartl'stutorial创建一个包含用户、文章和评论的博客应用程序(不使用脚手架)。我希望评论既属于用户又属于文章。我的主要问题是:我不知道如何将当前文章的ID放入评论Controller。

  6. ruby - 使用 Ruby 通过 Outlook 发送消息的最简单方法是什么? - 2

    我的工作要求我为某些测试自动生成电子邮件。我一直在四处寻找,但未能找到可以快速实现的合理解决方案。它需要在outlook而不是其他邮件服务器中,因为我们有一些奇怪的身份验证规则,我们需要保存草稿而不是仅仅发送邮件的选项。显然win32ole可以做到这一点,但我找不到任何相当简单的例子。 最佳答案 假设存储了Outlook凭据并且您设置为自动登录到Outlook,WIN32OLE可以很好地完成此操作:require'win32ole'outlook=WIN32OLE.new('Outlook.Application')message=

  7. UE4 源码阅读:从引擎启动到Receive Begin Play - 2

    一、引擎主循环UE版本:4.27一、引擎主循环的位置:Launch.cpp:GuardedMain函数二、、GuardedMain函数执行逻辑:1、EnginePreInit:加载大多数模块int32ErrorLevel=EnginePreInit(CmdLine);PreInit模块加载顺序:模块加载过程:(1)注册模块中定义的UObject,同时为每个类构造一个类默认对象(CDO,记录类的默认状态,作为模板用于子类实例创建)(2)调用模块的StartUpModule方法2、FEngineLoop::Init()1、检查Engine的配置文件找出使用了哪一个GameEngine类(UGame

  8. postman——集合——执行集合——测试脚本——pm对象简单示例02 - 2

    //1.验证返回状态码是否是200pm.test("Statuscodeis200",function(){pm.response.to.have.status(200);});//2.验证返回body内是否含有某个值pm.test("Bodymatchesstring",function(){pm.expect(pm.response.text()).to.include("string_you_want_to_search");});//3.验证某个返回值是否是100pm.test("Yourtestname",function(){varjsonData=pm.response.json

  9. Qt Designer的简单使用 - 2

    在前面两节的例子中,主界面窗口的尺寸和标签控件显示的矩形区域等,都是用C++代码编写的。窗口和控件的尺寸都是预估的,控件如果多起来,那就不好估计每个控件合适的位置和大小了。用C++代码编写图形界面的问题就是不直观,因此Qt项目开发了专门的可视化图形界面编辑器——QtDesigner(Qt设计师)。通过QtDesigner就可以很方便地创建图形界面文件*.ui,然后将ui文件应用到源代码里面,做到“所见即所得”,大大方便了图形界面的设计。本节就演示一下QtDesigner的简单使用,学习拖拽控件和设置控件属性,并将ui文件应用到Qt程序代码里。使用QtDesigner设计界面在开始菜单中找到「Q

  10. 微信小程序通过字典表匹配对应数据 - 2

    前言一般来说,前端根据后台返回code码展示对应内容只需要在前台判断code值展示对应的内容即可,但要是匹配的code码比较多或者多个页面用到时,为了便于后期维护,后台就会使用字典表让前端匹配,下面我将在微信小程序中通过wxs的方法实现这个操作。为什么要使用wxs?{{method(a,b)}}可以看到,上述代码是一个调用方法传值的操作,在vue中很常见,多用于数据之间的转换,但由于微信小程序诸多限制的原因,你并不能优雅的这样操作,可能有人会说,为什么不用if判断实现呢?但是if判断的局限性在于如果存在数据量过大时,大量重复性操作和if判断会让你的代码显得异常冗余。wxswxs相当于是一个独立

随机推荐