Servlet+mybatis+jsp注解方式实现增删改查

1.需要导入相关包如下。

在这里插入图片描述
2.mybatis.xml里面的内容:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--    定义环境-->
    <environments default="mysql">
        <environment id="mysql">
<!--          定义事务-->
            <transactionManager type="JDBC"></transactionManager>
<!--定义数据源            -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatisdb?characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="wu"/>
            </dataSource>
        </environment>
    </environments>
<!--    映射接口中的sql语句-->
    <mappers>
        <mapper class="com.inter.AddressDao"></mapper>
    </mappers>
</configuration>

3.DButil里面:

package util;

import java.io.Reader;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;



public class DButil {
	 public static SqlSessionFactory factory;
	    static {
	        //通过字符流的读取将主配置文件读取到程序中;
	        try {
	            Reader reader= Resources.getResourceAsReader("mybatis.xml");
	            
	            //创建会话工厂建造者对象
	            SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
	            //得到会话工厂对象
	            factory=builder.build(reader);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }
	    //得到链接对象
	    public static SqlSession getSession(boolean auto){
	        return  factory.openSession(auto);
	    }
		
}

4.把对象进行封装(com.bean里面):

package com.bean;

public class Address {
	private int id;
	private String Contactor;
	private String Address;
	private String Phone;
	private String email;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getContactor() {
		return Contactor;
	}
	public void setContactor(String contactor) {
		Contactor = contactor;
	}
	public String getAddress() {
		return Address;
	}
	public void setAddress(String address) {
		Address = address;
	}
	public String getPhone() {
		return Phone;
	}
	public void setPhone(String phone) {
		Phone = phone;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	@Override
	public String toString() {
		return "Address [id=" + id + ", Contactor=" + Contactor + ", Address=" + Address + ", Phone=" + Phone
				+ ", email=" + email + "]";
	}
	public Address() {
		// TODO Auto-generated constructor stub
	}
	
	public Address(int id,String contactor,String address,String phone,String email) {
		super();
		this.id=id;
		this.Contactor=contactor;
		this.Address=address;
		this.Phone=phone;
		this.email=email;
	}

}

5.com.inter里面 接口:

package com.inter;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.bean.Address;

public interface AddressDao {
	 @Insert("insert into address(Contactor,Address,Phone,email) values(#{Contactor},#{Address},#{Phone},#{email})")//自动映射
	 int insert(Address address);
	 
	 @Select("select * from address")
	 List<Address> select();
	 
	 @Update("update address set Contactor=#{Contactor},Address=#{Address},Phone=#{Phone},email=#{email} where id=#{id}")
	 int update(Address address);
	 
	 @Delete("delete from address where id=#{id}")
	 int delete(Address address);
}

6.servlet中增删改查在这里插入图片描述

代码如下:
InsertServlet:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 request.setCharacterEncoding("utf-8"); 		 
		 String contactor = request.getParameter("contactor");
		 String address = request.getParameter("address");
		 String phone = request.getParameter("phone");
		 String email = request.getParameter("email");
		 Address a=new Address(0, contactor, address, phone, email);
		 SqlSession session= DButil.getSession(true);
		 AddressDao dao=session.getMapper(AddressDao.class);
		 dao.insert(a);
		 session.close();
		 response.sendRedirect("SelectServlet");
	}

DeleteServlet:

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 SqlSession session= DButil.getSession(true);
		 AddressDao dao=session.getMapper(AddressDao.class);
		 int id=Integer.parseInt(request.getParameter("id"));
		 Address a=new Address();
		 a.setId(id);
		 dao.delete(a);
		 request.setAttribute("a", a);
		 request.getRequestDispatcher("SelectServlet").forward(request, response);
	}

UpdateServlet:

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 PrintWriter out = response.getWriter();
		 out.println("aaaa");
		 int id=Integer.parseInt(request.getParameter("id"));		
		 String contactor = request.getParameter("contactor");
		 String address = request.getParameter("address");
		 String phone = request.getParameter("phone");
		 String email = request.getParameter("email");
		 Address a=new Address(id, contactor, address, phone, email);		 
		 SqlSession session= DButil.getSession(true);
		 AddressDao dao=session.getMapper(AddressDao.class);
		 dao.update(a);
		 //List<Address> list=dao.select();
		 //request.setAttribute("list", list);		
		 request.getRequestDispatcher("show.jsp").forward(request, response);
		 
	}

