练竹园何平安

Javaweb实战项目:公司信息管理系统(上)

Toretto·2023-08-24 02:02·111 次阅读

Javaweb实战项目:公司信息管理系统(上)

科普一下htpps各种错误代码:常见HTTP错误代码大全 – 知乎 (zhihu.com)

环境搭建/基础准备

创建如下的文件

配置MySQL数据库:

-- 部门管理
create table dept(
    id int unsigned primary key auto_increment comment '主键ID',
    name varchar(10) not null unique comment '部门名称',
    create_time datetime not null comment '创建时间',
    update_time datetime not null comment '修改时间'
) comment '部门表';
insert into dept (id, name, create_time, update_time) values(1,'学工部',now(),now()),(2,'教研部',now(),now()),(3,'咨询部',now(),now()), (4,'就业部',now(),now()),(5,'人事部',now(),now());
-- 员工管理(带约束)
create table emp (
  id int unsigned primary key auto_increment comment 'ID',
  username varchar(20) not null unique comment '用户名',
  password varchar(32) default '123456' comment '密码',
  name varchar(10) not null comment '姓名',
  gender tinyint unsigned not null comment '性别, 说明: 1 男, 2 女',
  image varchar(300) comment '图像',
  job tinyint unsigned comment '职位, 说明: 1 班主任,2 讲师, 3 学工主管, 4 教研主管, 5 咨询师',
  entrydate date comment '入职时间',
  dept_id int unsigned comment '部门ID',
  create_time datetime not null comment '创建时间',
  update_time datetime not null comment '修改时间'
) comment '员工表';
INSERT INTO emp
	(id, username, password, name, gender, image, job, entrydate,dept_id, create_time, update_time) VALUES
	(1,'jinyong','123456','金庸',1,'1.jpg',4,'2000-01-01',2,now(),now()),
	(2,'zhangwuji','123456','张无忌',1,'2.jpg',2,'2015-01-01',2,now(),now()),
	(3,'yangxiao','123456','杨逍',1,'3.jpg',2,'2008-05-01',2,now(),now()),
	(4,'weiyixiao','123456','韦一笑',1,'4.jpg',2,'2007-01-01',2,now(),now()),
	(5,'changyuchun','123456','常遇春',1,'5.jpg',2,'2012-12-05',2,now(),now()),
	(6,'xiaozhao','123456','小昭',2,'6.jpg',3,'2013-09-05',1,now(),now()),
	(7,'jixiaofu','123456','纪晓芙',2,'7.jpg',1,'2005-08-01',1,now(),now()),
	(8,'zhouzhiruo','123456','周芷若',2,'8.jpg',1,'2014-11-09',1,now(),now()),
	(9,'dingminjun','123456','丁敏君',2,'9.jpg',1,'2011-03-11',1,now(),now()),
	(10,'zhaomin','123456','赵敏',2,'10.jpg',1,'2013-09-05',1,now(),now()),
	(11,'luzhangke','123456','鹿杖客',1,'11.jpg',5,'2007-02-01',3,now(),now()),
	(12,'hebiweng','123456','鹤笔翁',1,'12.jpg',5,'2008-08-18',3,now(),now()),
	(13,'fangdongbai','123456','方东白',1,'13.jpg',5,'2012-11-01',3,now(),now()),
	(14,'zhangsanfeng','123456','张三丰',1,'14.jpg',2,'2002-08-01',2,now(),now()),
	(15,'yulianzhou','123456','俞莲舟',1,'15.jpg',2,'2011-05-01',2,now(),now()),
	(16,'songyuanqiao','123456','宋远桥',1,'16.jpg',2,'2007-01-01',2,now(),now()),
	(17,'chenyouliang','123456','陈友谅',1,'17.jpg',NULL,'2015-03-21',NULL,now(),now());

可以看到SQL语句里面的dept和emp的变量,就分别在pojo里的Dept and Emp里定理对应的私有型变量,命名规则为驼峰型,并添加上lombok注解省略简单方法。

配置application.properties文件:


#驱动类名称
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#数据库连接的url
spring.datasource.url=jdbc:mysql://localhost:3306/tlias
#连接数据库的用户名
spring.datasource.username=root
#连接数据库的密码
spring.datasource.password=1234
#配置mybatis的日志, 指定输出到控制台
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#开启mybatis的驼峰命名自动映射开关 a_column ------> aCloumn
mybatis.configuration.map-underscore-to-camel-case=true

使用Restful开发规范前端请求方式:

https://localhost:8080/users/1 (GET:查询id为1的用户;DELECT:删除id为1的用户)

https://localhost:8080/users (POST:新增/修改用户)

 

Result类:用作于统一的数据操作响应的返回类型,看代码就懂了:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result {
private Integer code;//响应码,1 代表成功; 0 代表失败
private String msg; //响应信息 描述字符串
private Object data; //返回的数据

//增删改 成功响应
public static Result success(){
return new Result(1,"success",null);
}
//查询 成功响应
public static Result success(Object data){
return new Result(1,"success",data);
}
//失败响应
public static Result error(String msg){
return new Result(0,msg,null);
}
}

