簡單的jdbc封裝+servlet的封裝

  • 用於實體映射的類(Column.java,Tab.java)
  • Tab.java(表映射類)
package annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 方法註解映射,映射調用的方法
 * @author facebook
 *
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface MethodAnnotation {
    String method() default "";
}
  • Column.java(字段映射類)
package annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 實體類映射數據庫表類
 * @author facebook
 *
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE})
public @interface Tab {
    /**
     * 用於修飾實體類,表示實體類名與數據庫表名之間的映射
     * @return
     */
    String table() default "";

}
  • Employee.java(員工實體類)
package entity;

import java.io.Serializable;

import annotation.Column;
import annotation.Tab;

@Tab(table = "employee")
public class Employee implements Serializable{
    private static final long serialVersionUID = 1L;

    @Column(name="emp_id",type=Integer.class,isNull = false,isPrimary = true,isAutoIncrement=true,isUnique = false)
    private Integer emp_id;

    @Column(name="emp_code",type=String.class,len = 30,isNull = false,isUnique = false)
    private String emp_code;

    @Column(name="emp_name",type=String.class,len = 30,isNull = true)
    private String emp_name;

    public Employee(){
        super();
    }

    public Employee(String emp_code, String emp_name) {
        this();
        this.emp_code = emp_code;
        this.emp_name = emp_name;
    }

    public Integer getEmp_id() {
        return emp_id;
    }
    public void setEmp_id(Integer emp_id) {
        this.emp_id = emp_id;
    }
    public String getEmp_code() {
        return emp_code;
    }
    public void setEmp_code(String emp_code) {
        this.emp_code = emp_code;
    }
    public String getEmp_name() {
        return emp_name;
    }
    public void setEmp_name(String emp_name) {
        this.emp_name = emp_name;
    }

    /**
     * 重寫父類的toString方法,將對象屬性以field&value的形式組裝起來
     */
    @Override
    public String toString() {
        return "emp_id=" + emp_id + "&emp_code=" + emp_code + "&emp_name=" + emp_name;
    }

}
  • BaseException.java(自定義異常類)
package exception;

/**
 * 自定義異常
 * @author facebook
 *
 */
@SuppressWarnings("serial")
public class BaseException extends RuntimeException{

    public BaseException() {
        super();
        // TODO Auto-generated constructor stub
    }

    public BaseException(String message, Throwable cause,
            boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
        // TODO Auto-generated constructor stub
    }

    public BaseException(String message, Throwable cause) {
        super(message, cause);
        // TODO Auto-generated constructor stub
    }

    public BaseException(String message) {
        super(message);
        // TODO Auto-generated constructor stub
    }

    public BaseException(Throwable cause) {
        super(cause);
        // TODO Auto-generated constructor stub
    }

}
  • BaseDao.java(數據庫CURD)
package exception;

/**
 * 自定義異常
 * @author facebook
 *
 */
@SuppressWarnings("serial")
public class BaseException extends RuntimeException{

    public BaseException() {
        super();
        // TODO Auto-generated constructor stub
    }

    public BaseException(String message, Throwable cause,
            boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
        // TODO Auto-generated constructor stub
    }

    public BaseException(String message, Throwable cause) {
        super(message, cause);
        // TODO Auto-generated constructor stub
    }

    public BaseException(String message) {
        super(message);
        // TODO Auto-generated constructor stub
    }

    public BaseException(Throwable cause) {
        super(cause);
        // TODO Auto-generated constructor stub
    }

}
  • DatabaseConnection.java(數據庫連接與對象封裝類)
package utils;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

public class DatabaseConnection {
    private static String username = "root";
    private static String userpassword = "120607";
    private static String url = "jdbc:mysql://localhost:3307/employee?Unicode=true&characterEncoding=UTF-8";
    public static Connection  conn;

