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="zhangsan@atguigu.com" 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)进行拦截即可

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Boot和Vue.js可以很好地搭配使用,实现前后端分离的Web应用程序。以下是一个简单的例子,演示如何使用Spring Boot和Vue.js实现增删改查功能。 1. 创建一个Spring Boot项目,包含Spring WebSpring Data JPA依赖。创建一个实体类和一个Repository接口,用于操作数据库。 ```java @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String email; // 省略getter和setter } @Repository public interface UserRepository extends JpaRepository<User, Long> { } ``` 2. 创建一个RESTful API,使用Spring MVC和Spring Data REST实现,用于获取、创建、更新和删除用户。 ```java @RestController @RequestMapping("/api/users") public class UserController { @Autowired private UserRepository userRepository; @GetMapping public List<User> findAll() { return userRepository.findAll(); } @PostMapping public User create(@RequestBody User user) { return userRepository.save(user); } @PutMapping("/{id}") public User update(@PathVariable Long id, @RequestBody User user) { user.setId(id); return userRepository.save(user); } @DeleteMapping("/{id}") public void delete(@PathVariable Long id) { userRepository.deleteById(id); } } ``` 3. 创建一个Vue.js应用程序,使用axios库与后端进行通信。创建一个组件,用于显示用户列表,以及一个表单组件,用于创建或更新用户。 ```html <template> <div> <table> <tr> <th>ID</th> <th>Name</th> <th>Email</th> <th>Actions</th> </tr> <tr v-for="user in users" :key="user.id"> <td>{{ user.id }}</td> <td>{{ user.name }}</td> <td>{{ user.email }}</td> <td> <button @click="edit(user)">Edit</button> <button @click="remove(user)">Remove</button> </td> </tr> </table> <form v-if="editing" @submit.prevent="save"> <input type="text" v-model="user.name" placeholder="Name"> <input type="email" v-model="user.email" placeholder="Email"> <button type="submit">{{ editing.id ? 'Update' : 'Create' }}</button> </form> </div> </template> <script> import axios from 'axios'; export default { data() { return { users: [], user: {}, editing: false, }; }, methods: { async fetchUsers() { const { data } = await axios.get('/api/users'); this.users = data; }, async save() { if (this.editing.id) { await axios.put(`/api/users/${this.editing.id}`, this.user); } else { await axios.post('/api/users', this.user); } this.editing = false; this.user = {}; await this.fetchUsers(); }, async remove(user) { await axios.delete(`/api/users/${user.id}`); await this.fetchUsers(); }, edit(user) { this.editing = true; this.user = { ...user }; }, }, async mounted() { await this.fetchUsers(); }, }; </script> ``` 4. 在Spring Boot应用程序中配置静态资源路径,将Vue.js应用程序打包为静态资源,并在Spring Boot应用程序中提供静态资源服务。 ```properties spring.mvc.static-path-pattern=/static/** spring.resources.static-locations=classpath:/static/ ``` 5. 打包Vue.js应用程序,并将生成的dist目录复制到Spring Boot应用程序的静态资源目录中。 6. 运行Spring Boot应用程序,访问http://localhost:8080/static/index.html即可看到用户列表和表单。现在可以使用Vue.js应用程序与后端进行交互,实现增删改查功能了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值