添加查询系统

原始记录日志方式:private static Logger log= LoggerFactory.getLogger(DeptController.class);有了lombok可以直接在Controller类上使用Slf4j注解来自动创建log日志;

原始指定值和请求方法:@RequestMapping(value = “/dept”,method = RequestMethod.GET) //指定请求方式为GET;直接新的注解:@GetMapping(“/dept”) //直接使用Get/Post/…Mapping就可以省略method后面的。Java像是面向注解编程…

DeptController类:通过前端请求GET型的depts指令,调用Result类型的 list方法,创建一个DeptServicelmpl类的list()方法的集合用于输出,并将结果返回给前端。

@Autowired
private DeptServicelmpl deptService;

@GetMapping("/depts")   /**直接使用Get/Post/...Mapping就可以省略method后面的*/
    public Result list(){
        log.info("查询全部部门数据");

        List<Dept> deptList=deptService.list();
        return Result.success(deptList);
    }

DeptService接口里面:定义了一个Dept类的集合的方法。

List<Dept> list();

DeptServicelmpl接口类:重新list()方法,里面返回DepMapper类的list()方法的结果。

@Service
public class DeptServicelmpl implements DeptService {

@Autowired
private DeptMapper deptMapper;
@Override
public List<Dept> list() {
return deptMapper.list();
}
}

DeptMapper接口:list()方法为调用SQL的select查询语句。

@Mapper
public interface DeptMapper {
@Select("select *from dept")
List<Dept> list();
}

总的来说就是要熟悉三层架构,层层套娃,Controller类调用Service类,Service类再调用Mapper类的方法,然后该方法又返回给Service,再返回给Controller,最后返回给前端。用postman可以输入https://localhost:8080/depts测试下响应。

前后端联调

首先下载该项目的前端文件:https://pan.baidu.com/s/1w0b-MJ33WhzNEwXNgB9EKw?pwd=1234,提取码:1234

将zip解压到一个全英文路径的文件夹,并打开里面的exe文件,打开任务管理器如果有这个程序在后台说明就运行成功了,该程序会自动占用一个90端口。打开浏览器输入localhost:90,点击部门管理,如果有结果说明就成功了!可以打开F12查看网络,是通过Tomcat将90端口转换为8080端口的。

删除部门系统

删除方法就需要前端请求时附上一个id了,且返回给前端的数据不需要日志(date),所有就用Result返回类中的success无参方法了。

一样的,Controller层:这里的@PathVariable注解是用于传递上面的{id}的

@DeleteMapping("/depts/{id}")
public Result delete(@PathVariable Integer id){
log.info("根据id删除部门:{}",id);
deptService.delect(id);
return Result.success();
}

DeptService接口:定义一个有参的方法(id)

void delect(Integer id);

DeptServicelmpl类:

@Override
public void delect(Integer id){
deptMapper.delectById(id);
}

DeptMapper类:

@Delete("delete from dept where id=#{id}")
void delectById(Integer id);

总之就是套娃…..会了一个其他的几乎也就全会。请求方式是DELECT了注意哦~

新增部门

请求参数就一个部门名字,因为id是自动生成,create_time和update_time也是根据创建时间生成。请求类型为POST。

Controller:

@PostMapping("/depts")
public Result add(@RequestBody Dept dept){
log.info("添加部门:{}",dept);
deptService.add(dept);
return Result.success();
}

Service:(接口省了)

@Override
public void add(Dept dept) {
dept.setCreateTime(LocalDateTime.now());
dept.setUpdateTime(LocalDateTime.now());
deptMapper.insert(dept);
}

Mapper:

@Insert("INSERT INTO dept (name, create_time, update_time) value (#{name},#{createTime},#{updateTime})")
void insert(Dept dept);

postman我这样编辑:

分页查询功能

由于起始索引有变化((页码-1)*每页展示记录数 ),所以需要前端传递一个页码数,另外前端还需要传递‘每页展示记录数’的参数。

先在pojo里创建个PageBean类用于定义参数,就跟之前的Dept一样,需要添加上@Date等注解。定义的变量:

private Long total;//总记录数
private List rows;//数据列表

先在Controller类定义@GetMapping的方法,因为要传递参数所以就要用有参的嘛,参数就这么定义:@RequestParam注解替代了原始的if语句,直接添加默认值。

@RequestParam(defaultValue = "1") Integer page,@RequestParam(defaultValue = "10") Integer pageSize

EmpController类:

@GetMapping("/emps")
public Result page(@RequestParam(defaultValue = "1") Integer page,
                   @RequestParam(defaultValue = "10") Integer pageSize){
log.info("分页查询,参数:{},{}",page,pageSize);
PageBean pageBean=empService.page(page,pageSize);
return Result.success(pageBean);
}

