作者:拜客
IStudentDao.java代码如下(示例):
public interface IStudentDao {
//查询全部学生
public List<Student> queryAllStudent();
public Student queryStudentBySno(int sno);
public boolean isExist(int sno) ;
public boolean addStudent(Student student) ;
public boolean deleteStudentBySno(int sno);
public boolean updateStudentBySno(int sno,Student student) ;
}
StudentDaoImpl.java代码如下(示例):
package org.mabo.dao.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.mabo.dao.IStudentDao;
import org.mabo.entity.Student;
import org.mabo.util.DBUtil;
//数据访问层 原子性
public class StudentDaoImpl implements IStudentDao{
public static int getTotalCount(String sql) {
ResultSet rs=null;
int count=-1;
rs=DBUtil.executeQuery(sql, null);
try {
if(rs.next()) {
count=rs.getInt(1);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
DBUtil.closeAll();
}
return count;
}
//查询全部学生
public List<Student> queryAllStudent() {
List<Student> students=new ArrayList<Student>();
Student student=new Student();
ResultSet rs=null;
try {
String sql="select *from student";
rs=DBUtil.executeQuery(sql, null);
while(rs.next()) {
int no=rs.getInt("sno");
String name=rs.getString("sname");
int age= rs.getInt("sage");
String address= rs.getString("saddress");
student=new Student(no,name,age,address);
students.add(student);
}
return students;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
finally {
DBUtil.closeAll();
}
}
public Student queryStudentBySno(int sno) {
ResultSet rs=null;
Student student=new Student();
try {
String sql="select *from student where sno=?";
Object[]params= {sno};
rs=DBUtil.executeQuery(sql, params);
if(rs.next()) {
int no=rs.getInt("sno");
String name=rs.getString("sname");
int age= rs.getInt("sage");
String address= rs.getString("saddress");
student=new Student(no,name,age,address);
}
return student;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
finally {
DBUtil.closeAll();
}
}
public boolean isExist(int sno) {
return queryStudentBySno(sno)==null ? false:true;
}
public boolean addStudent(Student student) {
String sql="insert into student values(?,?,?,?)";
Object[]params= {student.getSno(),student.getSname(),student.getSage(),student.getSadress()};
return DBUtil.executeUpdate(sql, params);
}
public boolean deleteStudentBySno(int sno) {
String sql="DELETE FROM student WHERE sno=?";
Object[]params= {sno};
return DBUtil.executeUpdate(sql, params);
}
public boolean updateStudentBySno(int sno,Student student) {
String sql="update student set sname=? ,sage=?,saddress=? where sno=?";
Object[]params= {student.getSname(),student.getSage(),student.getSadress(),student.getSno()};
return DBUtil.executeUpdate(sql, params);
}
}
Student.java代码如下(示例):
package org.mabo.entity;
//实体类
public class Student {
private int sno;
private String sname;
private int sage;
private String saddress;
public int getSno() {
return sno;
}
public void setSno(int sno) {
this.sno = sno;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public int getSage() {
return sage;
}
public void setSage(int sage) {
this.sage = sage;
}
public String getSadress() {
return saddress;
}
public void setSadress(String sadress) {
this.saddress = sadress;
}
public Student(int sno, String sname, int sage, String sadress) {
super();
this.sno = sno;
this.sname = sname;
this.sage = sage;
this.saddress = sadress;
}
public Student() {
}
public Student( int sage, String sadress) {
this.sage = sage;
this.saddress = sadress;
}
@Override
public String toString() {
return "Student [sno=" + sno + ", sname=" + sname + ", sage=" + sage + ", saddress=" + saddress + "]";
}
}
IStudentService.java代码如下(示例):
package org.mabo.service;
import java.util.List;
import org.mabo.entity.Student;
public interface IStudentService {
public boolean addStudent(Student student);
//删除学生
public boolean deleteStudent(int sno) ;
//更新学生信息
public boolean updateStudentBySno(int sno,Student student) ;
//根据学号查询学生
public Student queryStudentBySno(int sno) ;
//查询所有学生
public List<Student> queryAllStudent();
}
StudentServiceImpl.java代码如下(示例):
package org.mabo.service.impl;
import org.mabo.dao.IStudentDao;
import org.mabo.dao.impl.StudentDaoImpl;
import org.mabo.entity.Student;
import org.mabo.service.IStudentService;
import java.util.List;
//业务逻辑层
//负责对dao层进行组装
public class StudentServiceImpl implements IStudentService{
StudentDaoImpl studentDao=new StudentDaoImpl();
//增加学生
public boolean addStudent(Student student) {
if(studentDao.isExist(student.getSno())) {
studentDao.addStudent(student);
return true;
}
else {
return false;
}
}
//删除学生
public boolean deleteStudent(int sno) {
if(studentDao.isExist(sno)) {
return studentDao.deleteStudentBySno(sno);
}
return false;
}
//更新学生信息
public boolean updateStudentBySno(int sno,Student student) {
if(studentDao.isExist(sno)) {
return studentDao.updateStudentBySno(sno, student);
}
return false;
}
//根据学号查询学生
public Student queryStudentBySno(int sno) {
return studentDao.queryStudentBySno(sno);
}
//查询所有学生
public List<Student> queryAllStudent(){
return studentDao.queryAllStudent();
}
}
MyController.java代码如下(示例):
package com.mabo.controller;
import com.mabo.entity.Student;
import com.mabo.service.IStudentService;
import com.mabo.service.impl.StudentServiceImpl;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;
@Controller
public class MyController {
@RequestMapping(value = "/some.do")
public ModelAndView doSome(){
//处理some.do请求,相当于service调用处理完成了
ModelAndView mv = new ModelAndView();
//添加数据,框架在请求的最后把数据放入到request作用域
//request.setAttribute("msg","欢迎使用....");
mv.addObject("msg","欢迎使用springmvc做web开发");
mv.addObject("fun","执行的是doSome方法");
//指定视图,指定视图的完整路径
//框架对视图执行的forward操作,request.getRequestDispather("/show.jsp").forward(...)
mv.setViewName("show.jsp");
return mv;
}
@RequestMapping(value = "/queryAllStudent.do")
public ModelAndView doQueryAllStudent(){
IStudentService service=new StudentServiceImpl();
List<Student> students= service.queryAllStudent();
System.out.println(students.toString());
//处理some.do请求,相当于service调用处理完成了
ModelAndView mv = new ModelAndView();
//添加数据,框架在请求的最后把数据放入到request作用域
//request.setAttribute("msg","欢迎使用....");
mv.addObject("students",students);
//指定视图,指定视图的完整路径
//框架对视图执行的forward操作,request.getRequestDispather("/show.jsp").forward(...)
mv.setViewName("/index2.jsp");
return mv;
}
@RequestMapping(value = "/AddStudentServlet.do")
public ModelAndView doAddStudent(HttpServletRequest request){
try {
request.setCharacterEncoding("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
int no = Integer.parseInt(request.getParameter("sno")) ;
String name = request.getParameter("sname");
int age =Integer.parseInt(request.getParameter("sage")) ;
String address = request.getParameter("saddress");
Student student=new Student(no,name,age,address);
IStudentService service=new StudentServiceImpl();
boolean result= service.addStudent(student);
ModelAndView mv = new ModelAndView();
if(result==true) {
System.out.print("增加成功");
mv.setViewName("/queryAllStudent.do");
}
else {
System.out.print("增加失败");
}
return mv;
}
@RequestMapping(value = "/QueryStudentBySno.do")
public ModelAndView doQueryStudentBySno(HttpServletRequest request) {
try {
request.setCharacterEncoding("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
int no = Integer.parseInt(request.getParameter("sno"));
IStudentService service = new StudentServiceImpl();
Student student = service.queryStudentBySno(no);
if (student != null) {
ModelAndView mv = new ModelAndView();
//添加数据,框架在请求的最后把数据放入到request作用域
//request.setAttribute("msg","欢迎使用....");
mv.addObject("student", student);
//指定视图,指定视图的完整路径
//框架对视图执行的forward操作,request.getRequestDispather("/show.jsp").forward(...)
mv.setViewName("personInfo.jsp");
return mv;
} else {
System.out.println("失败");
}
return null;
}
@RequestMapping(value = "/DeleteStudentServlet.do")
public ModelAndView doDeleteStudent(HttpServletRequest request) {
int no = Integer.parseInt(request.getParameter("sno")) ;
IStudentService service=new StudentServiceImpl();
boolean result=service.deleteStudent(no);
if(result) {
ModelAndView mv = new ModelAndView();
mv.setViewName("/queryAllStudent.do");
return mv;
}
else return null;
}
@RequestMapping(value = "/UpdateStudent.do")
public ModelAndView doUpdateStudent(HttpServletRequest request) {
try {
request.setCharacterEncoding("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
int no = Integer.parseInt(request.getParameter("sno")) ;
String name = request.getParameter("sname");
int age =Integer.parseInt(request.getParameter("sage")) ;
String address = request.getParameter("saddress");
Student student=new Student(no,name,age,address);
IStudentService service=new StudentServiceImpl();
boolean result= service.updateStudentBySno(no, student);
ModelAndView mv=new ModelAndView();
if(result) {
System.out.print("成功");
mv.setViewName("/queryAllStudent.do");
return mv;
}
else {
System.out.print("失败");
return null;
}
}
}
DBUtil.java代码如下(示例):
package org.mabo.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.mabo.entity.Student;
public class DBUtil {
static String URL = "jdbc:mysql://localhost:3306/user?serverTimezone=UTC" ;
static String USERNAME = "root" ;
static String PWD = "368542";
public static Connection connection=null;
public static PreparedStatement pStatement=null;
public static ResultSet rs=null;
public static Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
return DriverManager.getConnection(URL, USERNAME, PWD);
}
public static PreparedStatement createPreparedStatement(String sql, Object[] params) throws ClassNotFoundException, SQLException {
pStatement=getConnection().prepareStatement(sql);
if(params!=null) {
for(int i=0;i<params.length;i++) {
pStatement.setObject(i+1, params[i]);
}
}
return pStatement;
}
public static boolean executeUpdate(String sql, Object[] params) {
try {
pStatement=createPreparedStatement(sql,params);
int count=pStatement.executeUpdate();
if(count>0) {
return true;
}
else {
return false;
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
finally {
try {
if(pStatement!=null) {
pStatement.close();
}
if(connection!=null) {
connection.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static ResultSet executeQuery(String sql,Object[]params) {
try {
pStatement=createPreparedStatement(sql,params);
rs=pStatement.executeQuery();
return rs;
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public static void closeAll() {
try {
if(DBUtil.rs!=null) {
DBUtil.rs.close();
}
if(DBUtil.pStatement!=null) {
DBUtil.pStatement.close();
}
if(DBUtil.connection!=null) {
DBUtil.connection.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
index.jsp代码如下(示例):
<%@page import="java.util.List"%>
<%@page import="org.mabo.entity.Student"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="" method="post" >
<table border="1">
<tr>
<th>学号</th>
<th>姓名</th>
<th>年龄</th>
<th>地址</th>
<th>操作</th>
</tr>
<%
List<Student> students=(List<Student>)request.getAttribute("students");
for(Student student:students){
%>
<tr>
<th><a href="QueryStudentBySnoServlet?sno=<%=student.getSno() %>"><%=student.getSno() %></a></th>
<th><a><%=student.getSname() %></a></th>
<th><a><%=student.getSage() %></a></th>
<th><a><%=student.getSadress() %></a></th>
<th><a href="DeleteStudentServlet?sno=<%=student.getSno() %>">删除</a></th>
</tr>
<%
}
%>
</table>
<a href="add.jsp">新增</a>
</form>
</body>
</html>
personInfo.jsp代码如下(示例):
<%@page import="org.mabo.entity.Student"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>个人信息</title>
</head>
<body>
<%
Student student=(Student)request.getAttribute("student");
%>
<form action="UpdateStudentServlet" method="post">
学号:<input type="text" name="sno" value="<%=student.getSno() %>" readonly="readonly"><br>
姓名:<input type="text" name="sname" value="<%=student.getSname() %>"><br>
年龄:<input type="text" name="sage" value="<%=student.getSage() %>"><br>
地址:<input type="text" name="saddress" value="<%=student.getSadress() %>"><br>
<input type="submit" value="修改"><br><a href="QueryAllStudentServlet">返回</a>
</form>
</body>
</html>
add.jsp代码如下(示例):
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="AddStudentServlet" method="post">
学号:<input type="text" name="sno"><br>
姓名:<input type="text" name="sname"><br>
年龄:<input type="text" name="sage"><br>
地址:<input type="text" name="saddress"><br>
<input type="submit" value="新增"><br><a href="QueryAllStudentServlet">返回</a>
</form>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.mabo</groupId>
<artifactId>SpringMVC</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--spring mvc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
</dependencies>
<build>
</build>
</project>
<?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
https://www.springframework.org/schema/context/spring-context.xsd">
<!--声明组件扫描器-->
<context:component-scan base-package="com.mabo"/>
</beans>
<?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">
<!--声明:注册springmvc的核心对象DispatcherServlet
需要在tomcat服务器启动后,创建DispatcherServlet对象实例
为什么要创建DispatcherServlet对象的实例呢?
因为在DispatcherServlet创建过程中,会同时创建springmvc容器对象,
读取springmvc的配置文件,把这个配置文件中的对象都配置好,
当用户发起请求时就可以直接使用对象了。
servlet的初始化会执行init()方法,DispatcherServlet在init()中{
//创建容器,读取配置文件
webApplicationContext ctx = new ClassPathXmlApplicationContext("springmvc.xml");
//把容器对象放入到ServletContext中
getServletContext().setAttribute(key,ctx);
}
-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--自定义springmvc读取文件的位置-->
<init-param>
<!--springmvc配置文件的位置属性-->
<param-name>contextConfigLocation</param-name>
<!--指定自定义文件的位置-->
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!--表示在tomcat启动后,创建servlet对象
数字表示启动后创建对象的顺序,数值越小,tomcat创建对象越早,要求大于等于0的整数
-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!--
使用框架的时候,url-pattern可以使用两种值
1.使用扩展名方式,语法 *.xxxx , xxxx时自定义扩展名。常用的方式 *.do, *.action, *.mvc等等
http://localhost:8080/myweb/some.do
http://localhost:8080?myweb/other.do
2.使用斜杠"/"
-->
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!--欢迎页面-->
<welcome-file-list>
<welcome-file>queryAllStudent.do</welcome-file>
</welcome-file-list>
</web-app>
欢迎页面为controller
跳转后为index.jsp
点击删除自动跳转到index.jsp
点击学生学号进入详细信息
该界面可以修改学生信息,修改完毕跳转到index.jsp
学号不可改
org.springframework.web.servlet.DispatcherServletr配置的时候爆红,并且在maven依赖中找不到相关的包
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
解决办法:在lib目录导入包spring-web-5.2.6.RELEASE.jar并添加
添加jar包
选择并确定
[MVC注解的项目参考教学视频](https://www.bilibili.com/video/BV1sk4y167pD)
[servlet基础参考视频](https://www.bilibili.com/video/BV18s411u7EH?p=38&t=509)