一、基本环境准备
1、配置pop.xml
pop文件可以直接复制使用不作修改,也可以根据自己的需求进行增删依赖和插件
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <modelVersion>4.0.0</modelVersion> 6 7 <groupId>org.tree</groupId> 8 <artifactId>A-lin</artifactId> 9 <version>1.0-SNAPSHOT</version> 10 <packaging>war</packaging> 11 12 <properties> 13 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 14 <maven.compiler.source>17</maven.compiler.source> 15 <maven.compiler.target>17</maven.compiler.target> 16 </properties> 17 18 19 <dependencies> 20 <!--mybatis--> 21 <dependency> 22 <groupId>org.mybatis</groupId> 23 <artifactId>mybatis</artifactId> 24 <version>3.5.11</version> 25 </dependency> 26 <!--mySql--> 27 <dependency> 28 <groupId>mysql</groupId> 29 <artifactId>mysql-connector-java</artifactId> 30 <version>8.0.30</version> 31 </dependency> 32 <!--servlet--> 33 <dependency> 34 <groupId>javax.servlet</groupId> 35 <artifactId>javax.servlet-api</artifactId> 36 <version>3.1.0</version> 37 <scope>provided</scope> 38 </dependency> 39 <!--jsp--> 40 <dependency> 41 <groupId>javax.servlet.jsp</groupId> 42 <artifactId>jsp-api</artifactId> 43 <version>2.2</version> 44 <scope>provided</scope> 45 </dependency> 46 <!--jstl--> 47 <dependency> 48 <groupId>jstl</groupId> 49 <artifactId>jstl</artifactId> 50 <version>1.2</version> 51 </dependency> 52 53 <dependency> 54 <groupId>taglibs</groupId> 55 <artifactId>standard</artifactId> 56 <version>1.1.2</version> 57 </dependency> 58 59 <dependency> 60 <groupId>com.alibaba</groupId> 61 <artifactId>fastjson</artifactId> 62 <version>1.2.62</version> 63 </dependency> 64 65 </dependencies> 66 67 <build> 68 <plugins> 69 <plugin> 70 <groupId>org.apache.tomcat.maven</groupId> 71 <artifactId>tomcat7-maven-plugin</artifactId> 72 <version>2.2</version> 73 </plugin> 74 </plugins> 75 </build> 76 77 </project>
2、配置mybatis.xml
mybatis文件要修改为自己的包名和数据库配置(database,username,password)
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 <configuration> 8 <!-- 1.改包名 9 2.数据库配置,数据库名称,用户名,密码 10 --> 12 <!--起别名--> 13 <typeAliases> <!--改包名--> 14 <package name="com.tree.entity"/> 15 </typeAliases> 16 17 <environments default="development"> 18 <environment id="development"> 19 <transactionManager type="JDBC"/> 20 <dataSource type="POOLED"> 21 <property name="driver" value="com.mysql.cj.jdbc.Driver"/> 22 <property name="url" value="jdbc:mysql:///tree?useSSL=false&useServerPrepStmts=true"/> 23 <property name="username" value="root"/> 24 <property name="password" value="root"/> 25 </dataSource> 26 </environment> 27 </environments> 28 <mappers> 29 <!--扫描mapper--> 30 <package name="com.tree.mapper"/><!--改包名--> 31 </mappers> 32 </configuration>
3、创建工厂类(简化获取数据库对象和连接,也减少资源占用,直接调用内部方法)
1 package com.tree.utils; 2 3 import org.apache.ibatis.io.Resources; 4 import org.apache.ibatis.session.SqlSessionFactory; 5 import org.apache.ibatis.session.SqlSessionFactoryBuilder; 6 7 import java.io.IOException; 8 import java.io.InputStream; 9 10 public class SqlSessionFactoryUtils { 11 private static SqlSessionFactory sqlSessionFactory; 12 13 static { 14 //静态代码块会随着类的加载而自动执行,且只执行一次 15 try { 16 String resource = "mybatis-config.xml"; 17 InputStream inputStream = Resources.getResourceAsStream(resource); 18 sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); 19 } catch (IOException e) { 20 e.printStackTrace(); 21 } 22 }
//调用getSqlSessionFactory方法23 public static SqlSessionFactory getSqlSessionFactory(){ 24 return sqlSessionFactory; 25 } 26 }
4.编写index.html和 jsp页面
index.html:
<a href="/A-lin/selectAllServlet">查询所有</a>
selectAll.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input type="button" value="新增" id="add"> <input type="button" value="刷新" id="refresh"><br> <hr> <table border="1" cellspacing="0" width="80%"> <tr> <th>学号</th> <th>姓名</th> <th>年龄</th> <th>操作</th> </tr> <c:forEach items="${students}" var="student"> <tr align="center"> <td id="${student.id}" name="id">${student.id}</td> <td>${student.name}</td> <td id="age">${student.age}</td> <td><a href="/A-lin/selectByIdServlet?id=${student.id}">修改</a> <a href="/A-lin/deleteByIdServlet?id=${student.id}">删除</a></td> </tr> </c:forEach> </table> <script> document.getElementById("add").onclick = function () { location.href = "addBrand.jsp"; } document.getElementById("refresh").onclick = function () { location.href = "/A-lin/selectAllServlet"; } </script> </body> </html>
add.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>添加信息</title> </head> <body> <h3>添加信息</h3> <form action="/A-lin/addServlet" method="post"> 学号:<input name="id"><br> 姓名:<input name="name"><br> 年龄:<input name="age"><br> <input type="submit" value="提交"> </form> </body> </html>
update.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>修改信息</title> </head> <body> <h3>修改信息</h3> <form action="/A-lin/updateByIdServlet" method="get"> <input type="hidden" name="id" value="${student.id}"> 姓名: <input readonly name="name" value="${student.name}"><br> 年龄: <input name="age" value="${student.age}"><br><br> <input type="submit" value="提交"> </form> </body> </html>
二、创建类和接口
1、编写实体类entity(有参无参构造方法、toString方法、set、get方法)
public class Student { private Integer id; private String name; private Integer age;
2、编写mapper接口和mapper.xml
1 public interface StudentMapper { 2 3 boolean add(Student student); 4 5 void deleteById(int id); 6 7 List<Student> selectAll(); 8 9 Student selectById(int id); 10 11 void updateById(Student student);
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper 3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 5 <mapper namespace="com.tree.mapper.StudentMapper"> 6 7 <resultMap id="studentResultMap" type="Student"> 8 9 </resultMap> 10 11 <!-- 增加--> 12 <insert id="add"> 13 insert into student1 values (#{id},#{name},#{age}); 14 </insert> 15 16 <!-- 根据id删除--> 17 <delete id="deleteById"> 18 delete from student1 where id = #{id}; 19 </delete> 20 21 <!-- 查询所有--> 22 <select id="selectAll" resultMap="studentResultMap"> 23 select * from student1; 24 </select> 25 <select id="selectById" resultType="com.tree.entity.Student"> 26 select * from student1 where id = #{id}; 27 </select> 28 <!-- 更改年龄--> 29 <update id="updateById"> 30 update student1 set age = #{age} where id = #{id}; 31 </update> 32 33 </mapper>
3、创建service层,调用mapper接口的方法
1 package com.tree.service; 2 3 import com.tree.entity.Student; 4 import com.tree.mapper.StudentMapper; 5 import com.tree.utils.SqlSessionFactoryUtils; 6 import org.apache.ibatis.session.SqlSession; 7 import org.apache.ibatis.session.SqlSessionFactory; 8 9 import java.util.List; 10 11 /** 12 * @author Tree 13 * @date 2022/12/10 00:11 14 */ 15 public class StudentService { 16 17 SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory(); 18 19 /** 20 * 增加 21 * 22 * @param student 23 * @return 24 */ 25 public void add(Student student) { 26 //2. 获取SqlSession 27 SqlSession sqlSession = factory.openSession(); 28 //3. 获取BrandMapper 29 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); 30 //4. 调用方法 31 mapper.add(student); 32 //5.提交并关闭事务 33 sqlSession.commit(); 34 sqlSession.close(); 35 } 36 37 /** 38 * 查询所有 39 */ 40 public List<Student> selectAll() { 41 //2. 获取SqlSession 42 SqlSession sqlSession = factory.openSession(); 43 //3. 获取BrandMapper 44 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); 45 //4. 调用方法 46 List<Student> students = mapper.selectAll(); 47 //5.提交事务 48 sqlSession.close(); 49 50 return students; 51 } 52 53 /** 54 * 查询id 55 */ 56 public Student selectById(int id) { 57 //2. 获取SqlSession 58 SqlSession sqlSession = factory.openSession(); 59 //3. 获取BrandMapper 60 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); 61 //4. 调用方法 62 Student student = mapper.selectById(id); 63 //5.提交事务关闭资源 64 sqlSession.close(); 65 //返回对象 66 return student; 67 } 68 69 70 /** 71 * 修改年龄 72 */ 73 public void updateById(Student student) { 74 //2. 获取SqlSession 75 SqlSession sqlSession = factory.openSession(); 76 //3. 获取BrandMapper 77 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); 78 //4. 调用方法 79 mapper.updateById(student); 80 //5.提交并关闭事务 81 sqlSession.commit(); 82 sqlSession.close(); 83 84 } 85 86 87 /** 88 * 删除 89 * 90 * @param id 91 */ 92 public void deleteById(int id) { 93 //2. 获取SqlSession 94 SqlSession sqlSession = factory.openSession(); 95 //3. 获取BrandMapper 96 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); 97 //4. 调用方法 98 mapper.deleteById(id); 99 //5.提交并关闭事务 100 sqlSession.commit(); 101 sqlSession.close(); 102 103 } 104 }
4、创建servlet类,调用service文件
addServlet:
package com.tree.servlet; import com.tree.entity.Student; import com.tree.service.StudentService; 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; @WebServlet("/addServlet") public class addServlet extends HttpServlet { private StudentService service = new StudentService(); @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //处理POST请求的乱码问题 request.setCharacterEncoding("utf-8"); // 1.接收并设置参数 int id = Integer.parseInt(request.getParameter("id")); String name = request.getParameter("name"); int age = Integer.parseInt(request.getParameter("age")); Student student = new Student(); student.setId(id); student.setName(name); student.setAge(age); // 2.调用BrandService完成查询 service.add(student); // 3. 存入request域中 request.setAttribute("Student", student); // 4. 转发到brand.jsp request.getRequestDispatcher("/selectAllServlet").forward(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
deleteServlet
package com.tree.servlet; import com.tree.service.StudentService; 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; @WebServlet("/deleteByIdServlet") public class deleteByIdServlet extends HttpServlet { private StudentService service = new StudentService(); @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //处理POST请求的乱码问题 request.setCharacterEncoding("utf-8"); // 1.接收参数 int id = Integer.parseInt(request.getParameter("id")); System.out.println(id); // 2.调用BrandService完成查询 service.deleteById(id); // 4. 转发到brand.jsp request.getRequestDispatcher("/selectAllServlet").forward(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
selectAll
1 package com.tree.servlet; 2 3 4 import com.tree.entity.Student; 5 import com.tree.service.StudentService; 6 7 import javax.servlet.ServletException; 8 import javax.servlet.annotation.WebServlet; 9 import javax.servlet.http.HttpServlet; 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 import java.io.IOException; 13 import java.util.List; 14 15 @WebServlet("/selectAllServlet") 16 public class selectAllServlet extends HttpServlet { 17 private StudentService service = new StudentService(); 18 19 @Override 20 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 21 //处理POST请求的乱码问题 22 request.setCharacterEncoding("utf-8"); 23 24 // 1.接收参数 25 26 // 2.调用BrandService完成查询 27 List<Student> students = service.selectAll(); 28 // 3. 存入request域中 29 request.setAttribute("students", students); 30 // 4. 转发到brand.jsp 31 request.getRequestDispatcher("/selectAll.jsp").forward(request, response); 32 } 33 34 @Override 35 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 36 this.doGet(request, response); 37 } 38 }
selectById:
package com.tree.servlet; import com.tree.entity.Student; import com.tree.service.StudentService; 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("/selectByIdServlet") public class selectByIdServlet extends HttpServlet { private StudentService service = new StudentService(); @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //处理POST请求的乱码问题 request.setCharacterEncoding("utf-8"); //1.接收参数 String id = request.getParameter("id"); // 2.调用BrandService完成查询 Student student = service.selectById(Integer.parseInt(id)); // 3. 存入request域中 request.setAttribute("student", student); // 4. 转发到brand.jsp request.getRequestDispatcher("/updateStudent.jsp").forward(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
update:
package com.tree.servlet; import com.tree.entity.Student; import com.tree.service.StudentService; 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("/updateByIdServlet") public class updateByIdServlet extends HttpServlet { private StudentService service = new StudentService(); @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //处理POST请求的乱码问题 request.setCharacterEncoding("utf-8"); // 1.接收参数 String id = request.getParameter("id"); String name = request.getParameter("name"); String age = request.getParameter("age"); //设置参数 Student student = new Student(); student.setId(Integer.valueOf(id)); student.setName(name); student.setAge(Integer.valueOf(age)); // 2.调用BrandService完成查询 service.updateById(student); // 4. 转发到brand.jsp request.getRequestDispatcher("/selectAllServlet").forward(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
成品页面很简陋就不放出来了,其实写好之后算是一个模板,以后有差不多的直接套用,兜兜转转也一年了
标签:JavaWeb,request,改查,javax,student,增删,import,servlet,id From: https://www.cnblogs.com/changeyi/p/16971830.html