项目改造–Spring mvc
文件目录
重要代码
线程池
package org.example.spring.mvc.jdbc;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Configuration
public class DatabasePool {
private static HikariDataSource hikariDataSource;
public static HikariDataSource getHikariDataSource(){
if(null != hikariDataSource){
return hikariDataSource;
}
synchronized (DatabasePool.class) {
if (null == hikariDataSource) {
String jdbcurl = "jdbc:mysql://127.0.0.1:3306/school?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
String driverName = "com.mysql.cj.jdbc.Driver";
HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setUsername("root");
hikariConfig.setPassword("990619");
hikariConfig.setDriverClassName(driverName);
hikariConfig.setJdbcUrl(jdbcurl);
hikariDataSource = new HikariDataSource(hikariConfig);
return hikariDataSource;
}
}
return null;
}
数据库管理
package org.example.spring.mvc.jdbc;
import org.example.spring.mvc.bean.Homework;
import org.example.spring.mvc.bean.Student;
import org.example.spring.mvc.bean.StudentHomework;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class StudentHomeworkJdbc {
private static ApplicationContext contextSh;
static {
contextSh = new AnnotationConfigApplicationContext(StudentHomework.class);
}
private static ApplicationContext contextS;
static {
contextS = new AnnotationConfigApplicationContext(Student.class);
}
private static ApplicationContext contextH;
static {
contextH = new AnnotationConfigApplicationContext(Homework.class);
}
public static List<StudentHomework> selectAll(){
String sqlString = "select * from s_student_homework";
List<StudentHomework> list = new ArrayList<>();
try(Connection connection = DatabasePool.getHikariDataSource().getConnection()){
try(Statement statement = connection.createStatement()){
try(ResultSet resultSet = statement.executeQuery(sqlString)){
while(resultSet.next()){
StudentHomework sh = (StudentHomework) contextSh.getBean("studentHomework");
sh.setId(resultSet.getLong("id"));
sh.setStudentId(resultSet.getLong("student_id"));
sh.setHomeworkId(resultSet.getLong("homework_id"));
sh.setHomeworkTitle(resultSet.getString("homework_title"));
sh.setHomeworkContent(resultSet.getString("homework_content"));
sh.setCreateTime(resultSet.getTimestamp("create_time"));
list.add(sh);
}
}
}
} catch (SQLException ex) {
ex.printStackTrace();
}
return list;
}
public static List<Student> selectAllStudent(){
String sqlString = "select * from s_student";
List<Student> list = new ArrayList<>();
try(Connection connection = DatabasePool.getHikariDataSource().getConnection()){
try(Statement statement = connection.createStatement()){
try(ResultSet resultSet = statement.executeQuery(sqlString)){
while(resultSet.next()){
Student stu = (Student) contextS.getBean("student");
stu.setId(resultSet.getLong("id"));
stu.setName(resultSet.getString("name"));
stu.setCreate_time(resultSet.getTimestamp("create_time"));
list.add(stu);
}
}
}
} catch (SQLException ex) {
ex.printStackTrace();
}
return list;
}
public static List<Homework> selectAllHomework(){
String sqlString = "select * from s_homework";
List<Homework> list = new ArrayList<>();
try(Connection connection = DatabasePool.getHikariDataSource().getConnection()){
try(Statement statement = connection.createStatement()){
try(ResultSet resultSet = statement.executeQuery(sqlString)){
while(resultSet.next()){
Homework hw = (Homework) contextH.getBean("homework");
hw.setId(resultSet.getLong("id"));
hw.setTitle(resultSet.getString("title"));
hw.setContent(resultSet.getString("content"));
hw.setCreate_time(resultSet.getTimestamp("create_time"));
list.add(hw);
}
}
}
} catch (SQLException ex) {
ex.printStackTrace();
}
return list;
}
public boolean addHomework(Homework hw) {
String sql = "INSERT INTO `school`.`s_homework`(`id`,`title`,`content`,`create_time`,`update_time`) VALUES (?,?,?,?,?)";
try(Connection connection = DatabasePool.getHikariDataSource().getConnection()){
PreparedStatement ps = connection.prepareStatement(sql);
ps.setLong(1,hw.getId());
ps.setString(2,hw.getTitle());
ps.setString(3,hw.getContent());
ps.setTimestamp(4, (Timestamp) hw.getCreate_time());
ps.setTimestamp(5, (Timestamp) hw.getUpdate_time());
int count = ps.executeUpdate();
ps.close();
return count > 0 ? true : false;
}catch(SQLException e){
e.printStackTrace();
}
return false;
}
public boolean addStudent(Student stu) {
String sql = "INSERT INTO `school`.`s_student`(`id`,`name`,`create_time`,`update_time`) VALUES (?,?,?,?)";
try(Connection connection = DatabasePool.getHikariDataSource().getConnection()){
PreparedStatement ps = connection.prepareStatement(sql);
ps.setLong(1,stu.getId());
ps.setString(2,stu.getName());
ps.setTimestamp(3, (Timestamp) stu.getCreate_time());
ps.setTimestamp(4, (Timestamp) stu.getUpdate_time());
int count = ps.executeUpdate();
ps.close();
return count > 0 ? true : false;
}catch(SQLException e){
e.printStackTrace();
}
return false;
}
public boolean submitHomework(StudentHomework studentHomework) {
String sql = "INSERT INTO `school`.`s_student_homework`(`id`,`student_id`,`homework_id`,`homework_title`,`homework_content`,`create_time`,`update_time`) VALUES (?,?,?,?,?,?,?)";
try(Connection connection = DatabasePool.getHikariDataSource().getConnection()){
PreparedStatement ps = connection.prepareStatement(sql);
ps.setLong(1,studentHomework.getId());
ps.setLong(2,studentHomework.getStudentId());
ps.setLong(3,studentHomework.getHomeworkId());
ps.setString(4,studentHomework.getHomeworkTitle());
ps.setString(5,studentHomework.getHomeworkContent());
ps.setTimestamp(6, (Timestamp) studentHomework.getCreateTime());
ps.setTimestamp(7, (Timestamp) studentHomework.getUpdateTime());
int count = ps.executeUpdate();
ps.close();
return count > 0 ? true : false;
}catch(SQLException e){
e.printStackTrace();
}
return false;
}
public boolean isExistStudent(Long id){
String sql = "SELECT * from `school`.`s_student` where id = ? ";
boolean flag = false;
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DatabasePool.getHikariDataSource().getConnection();
preparedStatement=connection.prepareStatement(sql);
preparedStatement.setLong(1,id);
resultSet = preparedStatement.executeQuery();
//获取执行结果
if(resultSet.next()){
flag = true;
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
if(null != resultSet) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(null != preparedStatement) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(null != connection) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return flag;
}
public boolean isExistHomework(Long id){
String sql = "SELECT * from `school`.`s_homework` where id = ? ";
boolean flag = false;
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DatabasePool.getHikariDataSource().getConnection();
preparedStatement=connection.prepareStatement(sql);
preparedStatement.setLong(1,id);
resultSet = preparedStatement.executeQuery();
//获取执行结果
if(resultSet.next()){
flag = true;
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
if(null != resultSet) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(null != preparedStatement) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(null != connection) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return flag;
}
TeacherController
package org.example.spring.mvc.controller;
import org.example.spring.mvc.jdbc.StudentHomeworkJdbc;
import org.example.spring.mvc.bean.Homework;
import org.example.spring.mvc.bean.Student;
import org.example.spring.mvc.bean.StudentHomework;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@Controller
/*@RequestMapping("/Teacher/")*/
public class TeacherController extends HttpServlet {
@RequestMapping("/add")
public void AddStudentHomeworkServlet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Long id = Long.parseLong(req.getParameter("id"));
String title = req.getParameter("title");
String content = req.getParameter("content");
Homework hw = new Homework();
hw.setId(id);
hw.setTitle(new String(title.getBytes("ISO-8859-1"), "UTF-8"));
hw.setContent(new String(content.getBytes("ISO-8859-1"), "UTF-8"));
StudentHomeworkJdbc add = new StudentHomeworkJdbc();
add.addHomework(hw);
}
@RequestMapping("/addStu")
public void AddStudentServlet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Long id = Long.parseLong(req.getParameter("id"));
String name = req.getParameter("name");
Student stu = new Student();
stu.setId(id);
stu.setName(new String(name.getBytes("ISO-8859-1"), "UTF-8"));
StudentHomeworkJdbc addStu = new StudentHomeworkJdbc();
addStu.addStudent(stu);
}
@RequestMapping("/list")
public void StudentHomeworkServlet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<StudentHomework> list = StudentHomeworkJdbc.selectAll();
req.setAttribute("list",list);
req.getRequestDispatcher("index.jsp").forward(req,resp);
}
}
StudentController
package org.example.spring.mvc.controller;
import org.example.spring.mvc.jdbc.StudentHomeworkJdbc;
import org.example.spring.mvc.bean.StudentHomework;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServlet;
import java.io.UnsupportedEncodingException;
@Controller
/*@RequestMapping("/Student/")*/
public class StudentController extends HttpServlet {
/**
* @RequestMapping(value = "submitHomework",method = RequestMethod.GET)等价于
* @GetMapping("submitHomework")
*/
@ResponseBody
public Object testMapping(@RequestBody Object request, @RequestParam(required = true) String id){
//HttpServletRequest 获取Body ------> request
//Object ------> HttpServletResponse
return new Object();
}
@RequestMapping("/submitHomework") /**会映射到 StudentController.SubmitHomeworkServlet()*/
public void SubmitHomeworkServlet(@RequestParam(value = "id")Long id,
@RequestParam(value = "studentId")Long studentId,
@RequestParam(value = "homeworkId")Long homeworkId,
@RequestParam(value = "homeworkTitle")String homeworkTitle,
@RequestParam(value = "homeworkContent")String homeworkContent) throws UnsupportedEncodingException {
/* Long id = Long.parseLong(req.getParameter("id"));
Long studentId = Long.parseLong(req.getParameter("studentId"));
Long homeworkId = Long.parseLong(req.getParameter("homeworkId"));
String homeworkTitle = req.getParameter("homeworkTitle");
String homeworkContent = req.getParameter("homeworkContent");
*/
StudentHomeworkJdbc submitHw = new StudentHomeworkJdbc();
if (submitHw.isExistStudent(studentId)) {
if (submitHw.isExistHomework(homeworkId)) {
StudentHomework sh = new StudentHomework();
sh.setId(id);
sh.setStudentId(studentId);
sh.setHomeworkId(homeworkId);
sh.setHomeworkTitle(new String(homeworkTitle.getBytes("ISO-8859-1"), "UTF-8"));
sh.setHomeworkContent(new String(homeworkContent.getBytes("ISO-8859-1"), "UTF-8"));
submitHw.submitHomework(sh);
}
}
}
}
app-context.xml
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- <bean id="testBean" class="org.example.spring.mvc.bean.TestBean"></bean>-->
<bean id = "dbPool" class="org.example.spring.mvc.jdbc.DatabasePool"></bean>
<context:component-scan base-package="org.example.spring.mvc.bean"></context:component-scan>
<context:component-scan base-package="org.example.spring.mvc.jdbc"></context:component-scan>
</beans>
app-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="org.example.spring.mvc.controller"></context:component-scan>
</beans>