    static{
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    /**
     * 獲取數據庫連接
     */
    public static void connection(){
        try {
            conn = (Connection) DriverManager.getConnection(url,username,userpassword);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    /**
     * 創建PreparedStatement對象
     * @param sql
     * @return
     * @throws SQLException
     */
    public static PreparedStatement preparedStatement(String sql) throws SQLException{
        connection();
        return (PreparedStatement) conn.prepareStatement(sql);
    }
    /**
     * 創建ResultSet對象
     * @param sql
     * @return
     * @throws SQLException
     */
    public static ResultSet resultSet(String sql) throws SQLException{
        return preparedStatement(sql).executeQuery();
    }
    /**
     * 關閉數據庫連接
     * @param obj
     * @throws SQLException
     */
    public static void close(Object obj) throws SQLException{
        if(obj==null){
            return;
        }
        if(obj instanceof ResultSet){
            ((ResultSet) obj).close();
        }
        if(obj instanceof PreparedStatement){
            ((PreparedStatement) obj).close();
        }
        if(obj instanceof Connection){
            ((Connection) obj).close();
        }
    }
}
  • MethodAnnotation.java(servlet方法映射類)
package annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 方法註解映射,映射調用的方法
 * @author facebook
 *
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface MethodAnnotation {
    String method() default "";
}
  • BaseServlet.java(servlet基類封裝,提供自定義子類繼承,使用反射和註解映射不同子servlet的方法,前端實現觸發不同的功能使用同一個對象的不同方法)
package web;

import java.io.IOException;
import java.lang.reflect.Method;

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

import annotation.MethodAnnotation;

/**
 * 封裝servlet的頂層操作,根據註解映射,找到對應的方法,並執行操作
 * @author facebook
 *
 */
public class BaseServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        invoke(request,response);
    }

    /**
     * 執行指定的方法
     * @param request
     * @param response
     * @throws IOException
     */
    protected void invoke(HttpServletRequest request, HttpServletResponse response) throws IOException{
        Class<?> clz =  this.getClass();
        int count=0;
        boolean flag = true;
        String method = request.getParameter("method");
        Method[] methods = clz.getDeclaredMethods();
        for(Method m : methods){
            if(m.isAnnotationPresent(MethodAnnotation.class)){
                MethodAnnotation methodAnnotation = m.getAnnotation(MethodAnnotation.class);
                if(methodAnnotation.method().equals(method)){
                    try {
                        m.invoke(this, request,response);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    flag = true;
                    break;
                }else{
                    flag = false;
                }
            }else{
                count++;
            }
        }
        if(!flag){
            response.getWriter().write("<script>alert('沒有找到相應的操作,請查看method中的參數是否配置出錯!')</script>");
            return;
        }
        if(count==methods.length){
            response.getWriter().write("<script>alert('沒有添加任何方法映射!')</script>");
            return;
        }

    }
}
  • UserServlet.java(測試servlet類)
package web;

import java.io.IOException;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import annotation.MethodAnnotation;

@WebServlet("/UserServlet")
public class UserServlet extends BaseServlet {
    private static final long serialVersionUID = 1L;

    @MethodAnnotation(method="queryList")
    public void queryList(HttpServletRequest request, HttpServletResponse response){
        try {
            response.getWriter().write("<script>alert('你調用了查詢方法!......queryList')</script>");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @MethodAnnotation(method="saveObject")
    public void saveObject(HttpServletRequest request, HttpServletResponse response){
        try {
            response.getWriter().write("<script>alert('你調用了保存方法!......saveObject')</script>");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @MethodAnnotation(method="delObject")
    public void delObject(HttpServletRequest request, HttpServletResponse response){
        try {
            response.getWriter().write("<script>alert('你調用了刪除方法!......delObject')</script>");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @MethodAnnotation(method="findObject")
    public void findObject(HttpServletRequest request, HttpServletResponse response){
        try {
            response.getWriter().write("<script>alert('你調用了單個對象的查詢方法!.....findObject')</script>");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章