MySQL---数据库从入门走向大神系列(十二)-构建MVC项目(1)

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介: MySQL---数据库从入门走向大神系列(十二)-构建MVC项目

这个是对前面技术的一个小总结吧,用到的大概技术有:

MVC框架,加注解,Struts框架的思想,动态代理,线程管理对象ThreadLocal,Connection对象池,Properties文件读取,EL表达式,JSTL,JavaBean,Java访问MySQL数据库,增删改查…

其实做出来界面挺简单:

image.png

完整的项目链接:

https://github.com/chenhaoxiang/Java/tree/master/myMvcWeb2

这里只写出一些核心的类的代码:

Book.java:

package cn.hncu.domain;
/*
alter table book add constraint fk_book foreign key (studid) references stud(id);
设置studid为book的外键(fk_book)为stud的主键id
 */
public class Book {
    private Integer id;
    private String namem;
    private Double price;
    // ※一对多关系中的多方(外键字段): 在写JavaBean时,要包含对方(一方)的整个值对象类型的变量
    private Stud stud;//设置书的主人
    public Book() {
        super();
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getNamem() {
        return namem;
    }
    public void setNamem(String namem) {
        this.namem = namem;
    }
    public Double getPrice() {
        return price;
    }
    public void setPrice(Double price) {
        this.price = price;
    }
    public Stud getStud() {
        return stud;
    }
    public void setStud(Stud stud) {
        this.stud = stud;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Book other = (Book) obj;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        return true;
    }
}

Stud.java

package cn.hncu.domain;
import java.util.ArrayList;
import java.util.List;
public class Stud {
    private String id;
    private String name;
    //※一对多中的一方: 添加一个集合(用set也行)以表示该关系
    private List<Book > books = new ArrayList<Book>();
    public Stud() {
        super();
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public List<Book> getBooks() {
        return books;
    }
    public void setBooks(List<Book> books) {
        this.books = books;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Stud other = (Stud) obj;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        return true;
    }
    //注意,如果要添加toString()方法,注意一对多关系中的信息输出嵌套
}

TxProxy.java:

package cn.hncu.pubs.tx;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import cn.hncu.pubs.ConnsUtil;
public class TxProxy implements InvocationHandler{
    private Object srcObj;
    public TxProxy(Object srcObj) {
        this.srcObj = srcObj;
    }
    /* 版本1
    public static Object getProxy(Object srcObj){
        Object proxiedObj = Proxy.newProxyInstance(TxProxy.class.getClassLoader(),
                            srcObj.getClass().getInterfaces(),
                            new TxProxy(srcObj));
        return proxiedObj;
    }
    */
    /* 版本2
    public static<T> T getProxy(Object srcObj, Class<T> cls){
        Object proxiedObj = Proxy.newProxyInstance(TxProxy.class.getClassLoader(),
                            srcObj.getClass().getInterfaces(),
                            new TxProxy(srcObj));
        return (T)proxiedObj;
    }
    */
    /* 版本3
    public static<T> T getProxy(Class<T> cls){
        Object srcObj = null;
        try {
            srcObj = cls.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        Object proxiedObj = Proxy.newProxyInstance(TxProxy.class.getClassLoader(),
                            srcObj.getClass().getInterfaces(),
                            new TxProxy(srcObj));
        return (T)proxiedObj;
    }
    */
    //版本4
    public static<T> T getProxy(T srcObj){
        Object proxiedObj = Proxy.newProxyInstance(TxProxy.class.getClassLoader(),
                            srcObj.getClass().getInterfaces(),
                            new TxProxy(srcObj));
        return (T)proxiedObj;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        //判断method方法是不是添加了注解
        if(method.isAnnotationPresent(Transaction.class)){
            Connection con=null;
            Object returnValue =null;
            try {
                con = ConnsUtil.getConnection();
                con.setAutoCommit(false);
                System.out.println("在动态代理中开启一个事务....");
                returnValue = method.invoke(srcObj, args);
                con.commit();
                System.out.println("在动态代理中提交一个事务....");
            } catch (Exception e) {
                con.rollback();
                System.out.println("在动态代理中回滚一个事务....");
            }finally{
                if(con!=null){
                    try {
                        con.setAutoCommit(true);
                        con.close();
                    } catch (Exception e) {
                        throw new RuntimeException("数据库连接关闭失败", e);
                    }
                }
            }
            return returnValue;
        }else{//没有添加注解,直接放行
            return method.invoke(srcObj, args);
        }
    }
}

Transaction.java:注解

package cn.hncu.pubs.tx;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(value=ElementType.METHOD)
public @interface Transaction {
}

BaseServlet.java:

package cn.hncu.pubs;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * @author 陈浩翔
 *
 * 2016-8-15
 */
public abstract class BaseServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        String cmd = req.getParameter("cmd");
        if(cmd==null){
            cmd="execute";
        }
        try {
            System.out.println("this:"+this);
            //下面这句不能访问私有方法
            //Method m = this.getClass().getMethod(cmd, HttpServletRequest.class,HttpServletResponse.class );
            //如果要用类反射实现访问类的私有方法,则需要这2步,这样子类的方法就不用设置成public了。
            //1获得私有方法  
            Method m = this.getClass().getDeclaredMethod(cmd, HttpServletRequest.class,HttpServletResponse.class );
            //2设置私有方法可以被访问 
            m.setAccessible(true);
            m.invoke(this, req,resp);//这里的this是子类对象,谁调用这里的,这个this就是谁    
            //下面这几句是给大家启发Struts框架的思想
//          String str =(String) m.invoke(this, request,response);
//          String resPage = "";//从配置struts.xml文件中读取str所对应的结果页面的地址
//          request.getRequestDispatcher(resPage).forward(request,response);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    //如果没有参数cmd为null,转向的界面,由子类自己实现
    public abstract void execute(HttpServletRequest request, HttpServletResponse response);
}

ConnsUtil.java

package cn.hncu.pubs;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class ConnsUtil {
    private static List<Connection> pool = new ArrayList<Connection>();
    private static final int NUM = 3;
    private static ThreadLocal<Connection> t = new ThreadLocal<Connection>();
    static{
        try {
            //读取配置文件
            Properties p = new Properties();
            p.load(ConnsUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"));
            String driver = p.getProperty("driver");
            String url = p.getProperty("url");
            String user = p.getProperty("username");
            String password = p.getProperty("password");
            Class.forName(driver);
            for(int i=0;i<NUM;i++){
                final Connection conn = DriverManager.getConnection(url, user, password);
                //System.out.println(conn.getClass().getClassLoader());//AppClassLoader
                //使用动态代理,代理conn对象,实现对close方法的拦截
                Object obj = Proxy.newProxyInstance(ConnsUtil.class.getClassLoader(),
                            new Class[]{Connection.class},
                            new InvocationHandler() {
                            @Override
                            public Object invoke(Object proxy, Method method, Object[] args)
                            throws Throwable {
                                //拦截close方法
                                if(method.getName().equalsIgnoreCase("close") &&(args==null||args.length==0) ){
                                    pool.add((Connection)proxy);
                                    //proxy为代理后的对象
                                    t.set(null);//把存储在本地线程管理类中的当前线程对应的对象设为空
                                    return null;
                                }
                                //conn为被代理的对象
                                return method.invoke(conn, args);
                            }
                        });
                pool.add( (Connection)obj);//把代理后的conn对象即obj加入池中
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static synchronized Connection getConnection() throws InterruptedException{
        //从本地线程管理对象t中拿
        Connection con = t.get();
        if(con==null){
            if(pool.size()<=0){
                Thread.sleep(50);
                return getConnection();
            }
            con=pool.remove(0);
            //放入到t中
            t.set(con);
        }
        return con;
    }
}

StudServlet.java:

package cn.hncu.stud;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.hncu.domain.Book;
import cn.hncu.domain.Stud;
import cn.hncu.pubs.BaseServlet;
import cn.hncu.pubs.tx.TxProxy;
import cn.hncu.stud.service.IStudService;
import cn.hncu.stud.service.StudService;
public class StudServlet extends BaseServlet {
    //版本1
    //private IStudService service = (IStudService) TxProxy.getProxy(new StudService());
    //版本2
    //private IStudService service = TxProxy.getProxy(new StudService(),IStudService.class);
    //版本3
    //private IStudService service = TxProxy.getProxy(StudService.class);//用实现类的class
    //版本4
    private IStudService service = TxProxy.getProxy(new StudService());//用实现类的class
    private void save(HttpServletRequest request, HttpServletResponse response) throws InterruptedException, ServletException, IOException {
        //收集并封装stud
        String name = request.getParameter("name");
        if(name==null||name.trim().length()<=0){
            response.sendRedirect("index.jsp");//重定向
            return ;
        }
        Stud stud = new Stud();
        stud.setName(name);
        //收集并封装所有book
        String bookNames[] = request.getParameterValues("bookname");//获取多个值
        String prices[] = request.getParameterValues("price");
        if(bookNames!=null){
            for(int i=0;i<bookNames.length;i++){
                Book book = new Book();
                if(bookNames[i]==null || bookNames[i].trim().length()<=0){
                    continue;
                }
                book.setNamem(bookNames[i]);
                if(prices[i]!=null && prices[i].trim().length()!=0 ){
                    Double price=0.0;
                    try {
                        price = Double.parseDouble(prices[i]);
                    } catch (NumberFormatException e) {
                        price=0.0;
                    }
                    book.setPrice(price);
                }
                book.setStud(stud);
                //继续封装stud----为stud中的books属性赋值--一方中的集合
                stud.getBooks().add(book);
            }
        }
        try {
            service.save(stud);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    private void query(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Map<String, String>> studs = service.query();
        request.setAttribute("studs", studs);
        request.getRequestDispatcher("/jsps/show.jsp").forward(request, response);
    }
    @Override
    public void execute(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("调用默认业务处理方法....");
    }
}
相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
3天前
|
关系型数据库 MySQL 分布式数据库
《MySQL 简易速速上手小册》第6章:MySQL 复制和分布式数据库(2024 最新版)
《MySQL 简易速速上手小册》第6章:MySQL 复制和分布式数据库(2024 最新版)
25 2
|
1天前
|
SQL 存储 关系型数据库
数据库开发之mysql前言以及详细解析
数据库开发之mysql前言以及详细解析
6 0
|
5天前
|
SQL 关系型数据库 MySQL
MySQL环境搭建——“MySQL数据库”
MySQL环境搭建——“MySQL数据库”
|
5天前
|
SQL NoSQL 关系型数据库
初识MySQL数据库——“MySQL数据库”
初识MySQL数据库——“MySQL数据库”
|
8天前
|
关系型数据库 MySQL 数据库
数据库基础(mysql)
数据库基础(mysql)
|
8天前
|
SQL 关系型数据库 数据库
【后端面经】【数据库与MySQL】SQL优化:如何发现SQL中的问题?
【4月更文挑战第12天】数据库优化涉及硬件升级、操作系统调整、服务器/引擎优化和SQL优化。SQL优化目标是减少磁盘IO和内存/CPU消耗。`EXPLAIN`命令用于检查SQL执行计划,关注`type`、`possible_keys`、`key`、`rows`和`filtered`字段。设计索引时考虑外键、频繁出现在`where`、`order by`和关联查询中的列,以及区分度高的列。大数据表改结构需谨慎,可能需要停机、低峰期变更或新建表。面试中应准备SQL优化案例,如覆盖索引、优化`order by`、`count`和索引提示。优化分页查询时避免大偏移量,可利用上一批的最大ID进行限制。
32 3
|
9天前
|
存储 关系型数据库 MySQL
【后端面经】【数据库与MySQL】为什么MySQL用B+树而不用B树?-02
【4月更文挑战第11天】数据库索引使用规则:`AND`用`OR`不用,正用反不用,范围中断。索引带来空间和内存代价,包括额外磁盘空间、内存占用和数据修改时的维护成本。面试中可能涉及B+树、聚簇索引、覆盖索引等知识点。MySQL采用B+树,因其利于范围查询和内存效率。数据库不使用索引可能因`!=`、`LIKE`、字段区分度低、特殊表达式或全表扫描更快。索引与NULL值处理在不同数据库中有差异,MySQL允许NULL在索引中的使用。
12 3
|
10天前
|
关系型数据库 MySQL 数据库连接
Django(四):Django项目部署数据库及服务器配置详解(MySQL)
Django(四):Django项目部署数据库及服务器配置详解(MySQL)
33 11
|
19天前
|
SQL 数据可视化 关系型数据库
轻松入门MySQL:深入探究MySQL的ER模型,数据库设计的利器与挑战(22)
轻松入门MySQL:深入探究MySQL的ER模型,数据库设计的利器与挑战(22)
103 0
|
19天前
|
存储 关系型数据库 MySQL
轻松入门MySQL:数据库设计之范式规范,优化企业管理系统效率(21)
轻松入门MySQL:数据库设计之范式规范,优化企业管理系统效率(21)