SpringMVC使用RESTful接口案例详解
作者:学习使我快乐T
一、准备工作
和传统 CRUD 一样,实现对员工信息的增删改查。
①搭建环境
添加相关依赖
web.xml
springmvc.xml
②准备实体类
public class Employee { private Integer id; private String lastName; private String email; //1 male, 0 female private Integer gender; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Integer getGender() { return gender; } public void setGender(Integer gender) { this.gender = gender; } public Employee(Integer id, String lastName, String email, Integer gender) { super(); this.id = id; this.lastName = lastName; this.email = email; this.gender = gender; } public Employee() { } }
③准备dao模拟数据
@Repository public class EmployeeDao { private static Map<Integer, Employee> employees = null; static { employees = new HashMap<Integer, Employee>(); employees.put(1001, new Employee(1001, "E-AA", "aa@163.com", 1)); employees.put(1002, new Employee(1002, "E-BB", "bb@163.com", 1)); employees.put(1003, new Employee(1003, "E-CC", "cc@163.com", 0)); employees.put(1004, new Employee(1004, "E-DD", "dd@163.com", 0)); employees.put(1005, new Employee(1005, "E-EE", "ee@163.com", 1)); } private static Integer initId = 1006; public void save(Employee employee) { if (employee.getId() == null) { employee.setId(initId++); } employees.put(employee.getId(), employee); } public Collection<Employee> getAll() { return employees.values(); } public Employee get(Integer id) { return employees.get(id); } public void delete(Integer id) { employees.remove(id); } }
二、功能清单
功能 URL地址 请求方式
访问首页√ / GET
查询全部数据√ / employee GET
删除√ / employee/2 DELETE
跳转到添加数据页面√ / toAdd GET
执行保存√ / employee POST
跳转到更新数据页面√ / employee/2 GET
执行更新√ / employee PUT
三、具体功能-访问首页
查询所有员工信息-->/employee-->get
跳转到添加页面-->/to/add-->get
新增员工信息-->/employee-->post
跳转到修改页面-->/employee/1-->get
修改员工信息-->/employee-->put
删除员工信息-->/employee--delete
配置默认的servlet处理静态资源
当前工程的web.xml配置的前端控制器DispatcherServlet的url-pattern是/
tomcat的web.xml配置的DefaultServlet的url-pattern也是/
此时,浏览器发送的请求会优先被DispatcherServlet进行处理,但是DispatcherServlet无法处理静态资源
若配置了<mvc:default-servlet-handler/>,此时浏览器发送的所有请求都会被DefaultServlet处理
若配置了<mvc:default-servlet-handler/>和<mvc:annotation-driven />
浏览器发送的请求会先被DispatcherServlet处理,无法处理再交给DefaultServlet处理
web.xml
<!--配置springMVC的编码过滤器--> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 配置SpringMVC的前端控制器,对浏览器发送的请求统一进行处理 --> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 通过初始化参数指定SpringMVC配置文件的位置和名称 --> <init-param> <!-- contextConfigLocation为固定值 --> <param-name>contextConfigLocation</param-name> <!-- 使用classpath:表示从类路径查找配置文件,例如maven工程中的 src/main/resources --> <param-value>classpath:springmvc.xml</param-value> </init-param> <!-- 作为框架的核心组件,在启动过程中有大量的初始化操作要做 而这些操作放在第一次请求时才执行会严重影响访问速度 因此需要通过此标签将启动控制DispatcherServlet的初始化时间提前到服务器启动时 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <!-- 设置springMVC的核心控制器所能处理的请求的请求路径 /所匹配的请求可以是/login或.html或.js或.css方式的请求路径 但是/不能匹配.jsp请求路径的请求 --> <url-pattern>/</url-pattern> </servlet-mapping> <filter> <filter-name>HiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>HiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
springmvc.xml
<!-- 自动扫描包 --> <context:component-scan base-package="com.atguigu"/> <!-- 配置Thymeleaf视图解析器 --> <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver"> <property name="order" value="1"/> <property name="characterEncoding" value="UTF-8"/> <property name="templateEngine"> <bean class="org.thymeleaf.spring5.SpringTemplateEngine"> <property name="templateResolver"> <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver"> <!-- 视图前缀 --> <property name="prefix" value="/WEB-INF/templates/"/> <!-- 视图后缀 --> <property name="suffix" value=".html"/> <property name="templateMode" value="HTML5"/> <property name="characterEncoding" value="UTF-8" /> </bean> </property> </bean> </property> </bean> <!-- 配置默认的servlet处理静态资源 当前工程的web.xml配置的前端控DispatcherServlet的url - pattern是/ tomcat的web.xml配置的DefaultServlet的url-pattern也是/ 此时,浏时器发送的请求会优先DispatcherServlet进行处理,但是DispatcherServlet无法处理静态资源 若配置了<mvc:default-servlet-handler />,此时浏览器发送的所有请求都会越DispatcherServlet处理 若配置了<mvc:default-servlet-handler />和<mvc:annotation-driven /> 浏览器发送的请求会先被DispatcherServlet.处理,无法处理在交给DefaultServlet处理 --> <!-- <mvc:default-servlet-handler></mvc:default-servlet-handler>--> <mvc:default-servlet-handler /> <mvc:annotation-driven /> <!-- path:设置处理的请求地址 view-name:设置请求地址所对应的视图名称 --> <mvc:view-controller path="/" view-name="index"></mvc:view-controller> <mvc:view-controller path="/to/add" view-name="employee_add"></mvc:view-controller>
employee_add.html
<form th:action="@{/employee}" method="post"> lastName:<input type="text" name="lastName"><br> email:<input type="text" name="email"><br> gender:<input type="radio" name="gender" value="1">male <input type="radio" name="gender" value="0">female<br> <input type="submit" value="add"><br> </form>
employee_list.html
<table border="1" cellpadding="0" cellspacing="0" style="text-align: center;" id="dataTable"> <tr> <th colspan="5">Employee Info</th> </tr> <tr> <th>id</th> <th>lastName</th> <th>email</th> <th>gender</th> <th>options(<a th:href="@{/to/add}" rel="external nofollow" >add</a>)</th> </tr> <tr th:each="employee : ${employeeList}"> <td th:text="${employee.id}"></td> <td th:text="${employee.lastName}"></td> <td th:text="${employee.email}"></td> <td th:text="${employee.gender}"></td> <td> <a class="deleteA" @click="deleteEmployee" th:href="@{'/employee/'+${employee.id}}" rel="external nofollow" rel="external nofollow" >delete</a> <a th:href="@{'/employee/'+${employee.id}}" rel="external nofollow" rel="external nofollow" >update</a> </td> </tr> </table> <!-- 作用:通过超链接控制表单的提交,将post请求转换为delete请求 --> <form id="delete_form" method="post"> <!-- HiddenHttpMethodFilter要求:必须传输_method请求参数,并且值为最终的请求方式 --> <input type="hidden" name="_method" value="delete"/> </form> <script type="text/javascript" th:src="@{/static/js/vue.js}"></script> <script type="text/javascript"> var vue = new Vue({ el: "#dataTable", methods: { //event表示当前事件 deleteEmployee: function (event) { //通过id获取表单标签 var delete_form = document.getElementById("delete_form"); //将触发事件的超链接的href属性为表单的action属性赋值 delete_form.action = event.target.href; //提交表单 delete_form.submit(); //阻止超链接的默认跳转行为 event.preventDefault(); } } }); </script>
employee_update.html
<form th:action="@{/employee}" method="post"> <input type="hidden" name="_method" value="put"> <input type="hidden" name="id" th:value="${employee.id}"> lastName:<input type="text" name="lastName" th:value="${employee.lastName}"> <br> email:<input type="text" name="email" th:value="${employee.email}"><br> <!-- th:field="${employee.gender}"可用于单选框或复选框的回显 </body> </html> 若单选框的value和employee.gender的值一致,则添加checked="checked"属性 --> gender:<input type="radio" name="gender" value="1" th:field="${employee.gender}">male <input type="radio" name="gender" value="0" th:field="${employee.gender}">female<br> <input type="submit" value="update"><br>
index.html
<h1>index.html</h1> <a th:href="@{/user}" rel="external nofollow" >查询所有的用户信息</a><br> <a th:href="@{/user/1}" rel="external nofollow" >查询用户id为1的信息</a><br> <form th:action="@{/user}" method="post"> <input type="submit" value="添加用户信息"> </form> <form th:action="@{/user}" method="post"> <input type="hidden" name="_method" value="put"> <input type="submit" value="修改用户信息"> </form> <form th:action="@{/user/5}" method="post"> <input type="hidden" name="_method" value="delete"> <input type="submit" value="删除用户信息"> </form> <hr> <a th:href="@{/employee}" rel="external nofollow" >查询所有的员工信息</a><br>
控制器方法
@Controller public class EmployeeController { @Autowired private EmployeeDao employeeDao; @RequestMapping(value = "/employee", method = RequestMethod.GET) public String getAllEmployee(Model model) { Collection<Employee> employeeList = employeeDao.getAll(); model.addAttribute("employeeList", employeeList); return "employee_list"; } @RequestMapping(value = "/employee", method = RequestMethod.POST) public String addEmployee(Employee employee) { employeeDao.save(employee); return "redirect:/employee"; } @RequestMapping(value = "/employee/{id}", method = RequestMethod.GET) public String toUpdate(@PathVariable("id") Integer id, Model model) { Employee employee = employeeDao.get(id); model.addAttribute("employee", employee); return "employee_update"; } @RequestMapping(value = "/employee", method = RequestMethod.PUT) public String updateEmployee(Employee employee) { employeeDao.save(employee); return "redirect:/employee"; } @RequestMapping(value = "/employee/{id}", method = RequestMethod.DELETE) public String deleteEmployee(@PathVariable("id") Integer id) { employeeDao.delete(id); return "redirect:/employee"; } }
到此这篇关于SpringMVC使用RESTful接口案例详解的文章就介绍到这了,更多相关SpringMVC RESTful内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!