SpringBoot之REST风格的增删改查


讲讲什么是REST

官方解释 : REST是表述性状态转移(REpresentational State Transfer),是一种基于HTTP的结构原则 ,用于表示被操作的资源

人话 : 一种软件架构风格,用于前后端通信,能让你的业务逻辑更加清晰

GET方法通常用于获取某一资源或集合
POST方法用于创建
PUT方法用于更新
DELETE用于删除资源

在这里插入图片描述
详细状态码信息 : 传送门


提示:以下是本篇文章正文内容,下面案例可供参考

一、登录与拦截器

学的时候感觉又回到最初的起点
先给出项目结构
在这里插入图片描述

再给个页面
在这里插入图片描述

具体步骤可以分为两步,创建拦截器注册拦截器 (登录操作就不写了,但是我们需要在登录业务中注册session)

1.创建拦截器

(1). 创建一个普通的Java类 , 命名为LoginHandlerInterceptor 类名最好能体现出它是一个拦截器

(2). 实现HandlerInterceptor接口并实现所有接口方法

(3). 重写preHandle()方法 , 判断session是否为空.

	@Override
    public boolean preHandle(HttpServletRequest request,
     HttpServletResponse response, Object handler) throws Exception {
    
    
        Object user = request.getSession().getAttribute("loginUser");
        if(user == null){
    
    
            request.setAttribute("msg","请先登录");
            request.getRequestDispatcher("/index.html").
            forward(request,response);
            return false;
        }else {
    
    
            //放行
            return true;
        }
    }

2.注册拦截器

在我们自己配置的MVC配置类中注册

			@Override
            public void addInterceptors(InterceptorRegistry registry) {
    
    
                //super.addInterceptors(registry);
                registry.addInterceptor((new LoginHandlerInterceptor())).addPathPatterns("/main.html")
                        .excludePathPatterns("/","/user/login","login.html");
            }

问题 : 加入拦截器后静态资源被过滤???
解决 : 2.0+会对静态资源拦截,所以在自定义拦截器时,只对登陆后去到的页面(如这里的main.html)进行拦截即可

二、增 (添加员工)

1.REST风格架构

在这里插入图片描述

2.进入添加页面

在进入添加员工页面时 , 我们需要查询出某些信息,这里我查的是员工的部门信息

代码如下(示例):

	@GetMapping("/emp")
    public String toAddPage(Model model){
    
    
        Collection<Department> departments =
         departmentDao.getDepartments();
         
        model.addAttribute("depts",departments);
        return "emp/add"; //来到添加页面
    }

3.添加内容

	@PostMapping("/emp")
    public String add(Employee employee) {
    
    
        //添加完员工后来到员工列表页面
        if(employee != null){
    
    
            employeeDao.save(employee);
        }
        //重定向到emps请求 (进入员工列表并 查出所有员工信息)
        return "redirect:/emps";
    }

三、删 (删除员工)

到现在还是没弄明白这种写法… 还得学学JS呀

spring boot 2.0以后需要在配置类中加入spring.mvc.hiddenmethod.filter.enabled = true , 否则会报405错误

前端表单和JS

<td>
	<a class="btn btn-sm btn-primary" th:href="@{/emp/}+${emp.id}">编辑</a>
	<button th:attr="del_uri=@{/emp/}+${emp.id}" class="btn btn-sm btn-warning deleteBtn">删除</button>
</td>
<form id="deleteEmpForm" method="post">
	<!--restful的删除-->
	<input type="hidden" name="_method" value="delete"/>
</form>
<script>
	$(".deleteBtn").click(function(){
    
    
	//删除当前员工的
	$("#deleteEmpForm").attr("action",$(this).attr("del_uri")).submit();
		return false;
	});
</script>
	//删除
    @DeleteMapping("/emp/{id}")
    public  String delete(@PathVariable("id")Integer id){
    
    
        employeeDao.delete(id);
        return "redirect:/emps"; //重定向到列表
    }

