69期-Java SE-055_综合练习

webdemo.sql

-- MySQL dump 10.13  Distrib 8.0.11, for macos10.13 (x86_64)
--
-- Host: 127.0.0.1    Database: webdemo
-- ------------------------------------------------------
-- Server version    8.0.11

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
 SET NAMES utf8mb4 ;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `classes`
--

DROP TABLE IF EXISTS `classes`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
 SET character_set_client = utf8mb4 ;
CREATE TABLE `classes` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `classes`
--

LOCK TABLES `classes` WRITE;
/*!40000 ALTER TABLE `classes` DISABLE KEYS */;
INSERT INTO `classes` VALUES (1,'一班'),(2,'二班'),(3,'三班');
/*!40000 ALTER TABLE `classes` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `student`
--

DROP TABLE IF EXISTS `student`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
 SET character_set_client = utf8mb4 ;
CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(11) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `cid` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `cid` (`cid`),
  CONSTRAINT `student_ibfk_1` FOREIGN KEY (`cid`) REFERENCES `classes` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `student`
--

LOCK TABLES `student` WRITE;
/*!40000 ALTER TABLE `student` DISABLE KEYS */;
INSERT INTO `student` VALUES (1,'张三',20,1),(2,'李四',21,1),(3,'王五',22,2),(4,'小明',18,2),(5,'小红',17,3);
/*!40000 ALTER TABLE `student` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2019-07-30 22:03:45

55.md

###Java Web 开发核心组件

Servlet:负责业务逻辑处理,接收客户端请求,作出响应。

JSP:负责用户交互界面,将业务数据展示给用户,并且提供用户操作界面。

EL:简化 JSP 复杂的编码。

JSTL:提供了一组标准标签库,进行开发,使得 JSP 代码更加简洁,JSTL + EL。

Ajax:异步加载,局部刷新。

Filter:对请求和响应进行过滤。

客户端 —> Controller —> Service —> Repository —> DB

69期-Java SE-055_综合练习_第1张图片

 

 index.jsp

<%--
  Created by IntelliJ IDEA.
  User: southwind
  Date: 2019-07-30
  Time: 20:03
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

  
    $Title$
  
  
    var="student">
        
学生编号 学生姓名 学生年龄 所在班级 操作
${student.id} ${student.name} ${student.age} ${student.classes.name} 删除 修改

 

update.jsp

<%--
  Created by IntelliJ IDEA.
  User: southwind
  Date: 2019-07-30
  Time: 21:50
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Titletitle>
head>
<body>
    <form action="/student.do?method=update" method="post">
        学生编号:<input type="text" readonly value="${student.id}" name="id"/><br/>
        学生姓名:<input type="text" value="${student.name}" name="name"/><br/>
        学生年龄:<input type="text" value="${student.age}" name="age"/><br/>
        所在班级:<select>
        <c:forEach items="${list}" var="classes">
            <option
                    ="${student.cid == classes.id}">
                    selected
                    c:if>
                    value="${classes.id}">${classes.name}option>
        c:forEach>
    select>
    form>
body>
html>

69期-Java SE-055_综合练习_第2张图片

 

 web.xml

xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
web-app>

69期-Java SE-055_综合练习_第3张图片

 

 69期-Java SE-055_综合练习_第4张图片

 

 c3p0-config.xml

xml version="1.0" encoding="UTF-8"?>
<c3p0-config>

    <named-config name="testc3p0">
        
        
        <property name="user">rootproperty>
        <property name="password">rootproperty>
        <property name="driverClass">com.mysql.jdbc.Driverproperty>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/webdemo?useUnicode=true&characterEncoding=UTF-8property>
        
        
        <property name="acquireIncrement">5property>
        
        <property name="initialPoolSize">5property>
        
        <property name="minPoolSize">5property>
        
        <property name="maxPoolSize">10property>
    
    named-config>
        
c3p0-config>

69期-Java SE-055_综合练习_第5张图片

 

 69期-Java SE-055_综合练习_第6张图片

 

 StudentServlet.java

package com.southwind.controller;

import com.southwind.entity.Classes;
import com.southwind.entity.Student;
import com.southwind.service.StudentService;
import com.southwind.service.impl.StudentServiceImpl;

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 java.io.IOException;
import java.util.List;

@WebServlet("/student.do")
public class StudentServlet extends HttpServlet {

    private StudentService studentService = new StudentServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method==null){
            method="findAll";
        }
        switch (method){
            case "findAll":
                List list = studentService.findAll();
                req.setAttribute("list",list);
                req.getRequestDispatcher("index.jsp").forward(req,resp);
                break;
            case "deleteById":
                String idStr = req.getParameter("id");
                Integer id = Integer.parseInt(idStr);
                studentService.deleteById(id);
                resp.sendRedirect("/student.do?method=findAll");
                break;
            case "findById":
                idStr = req.getParameter("id");
                id = Integer.parseInt(idStr);
                Student student = studentService.findById(id);
                List classList = studentService.findAllClasses();
                req.setAttribute("student",student);
                req.setAttribute("list",classList);
                req.getRequestDispatcher("update.jsp").forward(req,resp);
                break;
        }

    }
}

69期-Java SE-055_综合练习_第7张图片

 

 Classes.java

package com.southwind.entity;

import java.util.List;

public class Classes {
    private Integer id;
    private String name;
    private List students;

    public Classes(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    public List getStudents() {
        return students;
    }

    public void setStudents(List students) {
        this.students = students;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

 

Student.java

package com.southwind.entity;

public class Student {
    private Integer id;
    private String name;
    private Integer age;
    private Integer cid;
    private Classes classes;

    public Integer getCid() {
        return cid;
    }

    public void setCid(Integer cid) {
        this.cid = cid;
    }

    public Student(Integer id, String name, Integer age, Integer cid) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.cid = cid;
    }

    public Classes getClasses() {
        return classes;
    }

    public void setClasses(Classes classes) {
        this.classes = classes;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

69期-Java SE-055_综合练习_第8张图片

 

 ClassesRepository.java

package com.southwind.repository;

import com.southwind.entity.Classes;

import java.util.List;

public interface ClassesRepository {
    public Classes findById(Integer id);
    public List findAll();
}

 

StudentRepository.java

package com.southwind.repository;

import com.southwind.entity.Student;

import java.util.List;

public interface StudentRepository {
    public List findAll();
    public void deleteById(Integer id);
    public Student findById(Integer id);
}

69期-Java SE-055_综合练习_第9张图片

 

 ClassesRepositoryImpl.java

package com.southwind.repository.impl;

import com.southwind.entity.Classes;
import com.southwind.repository.ClassesRepository;
import com.southwind.util.JDBCTools;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ClassesRepositoryImpl implements ClassesRepository {
    @Override
    public Classes findById(Integer id) {
        Connection connection = JDBCTools.getConnection();
        String sql = "select * from classes where id = ?";
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        Classes classes = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1,id);
            resultSet = preparedStatement.executeQuery();
            if(resultSet.next()){
                String name = resultSet.getString(2);
                classes = new Classes(id,name);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCTools.release(connection,preparedStatement,resultSet);
        }
        return classes;
    }

    @Override
    public List findAll() {
        Connection connection = JDBCTools.getConnection();
        String sql = "select * from classes";
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        List list = new ArrayList<>();
        try {
            preparedStatement = connection.prepareStatement(sql);
            resultSet = preparedStatement.executeQuery();
            while(resultSet.next()){
                int id = resultSet.getInt(1);
                String name = resultSet.getString(2);
                Classes classes = new Classes(id,name);
                list.add(classes);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCTools.release(connection,preparedStatement,resultSet);
        }
        return list;
    }
}

 

StudentRepositoryImpl.java

package com.southwind.repository.impl;

import com.southwind.entity.Student;
import com.southwind.repository.StudentRepository;
import com.southwind.util.JDBCTools;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class StudentRepositoryImpl implements StudentRepository {
    @Override
    public List findAll() {
        Connection connection = JDBCTools.getConnection();
        String sql = "select * from student";
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        List list = new ArrayList<>();
        try {
            preparedStatement = connection.prepareStatement(sql);
            resultSet = preparedStatement.executeQuery();
            while(resultSet.next()){
                int id = resultSet.getInt(1);
                String name = resultSet.getString(2);
                int age = resultSet.getInt(3);
                int cid = resultSet.getInt(4);
                list.add(new Student(id,name,age,cid));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCTools.release(connection,preparedStatement,resultSet);
        }
        return list;
    }

    @Override
    public void deleteById(Integer id) {
        Connection connection = JDBCTools.getConnection();
        String sql = "delete from student where id = ?";
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1,id);
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCTools.release(connection,preparedStatement,null);
        }
    }

    @Override
    public Student findById(Integer id) {
        Connection connection = JDBCTools.getConnection();
        String sql = "select * from student where id = ?";
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        Student student = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1,id);
            resultSet = preparedStatement.executeQuery();
            if(resultSet.next()){
                String name = resultSet.getString(2);
                int age = resultSet.getInt(3);
                int cid = resultSet.getInt(4);
                student = new Student(id,name,age,cid);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCTools.release(connection,preparedStatement,resultSet);
        }
        return student;
    }
}

69期-Java SE-055_综合练习_第10张图片

 

 StudentService.java

package com.southwind.service;

import com.southwind.entity.Classes;
import com.southwind.entity.Student;

import java.util.List;

public interface StudentService {
    public List findAll();
    public void deleteById(Integer id);
    public Student findById(Integer id);
    public List findAllClasses();
}

69期-Java SE-055_综合练习_第11张图片

 

 StudentServiceImp.java

package com.southwind.service.impl;

import com.southwind.entity.Classes;
import com.southwind.entity.Student;
import com.southwind.repository.ClassesRepository;
import com.southwind.repository.StudentRepository;
import com.southwind.repository.impl.ClassesRepositoryImpl;
import com.southwind.repository.impl.StudentRepositoryImpl;
import com.southwind.service.StudentService;

import java.util.List;

public class StudentServiceImpl implements StudentService {

    private StudentRepository studentRepository = new StudentRepositoryImpl();
    private ClassesRepository classesRepository = new ClassesRepositoryImpl();

    @Override
    public List findAll() {
        List list = studentRepository.findAll();
        for(Student student:list){
            Classes classes = classesRepository.findById(student.getCid());
            student.setClasses(classes);
        }
        return list;
    }

    @Override
    public void deleteById(Integer id) {
        studentRepository.deleteById(id);
    }

    @Override
    public Student findById(Integer id) {
        return studentRepository.findById(id);
    }

    @Override
    public List findAllClasses() {
        return classesRepository.findAll();
    }
}

69期-Java SE-055_综合练习_第12张图片

 

 JDBCTools.java

package com.southwind.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCTools {
    private static DataSource dataSource;
    static {
        dataSource = new ComboPooledDataSource("testc3p0");
    }

    public static Connection getConnection(){
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static void release(Connection connection, Statement statement, ResultSet resultSet){
        try {
            if(connection!=null){
                connection.close();
            }
            if(statement!=null){
                statement.close();
            }
            if(resultSet!=null){
                resultSet.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

 

转载于:https://www.cnblogs.com/HiJackykun/p/11553671.html

你可能感兴趣的:(69期-Java SE-055_综合练习)