[WeChat applet series] A complete example of a simple applet connecting to a backend database (with source code for free download) (Servlet)

[WeChat applet series] A complete example of a simple applet connecting to a backend database (with source code for free download) (Servlet)

log in page

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;

}

home page

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;
}

rear end

Too lazy to stick, complete example resource address: (55 messages) Wechat applet uses Servlet to connect to database source code.zip-Java Document Class Resources-CSDN Library

Dao layer code

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 code (partial)

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);
	}

}

Guess you like

Origin blog.csdn.net/weixin_55452293/article/details/127013580