三层架构 —— 具体代码
一、前提概要
1. 表示层(Web)接收请求、响应数据
(1)接收请求参数
(2)调用service查询学生
(3)返回结果
2. 业务层(Service)逻辑处理
(1)调用mapper查询学生
3. 持久层(Dao)数据访问
@Select(" ")
void selectById(Integer id);
二、准备环境
1. 创建新的环境,引入坐标
2. 创建包结构( domain、util、servlet、service、mapper )
3. 添加文件( Mybatis配置文件、工具类、实体类 )
4. 添加过滤器(全面处理中文乱码)
5. 添加前端页面
6. 部署测试
三、具体代码
(一)domain( 实体类包 )
1 package com.itheima.domain; 2 3 import lombok.AllArgsConstructor; 4 import lombok.Data; 5 import lombok.NoArgsConstructor; 6 7 @Data 8 @NoArgsConstructor 9 @AllArgsConstructor 10 public class Student { 11 private String id; //学号 12 private String name; //姓名 13 private String birthday; //生日 14 private String address; //地址 15 }
(二)mapper( 持久层 )
1 package com.itheima.mapper; 2 3 import com.itheima.domain.Student; 4 import org.apache.ibatis.annotations.Delete; 5 import org.apache.ibatis.annotations.Insert; 6 import org.apache.ibatis.annotations.Select; 7 import org.apache.ibatis.annotations.Update; 8 9 import java.util.List; 10 11 public interface StudentMapper { 12 @Select("select * from student") 13 List<Student> findAll(); 14 15 @Insert("insert into student values(#{id},#{name},#{birthday},#{address})") 16 void save(Student student); 17 18 @Delete("delete from student where id = #{id}") 19 void deleteById(String id); 20 21 @Select("select * from student where id = #{id}") 22 Student findById(String id); 23 24 @Update("update student set name = #{name}, birthday = #{birthday}, address = #{address} where id = #{id}") 25 void update(Student student); 26 }
(三)service( 业务层 )
1 package com.itheima.service; 2 3 import com.itheima.domain.Student; 4 5 import java.util.List; 6 7 public interface StudentService { 8 9 List<Student> findAll(); 10 11 void save(Student student); 12 13 void deleteById(String id); 14 15 Student findById(String id); 16 17 void update(Student student); 18 }
impl
1 package com.itheima.service.impl; 2 3 import com.itheima.domain.Student; 4 import com.itheima.mapper.StudentMapper; 5 import com.itheima.service.StudentService; 6 import com.itheima.util.MyBatisUtil; 7 import org.apache.ibatis.session.SqlSession; 8 9 import java.util.List; 10 11 public class StudentServiceImpl implements StudentService { 12 @Override 13 public List<Student> findAll() { 14 SqlSession sqlSession = MyBatisUtil.getSqlSession(); 15 StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); 16 List<Student> list = studentMapper.findAll(); 17 MyBatisUtil.close(sqlSession); 18 return list; 19 } 20 21 @Override 22 public void save(Student student) { 23 SqlSession sqlSession = MyBatisUtil.getSqlSession(); 24 StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); 25 studentMapper.save(student); 26 MyBatisUtil.close(sqlSession); 27 } 28 29 @Override 30 public void deleteById(String id) { 31 SqlSession sqlSession = MyBatisUtil.getSqlSession(); 32 StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); 33 studentMapper.deleteById(id); 34 MyBatisUtil.close(sqlSession); 35 } 36 37 @Override 38 public Student findById(String id) { 39 SqlSession sqlSession = MyBatisUtil.getSqlSession(); 40 StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); 41 Student student = studentMapper.findById(id); 42 MyBatisUtil.close(sqlSession); 43 return student; 44 } 45 46 @Override 47 public void update(Student student) { 48 SqlSession sqlSession = MyBatisUtil.getSqlSession(); 49 StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); 50 studentMapper.update(student); 51 MyBatisUtil.close(sqlSession); 52 } 53 }
(四)util( 工具类包 )
1 package com.itheima.util; 2 3 import org.apache.ibatis.io.Resources; 4 import org.apache.ibatis.session.SqlSession; 5 import org.apache.ibatis.session.SqlSessionFactory; 6 import org.apache.ibatis.session.SqlSessionFactoryBuilder; 7 8 import java.io.InputStream; 9 10 public class MyBatisUtil { 11 private static SqlSessionFactory sqlSessionFactory; 12 13 //静态代码块 14 static { 15 try { 16 //读取配置文件,读成数据流 17 InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml"); 18 19 //创建SqlSessionFactory 20 sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); 21 } catch (Exception e) { 22 e.printStackTrace(); 23 } 24 } 25 26 //获取sqlSession 27 public static SqlSession getSqlSession() { 28 return sqlSessionFactory.openSession(); 29 } 30 31 //提交事务和释放资源 32 public static void close(SqlSession sqlSession) { 33 if (sqlSession != null) { 34 //提交事务(mybatis默认情况下是不会自动提交事务) 35 sqlSession.commit(); 36 37 //释放资源 38 sqlSession.close(); 39 } 40 } 41 }
(五)web( 表示层 )
filter
1 package com.itheima.web.filter; 2 import javax.servlet.*; 3 import javax.servlet.annotation.WebFilter; 4 import javax.servlet.http.HttpServletRequest; 5 import javax.servlet.http.HttpServletResponse; 6 import java.io.IOException; 7 8 /** 9 * 解决全站乱码问题,处理所有的请求 10 */ 11 @WebFilter("/*") 12 public class CharacterEncodingFilter implements Filter { 13 @Override 14 public void doFilter(ServletRequest req, ServletResponse rep, FilterChain filterChain) throws IOException, ServletException { 15 //将父接口转为子接口 16 HttpServletRequest request = (HttpServletRequest) req; 17 HttpServletResponse response = (HttpServletResponse) rep; 18 19 //不需要过滤的url 20 String path = request.getServletPath(); 21 String[] urls = {".html", ".js", ".css", ".ico", ".jpg", ".png"}; 22 boolean flag = true; 23 for (String str : urls) { 24 if (path.indexOf(str) != -1) { 25 flag = false; 26 break; 27 } 28 } 29 30 //需要过滤的资源走这个逻辑 31 if (flag) { 32 //解决post请求中文数据乱码问题 33 if (request.getMethod().equalsIgnoreCase("post")) { 34 request.setCharacterEncoding("utf-8"); 35 } 36 37 //解决跨域问题 38 /* 允许跨域的主机地址 */ 39 response.setHeader("Access-Control-Allow-Origin", "*"); 40 /* 允许跨域的请求方法GET, POST, HEAD 等 */ 41 response.setHeader("Access-Control-Allow-Methods", "*"); 42 /* 重新预检验跨域的缓存时间 (s) */ 43 response.setHeader("Access-Control-Max-Age", "3600"); 44 /* 允许跨域的请求头 */ 45 response.setHeader("Access-Control-Allow-Headers", "*"); 46 /* 是否携带cookie */ 47 response.setHeader("Access-Control-Allow-Credentials", "true"); 48 49 50 //处理响应乱码 51 response.setContentType("application/json;charset=utf-8"); 52 } 53 54 filterChain.doFilter(request, response); 55 } 56 57 @Override 58 public void init(FilterConfig filterConfig) throws ServletException { 59 60 } 61 @Override 62 public void destroy() { 63 64 } 65 }
1 package com.itheima.web.servlet; 2 3 import cn.hutool.core.io.IoUtil; 4 import com.fasterxml.jackson.databind.ObjectMapper; 5 import com.itheima.domain.Student; 6 import com.itheima.service.StudentService; 7 import com.itheima.service.impl.StudentServiceImpl; 8 9 import javax.servlet.ServletException; 10 import javax.servlet.ServletInputStream; 11 import javax.servlet.annotation.WebServlet; 12 import javax.servlet.http.HttpServlet; 13 import javax.servlet.http.HttpServletRequest; 14 import javax.servlet.http.HttpServletResponse; 15 import java.io.IOException; 16 import java.util.List; 17 18 @WebServlet("/studentServlet") 19 public class StudentServlet extends HttpServlet { 20 @Override 21 protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 22 // 接收action,确定请求目的 23 String action = req.getParameter("action"); 24 if ("findAll".equals(action)) { 25 findAll(req, resp); 26 } else if ("save".equals(action)) { 27 save(req, resp); 28 } else if ("deleteById".equals(action)) { 29 deleteById(req, resp); 30 } else if ("findById".equals(action)) { 31 findById(req, resp); 32 } else if ("update".equals(action)) { 33 update(req, resp); 34 } else { 35 resp.getWriter().write("方法请求错误"); 36 } 37 } 38 39 // 修改 40 private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException { 41 // 1. 获取请求参数 42 ServletInputStream is = req.getInputStream(); 43 String json = IoUtil.read(is, "utf-8"); 44 Student student = new ObjectMapper().readValue(json, Student.class); 45 // 2. 调用业务逻辑 46 StudentService studentService = new StudentServiceImpl(); 47 studentService.update(student); 48 // 3. 响应结果 49 resp.getWriter().write("OK"); 50 } 51 52 // 根据id查询学生(回显) 53 private void findById(HttpServletRequest req, HttpServletResponse resp) throws IOException { 54 // 1. 获取请求参数 55 String id = req.getParameter("id"); 56 // 2. 调用业务逻辑 57 StudentService studentService = new StudentServiceImpl(); 58 Student student = studentService.findById(id); 59 // 3. 响应结果 60 String json = new ObjectMapper().writeValueAsString(student); 61 resp.getWriter().write(json); 62 } 63 64 // 根据id删除 65 private void deleteById(HttpServletRequest req, HttpServletResponse resp) throws IOException { 66 // 1. 获取请求参数 67 String id = req.getParameter("id"); 68 // 2. 调用业务逻辑 69 StudentService studentService = new StudentServiceImpl(); 70 studentService.deleteById(id); 71 // 3. 响应结果 72 resp.getWriter().write("OK"); 73 74 } 75 76 // 新增 77 private void save(HttpServletRequest req, HttpServletResponse resp) throws IOException { 78 // 1. 获取请求参数(如果页面提交的数据为json格式,则req.getPXXX方法不能用了,只能使用字节流获取) 79 // String id = req.getParameter("id"); 80 ServletInputStream is = req.getInputStream(); 81 // 把字节数据转换为指定编码格式的字符串{key:value} 82 String json = IoUtil.read(is, "utf-8"); 83 Student student = new ObjectMapper().readValue(json, Student.class); 84 // 2. 调用业务逻辑 85 StudentService studentService = new StudentServiceImpl(); 86 studentService.save(student); 87 // 3. 响应结果 88 resp.getWriter().write("OK"); 89 } 90 91 // 查询所有 92 private void findAll(HttpServletRequest req, HttpServletResponse resp) throws IOException { 93 // 1. 获取请求参数(无) 94 95 // 2. 调用业务逻辑 96 StudentService studentService = new StudentServiceImpl(); 97 List<Student> studentList = studentService.findAll(); 98 // 3. 响应结果 99 String json = new ObjectMapper().writeValueAsString(studentList); 100 resp.getWriter().write(json); 101 } 102 }
四、配置
(一)pom.xml
1 <dependencies> 2 <!--数据库驱动--> 3 <dependency> 4 <groupId>mysql</groupId> 5 <artifactId>mysql-connector-java</artifactId> 6 <version>8.0.28</version> 7 </dependency> 8 <!--mybatis框架--> 9 <dependency> 10 <groupId>org.mybatis</groupId> 11 <artifactId>mybatis</artifactId> 12 <version>3.5.9</version> 13 </dependency> 14 <!--lombok--> 15 <dependency> 16 <groupId>org.projectlombok</groupId> 17 <artifactId>lombok</artifactId> 18 <version>1.18.26</version> 19 </dependency> 20 <!--json转换工具--> 21 <dependency> 22 <groupId>com.fasterxml.jackson.core</groupId> 23 <artifactId>jackson-databind</artifactId> 24 <version>2.9.9</version> 25 </dependency> 26 <!--单元测试--> 27 <dependency> 28 <groupId>junit</groupId> 29 <artifactId>junit</artifactId> 30 <version>4.12</version> 31 </dependency> 32 33 <!--hutool--> 34 <dependency> 35 <groupId>cn.hutool</groupId> 36 <artifactId>hutool-all</artifactId> 37 <version>5.4.3</version> 38 </dependency> 39 <!--servlet--> 40 <dependency> 41 <groupId>javax.servlet</groupId> 42 <artifactId>javax.servlet-api</artifactId> 43 <version>3.0.1</version> 44 </dependency> 45 </dependencies> 46 47 <build> 48 <plugins> 49 <plugin> 50 <groupId>org.apache.maven.plugins</groupId> 51 <artifactId>maven-war-plugin</artifactId> 52 <version>3.2.2</version> 53 </plugin> 54 </plugins> 55 </build>
(二)resources
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> 3 <configuration> 4 5 <!--配置--> 6 <settings> 7 <setting name="logImpl" value="STDOUT_LOGGING"/> 8 <setting name="mapUnderscoreToCamelCase" value="true"/> 9 </settings> 10 11 <!--数据库环境配置--> 12 <environments default="mysql"> 13 <environment id="mysql"> 14 <transactionManager type="JDBC"/> 15 <dataSource type="POOLED"> 16 <property name="driver" value="com.mysql.cj.jdbc.Driver"/> 17 <property name="url" value="jdbc:mysql://localhost:3306/vue"/> 18 <property name="username" value="root"/> 19 <property name="password" value="root"/> 20 </dataSource> 21 </environment> 22 </environments> 23 24 <!--映射关系配置--> 25 <mappers> 26 <package name="com.itheima.mapper"></package> 27 </mappers> 28 </configuration>