SelectServlet:

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		SqlSession session=DButil.getSession(true);
		AddressDao dao=(AddressDao)session.getMapper(AddressDao.class);
		List<Address> list=dao.select();
		session.close();
		request.setAttribute("list", list);
		request.getRequestDispatcher("index.jsp").forward(request, response);
	}

6.相关jsp文件:
index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="SelectServlet" method="post">
<table align="center" border="1" width="70%" >
	<caption><a href="xxlr.jsp">添加联系人</a></caption>
	 <tr>
      <td>序号</td>
      <td>联系人</td>
      <td>联系人地址</td>
      <td>联系电话</td>
       <td>E-Mail</td>
       <td>删除</td>
    </tr>
    <c:forEach items="${list}" var="a" varStatus="s">
      <tr>
      <td>${s.count}</td>
      <td>${a.contactor}</td>
      <td>${a.address}</td>
      <td>${a.phone}</td>
       <td>${a.email}</td>
       <td><a href="DeleteServlet?id=${a.id}">删除</a></td>
    </tr>
    </c:forEach>
</table>
</form>
</body>
</html>

update.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>update</title>
</head>
<body>
<form action="UpdateServlet"  method="get"> 
<table align="center" border="1" width="70%" >
	<caption>更新联系人</caption>
	 <tr>
      <td>序号</td>
      <td>联系人</td>
      <td>联系人地址</td>
      <td>联系电话</td>
       <td>E-Mail</td>
      </tr>
      <tr>
      <td><input type="text" name="id" value="${a.id }"></td>
      <td><input type="text" name="contactor" value="${a.contactor }"></td>
      <td><input type="text" name="address" value="${a.address }"></td>
      <td><input type="text" name="phone" value="${a.phone }"></td>
       <td><input type="text" name="email" value="${a.email }"></td>
      </tr>
	  <tr><td colspan="5"><input type="submit" value="修改"></td></tr>
</table>
</form>
</body>
</html>

userwrite.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>添加用户</title>
<script type="text/javascript">
   function check(){
	   var contactor=document.getElementById("contactor").value;
	   var address=document.getElementById("address").value;
	   var phone=document.getElementById("phone").value;
	   var email=document.getElementById("email").value;
	   if(contactor==""){
		   document.getElementById("spancontactor").innerHTML="联系人不能为空";
	   }else if(address==""){
		   document.getElementById("spanaddress").innerHTML="地址不能为空";
	   }else if(phone==""){
		   document.getElementById("spanphone").innerHTML="电话不能为空";
	   }else if(email==""){
		   document.getElementById("spanemail").innerHTML="邮箱不能为空";
	   }else if(email.indexOf("@")==-1){
		   document.getElementById("spanemail").innerHTML="邮箱必须有@";
	   }else{
		   document.form1.submit();
	   }
   }
</script>
</head>
<body>
<form action="InsertServlet" method="post" name="form1">
   <table align="center">
            <tr>
         <td>联系人:</td>
         <td><input name="contactor" id="contactor"></td>
         <td><span id="spancontactor" style="color:red"></span></td>
      </tr>
            <tr>
         <td>联系人地址:</td>
         <td><input name="address" id="address"></td>
         <td><span id="spanaddress" style="color:red"></span></td>
      </tr>
         <tr>
         <td>电话:</td>
         <td><input name="phone" id="phone"></td>
         <td><span id="spanphone" style="color:red"></span></td>
      </tr>
            <tr>
         <td>E-Mail:</td>
         <td><input name="email" id="email"></td>
         <td><span id="spanemail" style="color:red"></span></td>
      </tr>
    <tr>
         <td colspan="3"><input type="button" value="添加联系人" onclick="check()"></td>
      </tr>
   </table>
</form>
</body>
</html>

然后就是自己准备数据库。这就不过多展示了大家都会,以上就能实现简单的增删改查功能.

  • 2
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值