四、改 (修改员工信息)

这个最麻烦,我们需要和前面的添加员工共用一个页面,所以顺道把添加员工的页面也给出

在前端页面有一个判空操作 如果emp对象为空,表示添加员工操作,反之为修改,需要查出该对象的内容 , 且需要将修改时的请求方式指定为PUT

<!--添加内容使用post请求-->
	<form th:action="@{/emp}" method="post">
	<!--指定提交方式(放在表单里)-->
	<input type="hidden" th:if="${emp!=null}" name="_method" value="put">
	<input type="hidden" name="id" th:if="${emp!=null}" th:value="${emp.id}">
<div class="form-group">
	<label>LastName</label>
	<input type="text" name="lastName" class="form-control" placeholder="zhangsan" th:value="${emp!=null}?${emp.lastName}">
</div>
<div class="form-group">
	<label>Email</label>
	<input type="email" name="email" class="form-control" placeholder="[email protected]" th:value="${emp!=null}?${emp.email}">
</div>
<div class="form-group">
	<label>Gender</label><br/>
	<div class="form-check form-check-inline">
	<input class="form-check-input" type="radio" name="gender" value="1" th:checked="${emp!=null}?${emp.gender == 1}">
	<label class="form-check-label"></label>
</div>
<div class="form-check form-check-inline">
	<input class="form-check-input" type="radio" name="gender" value="0" th:checked="${emp!=null}?${emp.gender == 0}">
	<label class="form-check-label"></label>
</div>
</div>
<div class="form-group">
	<label>department</label>
	<select class="form-control" name="department.id">
		<option th:selected="${emp!=null}?${dept.id == emp.department.id}" th:value="${dept.id}" th:each="dept:${depts}" th:text="${dept.departmentName}">1</option>
	</select>
</div>
<div class="form-group">
	<label>Birth</label>
	<input type="text" name="birth" class="form-control" placeholder="2016-01-01" th:href="${emp!=null}?${#dates.format(emp.birth,'yyyy-MM-dd')}" >
</div>
	<button type="submit" class="btn btn-primary" th:text="${emp!=null}?'修改':'提交'"></button>
</form>
	//修改
    @PutMapping("emp")
    public String updateById(Employee employee){
    
    
        System.out.println(employee);
        employeeDao.save(employee);
        return "redirect:/emps";
    }

五、查 (查询所有员工)

这个最简单… …

	@GetMapping("/emps")
    public String list(Model model){
    
    
        Collection<Employee> list = employeeDao.getAll();
        model.addAttribute("emps",list);
        return "emp/list";
    }

配置类

配置类需要先继承WebMvcConfigurerAdapter

@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
    
    
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
    
    
        registry.addViewController("/cust").setViewName("success");
    }
    
    @Bean
    public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){
    
    
        WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter(){
    
    
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
    
    
                registry.addViewController("/").setViewName("login"); //发出的所有请求都会给到index页面
                registry.addViewController("/index.html").setViewName("login"); //发出的所有请求都会给到index页面
                registry.addViewController("/main.html").setViewName("dashboard");
            }

            @Override
            public void addInterceptors(InterceptorRegistry registry) {
    
    
                //super.addInterceptors(registry);
                // 2.0+会对静态资源拦截,所以在自定义拦截器时,只对登陆后去到的主页(如这里的main.html)进行拦截即可
                registry.addInterceptor((new LoginHandlerInterceptor())).addPathPatterns("/main.html")
                        .excludePathPatterns("/","/user/login","login.html");
            }
        };
        return adapter;
    }
}

1.添加视图解析器 : addViewControllers 举例 ,地址栏上的所有/index.html请求都会被转送到login.html页面
2.添加拦截器 : 注意2.0+会对静态资源拦截,所以在自定义拦截器时,只对登陆后去到的主页(如这里的main.html)进行拦截即可

猜你喜欢

转载自blog.csdn.net/qq_45596525/article/details/109144933