EmpServiceImpl接口类:

@Override
public PageBean page(Integer page, Integer pageSize) {
Long count=empMapper.count();
Integer start=(page-1)*pageSize;
List<Emp> empList=empMapper.page(start,pageSize);
//封装PageBean对象
PageBean pageBean=new PageBean(count,empList);
return pageBean;
}

EmpMapper接口:一个是查询页码

@Select("Select count(*) from emp")
public Long count();

一个是查询当前页的数据

@Select("SELECT *from emp limit #{start},#{pagesize}")
public List<Emp> page(Integer start,Integer pagesize);

PageHelper分页插件:

目的就是简化Mapper接口和Service层的代码。下载:Maven Repository: com.github.pagehelper » pagehelper-spring-boot-starter » 1.4.6 (mvnrepository.com)

Mapper就只写:不用什么limit还要写两个查询

@Select("SELECT *from emp")
public List<Emp> list();

EmpServiceImpl接口类:

@Override
public PageBean page(Integer page, Integer pageSize) {
PageHelper.startPage(page,pageSize);
List<Emp> empList=empMapper.list();
Page<Emp> p=(Page<Emp>)empList;
//封装PageBean对象
PageBean pageBean=new PageBean(p.getTotal(),p.getResult());
return pageBean;
}

其他的类都一样。

条件分页查询

查询条件:模糊查询的名字,精确查询的性别,between中间查询的入职日期:eg.

select *
from emp
where name like concat('%', '张', '%')
and gender = 1
and entrydate between '2000-01-01' and '2010-01-01'
order by update_time desc

EmpController类里面查询方法再添加4个变量:String name,Short gender,@DateTimeFormat(pattern = “yyyy-MM-dd”) LocalDate begin,@DateTimeFormat(pattern = “yyyy-MM-dd”) LocalDate end,其他地方的看IDEA提示修改就行。Service里也要添加这四个变量。

EmpServiceImpl接口类里面要注意的是list()里面只需要这新增的四个变量,因为MySQL查询语句里面用不到page和pageSize这两个变量。Mapper接口:public List<Emp> list(String name, Short gender, LocalDate begin, LocalDate end);可以看出是使用了XML映射文件才没写@Selcet,XML文件里面的SQL查询语句(位置就在resources里面的top/hepingan/mapper):

<mapper namespace="top.hepingan.mapper.EmpMapper">
<select id="list" resultType="top.hepingan.pojo.Emp">
select *
from emp
<where>
<if test="name!=null">
name like concat('%', #{name}, '%')
</if>
<if test="gender!=null">
and gender = #{gender}
</if>
<if test="begin!=null and end!=null">
and entrydate between #{begin} and #{end}
</if>
</where>
order by update_time desc 
</select>
</mapper>

查询语句:http://localhost:8080/emps?page=1&pagesize=10&name=张&gender=1&begin=2000-01-01&end=2010-01-01

删除操作

前端请求参数:/emp/{ids},请求方式:DELECT

创建@DeleteMapping(“emps/{ids}”)注解的方法delete(@PathVariable List<Integer> ids)。然后直接调用empService的delete(ids)方法,点击报错的直接在Service里生成代码,接口类里面的重写就一行empMapper.delete(ids);然后再点报错的直接在Mapper里创建好代码,最后再在XML文件编写删除的代码:

<delete id="delete">
delete
from emp
where id in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete>

嗯学会了一种方法其他的都简单。

新增员工操作

前端请求方式post,json格式输入,要求有image,username,name,gender,job,entrydate,deptId。

数据比较多,之前创建的Emp就派上用场了,由于是json格式,所以就需要添加@RequestBody注解,调用Service的方法,创建Service方法,接口类定义基础的create_time and update_time,调用Mapper的方法,这里的Mapper里的添加方法就不用XML映射了,直接:

@Insert("INSERT INTO emp(username, name, gender, image, job, entrydate, dept_id, create_time, update_time)" +
"value (#{username},#{name},#{gender},#{image},#{job},#{entrydate},#{deptId},#{createTime},#{updateTime})")
void insert(Emp emp);

上传文件

上传到本地存储

在resources/static里面创建upload.html文件,里面编写:前端文件不用管。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上传文件</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
姓名: <input type="text" name="username"><br>
年龄: <input type="text" name="age"><br>
头像: <input type="file" name="image"><br>
<input type="submit" value="提交">
</form>

</body>
</html>

再在Controller里面创建一个UploadController类,里面编写:

@Slf4j
@RestController
public class UploadController {
@PostMapping("/upload")
public Result upload(String name, Integer age, MultipartFile image){
log.info("上传文件:{},{},{}",name,age,image);
return Result.success();
}
}

MultipartFile 函数就上传文件的格式。这里定义的变量名要和前端给的名字一样。

posted @   何平安  阅读(111)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
浏览器标题切换end
点击右上角即可分享
微信分享提示