第一天:后端思路梳理及代码实现
1.数据库设计
数据库设计使用一张表(course)设计
sql
CREATE TABLE course(
id INT PRIMARY KEY AUTO_INCREMENT COMMENT '课程ID',
cname VARCHAR(255) NOT NULL COMMENT '课程名称',
price DOUBLE NOT NULL COMMENT '售卖价格',
num_sort INT NOT NULL DEFAULT 0 COMMENT '排序',
cstatus TINYINT NOT NULL DEFAULT 1 COMMENT '状态',
course_bri VARCHAR(255) NOT NULL COMMENT '课程简介',
teacher_name VARCHAR(255) NOT NULL COMMENT '讲师姓名',
teacher_bri VARCHAR(255) COMMENT '讲师简介',
course_ol TEXT NOT NULL COMMENT '课程概述',
price_sale DOUBLE COMMENT '原价',
activ_flag VARCHAR(255) COMMENT '活动标签',
img_url VARCHAR(255) COMMENT '图片路径',
share_title VARCHAR(255) NOT NULL COMMENT '分享标题',
share_bri VARCHAR(255) NOT NULL COMMENT '分享简介',
course_other TEXT COMMENT 'markdown',
createTime DATETIME DEFAULT CURRENT_TIMESTAMP NULL COMMENT '创建时间',
updateTime DATETIME DEFAULT CURRENT_TIMESTAMP NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间');
2.环境搭建,依赖导入
使用三层架构,搭项目;
3.接口分析以及接口文档的书写
一共需要五个接口,接下来开始接口分析及书写;
1.测试类测试数据库连接
2.集成Tomcat
3.优化sevleat
发现书写接口时,不同接口对应不同的sevlet对象的话,会产生大量sevlet对象!
思路:使用反射机制来动态调用方法,使用继承机制来讲sevlet和具体执行方法分开!
java
package com.gzd.controller;
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.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class BaseController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method=req.getParameter("method");
if (method!=null){
Class clazz = this.getClass();
try {
Method method1 = clazz.getMethod(method, HttpServletRequest.class, HttpServletResponse.class);
method1.invoke(this,req,resp);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
}
=======================================================================================
java
package com.gzd.controller;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/course")
public class CourseManagerController extends BaseController{
public void findAll(HttpServletRequest req, HttpServletResponse resp){
System.out.println("我是findAll方法");
}
public void findByName(HttpServletRequest req, HttpServletResponse resp){
System.out.println("我是findByName方法");
}
public void findByStatus(HttpServletRequest req, HttpServletResponse resp){
System.out.println("我是findByStatus方法");
}
}
4.测试数据和实体类
java
package com.gzd.javaBean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@AllArgsConstructor//有参构造
@NoArgsConstructor//无参构造
public class Course {
private Integer id;
private String cname;
private Double price;
private Integer numSort;
private Integer cstatus;
private String courseBri;
private String teacherName;
private String teacherBri;
private String courseOl;
private Double priceSale;
private String activFlag;
private String imgUrl;
private String shareTitle;
private String shareBri;
private String courseOther;
private Date createTime;
private Date updateTime;
}
sql
INSERT INTO course (cname, price, num_sort, cstatus, course_bri, teacher_name, teacher_bri, course_ol, price_sale, activ_flag, img_url, share_title, share_bri, course_other, createTime, updateTime)
VALUES
('数据库基础', 99.99, 1, 1, '介绍数据库的基本概念和操作', '张老师', '资深数据库专家,多年教学经验', '本课程将详细介绍数据库的基础知识和常用操作。', 199.99, '限时优惠', 'https://example.com/database.jpg', '学习数据库,从基础开始', '掌握数据库知识,提升编程技能。', '## 数据库简介\n### 什么是数据库\n...\n### 数据库的作用\n...', NOW(), NOW()),
('Java编程入门', 149.99, 2, 1, 'Java编程语言入门课程,适合零基础学员', '李老师', 'Java开发专家,擅长Java Web开发', '本课程将引导学员从零开始学习Java编程语言。', 299.99, '早鸟优惠', 'https://example.com/java.jpg', 'Java编程,轻松入门', '零基础学Java,成为编程高手。', '## Java简介\n### Java的历史\n...\n### Java的特点\n...', NOW(), NOW()),
('Python数据分析', 299.99, 3, 1, '利用Python进行数据分析的实战课程', '王老师', '数据分析专家,擅长Python和机器学习', '本课程将教授学员如何使用Python进行数据分析。', 399.99, '新用户专享', 'https://example.com/python.jpg', 'Python数据分析,提升职场竞争力', '掌握Python数据分析,解锁职场新技能。', '## Python数据分析简介\n### 为什么选择Python\n...\n### Python数据分析工具\n...', NOW(), NOW());
5.接口编写:
java
public interface CourseDao {
public List<Course> findAll();
public Course findByname(String cname);
//查询状态
public List<Course> findBystatus(String status);
public int insert(Course course);
}
java
public class CourseDaoImp implements CourseDao {
//注入依赖
private JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());
@Override
public List<Course> findAll() {
return jdbcTemplate.query("SELECT id,cname,price,num_sort,cstatus FROM course",
new BeanPropertyRowMapper<Course>(Course.class));
}
@Override
public Course findByname(String cname) {
return jdbcTemplate.query("SELECT id,cname,price,num_sort,cstatus FROM course where cname=?",
new BeanPropertyRowMapper<Course>(Course.class),cname).get(0);
}
@Override
public List<Course> findBystatus(String cstatus) {
return jdbcTemplate.query("SELECT id,cname,price,num_sort,cstatus FROM course where cstatus=?",
new BeanPropertyRowMapper<Course>(Course.class),cstatus);
}
@Override
public int insert(Course course) {
Object[] arr = {
course.getCname(),
course.getPrice(),
course.getNumSort(),
course.getCstatus(),
course.getCourseBri(),
course.getTeacherName(),
course.getTeacherBri(),
course.getCourseOl(),
course.getPriceSale(),
course.getActivFlag(),
course.getImgUrl(),
course.getShareTitle(),
course.getShareBri(),
course.getCourseOther(),
course.getCreateTime(),
course.getUpdateTime()};
return jdbcTemplate.update("insert into course values (null,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", arr);
}
}
java
public interface CourseService {
//查询所有
public String findAll();
public String findByname(String cname);
public String findBystatus(String status);
//保存
public String saveCourse(Course course);
}
java
public class CourseServiceImp implements CourseService {
//注入依赖Dao层
private CourseDao courseDao = new CourseDaoImp();
@Override
public String findAll() {
return JSON.toJSONString(courseDao.findAll());
}
@Override
public String findByname(String cname) {
return JSON.toJSONString(courseDao.findByname(cname));
}
@Override
public String findBystatus(String status) {
return JSON.toJSONString(courseDao.findBystatus(status));
}
@Override
public String saveCourse(Course course) {
int insert = courseDao.insert(course);
if (insert ==0){
return "error!";
}
return "success";
}
}
java
@WebServlet("/course")
public class CourseManagerController extends BaseController {
//注入依赖
private CourseService courseService = new CourseServiceImp();
//1:查询所有
public void findAll(HttpServletRequest req, HttpServletResponse resp)throws Exception{
resp.setCharacterEncoding("UTF-8");
System.out.println(courseService.findAll());
resp.getWriter().write(courseService.findAll());
}
//2:根据课程名称查询
public void findByName(HttpServletRequest req, HttpServletResponse resp)throws Exception{
//乱码问题
req.setCharacterEncoding("UTF-8");
String cname = req.getParameter("cname");
resp.setCharacterEncoding("UTF-8");
resp.getWriter().write(courseService.findByname(cname));
}
public void findByStatus(HttpServletRequest req, HttpServletResponse resp)throws Exception{
resp.setCharacterEncoding("UTF-8");
resp.getWriter().write(courseService.findBystatus(req.getParameter("cstatus")));
}
//新建接口
public void saveCourse(HttpServletRequest req, HttpServletResponse resp) throws Exception{
//接受前端数据
DiskFileItemFactory factory = new DiskFileItemFactory();
//核心类
ServletFileUpload upload = new ServletFileUpload(factory);
//开始解析
//判断req有没有二进制的表单
boolean flag = ServletFileUpload.isMultipartContent(req);
//实体类
Course course = new Course();
//map集合
Map<String,Object> map = new HashMap<>();
if (flag){
//转换
List<FileItem> list= upload.parseRequest(req);
if (list!=null){
for (FileItem fileItem : list){
//实体类
//普通数据 文件数据
boolean flag_ = fileItem.isFormField();
if (flag_){
//获取key
String key = fileItem.getFieldName();
//获取value,指定字符集
String value = fileItem.getString("UTF-8");
//实体类封装
map.put(key,value);
}else {
InputStream inputStream = fileItem.getInputStream();
String imgurl = "http://localhost:8080/uploda"+System.currentTimeMillis()+fileItem.getName();
FileOutputStream outputStream = new FileOutputStream(imgurl);
//读写操作
IOUtils.copy(inputStream,outputStream);
//添加到map中
map.put("imgurl",imgurl);
}
}
}
}
//完成封装,调用service
BeanUtils.populate(course,map);
resp.getWriter().write(courseService.saveCourse(course));
}
//修改接口
}
java
public class BaseController extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//所有的请求都能接 method+接口名
String method = req.getParameter("method");
if (method!=null){
try {
//获取运行当前类时对象
Class class_ = this.getClass();//Class对象<> CourseManagerController
//Object o = class_.getConstructor().newInstance();
//获取当前运行时类的方法
Method class_method = class_.getMethod(method, HttpServletRequest.class,
HttpServletResponse.class);
//调用方啊
class_method.invoke(this,req,resp);
} catch (Exception e) {
System.out.println("没有该请求");
e.printStackTrace();
}
}
}
}