根据:springMVC工作原理

一、 添加所有员工信息

  1. 显示添加页面
  2. URL:Add
  3. 请求方式:GET
  4. jsp页面
  5. 添加请求方式:POST
  6. 显示效果:完成添加,重定向到 list 页

二、展示所有员工信息

  • URI:List
  • 请求方式:GET
  • 显示效果

三、删除单个员工信息

  • URL:emp/{id}
  • 请求方式:DELETE
  • 删除后效果:对应记录从数据表中删除

四、更改单个员工信息

  1. 显示修改页面
    • URI:emp/{id}
    • 请求方式:GET
    • 显示效果:回显表单。
  2. 修改员工信息
    • URI:emp
    • 请求方式:PUT
    • 显示效果:完成修改,重定向到 list 页面。
    为了方便数据的操作管理定义了两个类存储数据
  • (Employee类和Department类)

具体介绍:

  1. 实体类:
  • Student、Department
  • Handler
  • StudentDao、DepartmentDao
  1. 相关的页面
  • list.jsp
  • input.jsp

准备工作

  1. 导入对应的jar包
    classmate-0.8.0.jar
    com.springsource.net.sf.cglib-2.2.0.jar
    com.springsource.org.aopalliance-1.0.0.jar
    com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
    commons-fileupload-1.2.1.jar
    commons-io-2.0.jar
    commons-logging-1.1.3.jar
    hibernate-validator-5.0.0.CR2.jar
    hibernate-validator-annotation-processor-5.0.0.CR2.jar
    jackson-annotations-2.1.5.jar
    jackson-core-2.1.5.jar
    jackson-databind-2.1.5.jar
    jboss-logging-3.1.1.GA.jar
    jstl.jar
    spring-aop-4.0.0.RELEASE.jar
    spring-aspects-4.0.0.RELEASE.jar
    spring-beans-4.0.0.RELEASE.jar
    spring-context-4.0.0.RELEASE.jar
    spring-core-4.0.0.RELEASE.jar
    spring-expression-4.0.0.RELEASE.jar
    spring-jdbc-4.0.0.RELEASE.jar
    spring-orm-4.0.0.RELEASE.jar
    spring-tx-4.0.0.RELEASE.jar
    spring-web-4.0.0.RELEASE.jar
    spring-webmvc-4.0.0.RELEASE.jar
    standard.jar
    validation-api-1.1.0.CR1.jar
  2. 配置对应的web,xml,springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"id="WebApp_ID" version="2.5"><!-- 配置 SpringMVC 的 DispatcherServlet --><!-- The front controller of this Spring Web application, responsible for handling all application requests --><servlet><servlet-name>springDispatcherServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:springmvc.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><!-- Map all requests to the DispatcherServlet for handling --><servlet-mapping><servlet-name>springDispatcherServlet</servlet-name><url-pattern>/</url-pattern></servlet-mapping><!-- 配置 HiddenHttpMethodFilter: 把 POST 请求转为 DELETE、PUT 请求 --><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></web-app>

springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"><!-- 配置自动扫描的包 --><context:component-scanbase-package="com.atguigu.springmvc,com.qst.hello,com.qst.Obj,com.qst.ObjDao"></context:component-scan><!-- 配置视图解析器 --><beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/views/"></property><property name="suffix" value=".jsp"></property></bean><mvc:default-servlet-handler /><mvc:annotation-driven></mvc:annotation-driven></beans>

default-servlet-handler 将在 SpringMVC 上下文中定义一个 DefaultServletHttpRequestHandler,

  • 它会对进入 DispatcherServlet 的请求进行筛查, 如果发现是没有经过映射的请求, 就将该请求交由 WEB 应用服务器默认的 Servlet 处理.
  • 如果不是静态资源的请求,才由 DispatcherServlet 继续处理
  • 一般 WEB 应用服务器默认的 Servlet 的名称都是 default.
    若所使用的 WEB 服务器的默认 Servlet 名称不是 default,则需要通过 default-servlet-name 属性显式指定
  1. 实体类
    4.1 Student类
package com.qst.Obj;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;public class Student {private Integer id;private String name;private String email;private Integer gender;private String address;@Autowiredprivate Department department;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 String getAddress() {return address;}public void setAddress(String address) {this.address = address;}public Department getDepartment() {return department;}public void setDepartment(Department department) {this.department = department;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic String toString() {return "Student [id=" + id + ", name=" + name + ", email=" + email + ", address=" + address + ", department="+ department + "]";}public Student(Integer id, String name, String email, Integer gender, String address, Department department) {super();this.id = id;this.name = name;this.email = email;this.gender = gender;this.address = address;this.department = department;}public Student() {// TODO Auto-generated constructor stub}}

Department类

package com.qst.Obj;public class Department {private Integer id;private String departmentName;public Department() {// TODO Auto-generated constructor stub}public Department(Integer i, String string) {this.id = i;this.departmentName = string;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getDepartmentName() {return departmentName;}public void setDepartmentName(String departmentName) {this.departmentName = departmentName;}@Overridepublic String toString() {return "Department [id=" + id + "]";}}

4.2 Dao层StudentDao类

package com.qst.ObjDao;import java.util.Collection;
import java.util.HashMap;
import java.util.Map;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;import com.qst.Obj.Department;
import com.qst.Obj.Student;@Repository
public class StudentDao {@Autowiredprivate DepartmentDao departmentDao;public static Map<Integer, Student> students = null;static {students = new HashMap<Integer, Student>();students.put(1, new Student(1, "zs", "java@163.com", 0, "北京", new Department(101, "java开发")));students.put(2, new Student(2, "ls", "java@163.com", 1, "台湾", new Department(102, "php开发")));students.put(3, new Student(3, "ww", "java@163.com", 1, "天津", new Department(103, "C开发")));students.put(4, new Student(4, "zl", "java@163.com", 0, "武汉", new Department(104, "C#开发")));students.put(5, new Student(5, "wq", "java@163.com", 1, "湖北", new Department(105, "Go开发")));}public static Integer sid = 6;public void Save(Student student) {if (student.getId() == null) {student.setId(sid++);}student.setDepartment(departmentDao.get(student.getDepartment().getId()));students.put(student.getId(), student);}public Collection<Student> getStudents() {return students.values();}public Student get(Integer id) {return students.get(id);}public void remove(Integer id) {students.remove(id);}}

DepartmentDao类

package com.qst.ObjDao;import java.util.Collection;
import java.util.HashMap;
import java.util.Map;import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.ResponseBody;import com.qst.Obj.Department;@Repository
public class DepartmentDao {public static Map<Integer, Department> departments = null;static {departments = new HashMap<Integer,Department>();departments.put(101, new Department(101, "java开发"));departments.put(102, new Department(102, "php开发"));departments.put(103, new Department(103, "C开发"));departments.put(104, new Department(104, "C#开发"));departments.put(105, new Department(105, "Go开发"));}public Collection<Department> getAll(){return departments.values();}public Department get(Integer id) {return departments.get(id);}
}

4.3 headler类

package com.qst.ObjDao;import java.io.UnsupportedEncodingException;
import java.util.Map;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;import com.qst.Obj.Student;@Controller
public class Headler {private static String URL = "success";@Autowiredprivate StudentDao studentDao;@Autowiredprivate DepartmentDao departmentDao;@ModelAttributepublic void getStudent(@RequestParam(value = "id", required = false) Integer id, Map<String, Object> map) {if (id != null) {map.put("student", studentDao.get(id));}}//更新操作@RequestMapping(value = "/emp", method = RequestMethod.PUT, produces = "application/json; charset=utf-8")public String Update(Student student) {System.out.println(student.getAddress());studentDao.Save(student);return "redirect:/List";}// 删除操作@RequestMapping(value = "/emp/{id}", method = RequestMethod.DELETE)public String delete(@PathVariable("id") Integer id) {System.out.println("delete");studentDao.remove(id);System.out.println("id:" + id + "student.id");return "redirect:/List";}// 查询操作@RequestMapping(value = "/emp", method = RequestMethod.POST)public String save(Student student) {studentDao.Save(student);return "redirect:/List";}// 根据编号查询@RequestMapping(value = "/emp/{id}", method = RequestMethod.GET)public String input(@PathVariable("id") Integer id, Map<String, Object> map) {map.put("student", studentDao.get(id));System.out.println("id:" + id);map.put("departments", departmentDao.getAll());return "input";}@RequestMapping("/List")public String show(Map<String, Object> map) {map.put("student", studentDao.getStudents());return "list";}// 添加操作@RequestMapping(value = "/Add", method = RequestMethod.GET)public String Input(Map<String, Object> map) {map.put("departments", departmentDao.getAll());System.out.println("save" + departmentDao.getAll());map.put("student", new Student());return "input";}}
  1. 流程展示

使用SpringMVC多个表单组件标签目的

  1. form 标签

一般情况下,通过 GET 请求获取表单页面,而通过POST 请求提交表单页面,因此获取表单页面和提交表单 页面的 URL
是相同的。只要满足该最佳条件的契约,<form:form > 标签就无需通过 action 属性指定表单提交的 URL

可以通过 modelAttribute 属性指定绑定的模型属性,若没有指定该属性,则默认从 request 域对象中读取command
的表单bean,如果该属性值也不存在,则会 发生错误

  1. 表单标签

SpringMVC 提供了多个表单组件标签,如 < form:input/>、
< form:select/>
等,用以绑定表单字段的属性值,它们的共有属性如下:
– path:表单字段,对应 html 元素的 name 属性,支持级联属性
–htmlEscape:是否对表单值的 HTML 特殊字符进行转换,默认值 为 true
– cssClass:表单组件对应的 CSS
样式类名
– cssErrorClass:表单组件的数据存在错误时,采取的 CSS 样式

form:input、form:password、form:hidden、form:textarea :对应 HTML 表单的
text、password、hidden、textarea 标签 • form:radiobutton:单选框组件标签,当表单 bean
对应的 属性值和 value 值相等时,单选框被选中 • form:radiobuttons:单选框组标签,用于构造多个单选 框–
items:可以是一个 List、String[] 或 Map – itemValue:指定 radio 的 value 值。可以是集合中
bean 的一个 属性值 – itemLabel:指定 radio 的 label 值 – delimiter:多个单选框可以通过
delimiter 指定分隔符
form:checkbox:复选框组件。用于构造单个复选框 • form:checkboxs:用于构造多个复选框。使用方式同
form:radiobuttons 标签
• form:select:用于构造下拉框组件。使用方式同
form:radiobuttons 标签
• form:option:下拉框选项组件标签。使用方式同
form:radiobuttons 标签
• form:errors:显示表单组件或数据校验所对应的错误 – <form:errors path= “ ” /> :显示表单所有的错误
– <form:errors path= “ user
” /> :显示所有以 user 为前缀的属性对应
的错误
– <form:errors path= “ username” /> :显示特定表单对象属性的错误

  1. 注意:
    可以通过 modelAttribute 属性指定绑定的模型属性,若没有指定该属性,则默认从 request 域对象中读取 command 的表单 bean如果该属性值也不存在,则会发生错误。

SpringMVC 处理静态资源:

  1. 为什么会有这样的问题:
    优雅的 REST 风格的资源URL 不希望带 .html 或 .do 等后缀 若将 DispatcherServlet 请求映射配置为 /, 则 Spring MVC 将捕获 WEB 容器的所有请求, 包括静态资源的请求, SpringMVC 会将他们当成一个普通请求处理, 因找不到对应处理器将导致错误。
  2. 解决: 在 SpringMVC 的配置文件中配置 < mvc:default-servlet-handler/> 同时还要配置< mvc:annotation-driven ></mvc:annotation-driven> 为了使@RequestMapping 生效

结语:(送给每一个在努力前行的人)

以梦为马,不负韶华
流年笑掷,未来可期

SpringMVC实例之RESTful风格进行CRUD实例(学习笔记)相关推荐

  1. Restful风格的CRUD实现、Restful风格的Spring MVC实现

    推荐微信公众号:[矿洞程序员]文章由高端社区fameLink创始人陶德及其他社区大佬原创. 1.课程名称:Restful风格的Spring MVC实现 2.课程内容 对于整个现在求职来讲,包括工作来讲 ...

  2. SpringBoot(四) Web开发(2)Restful风格的CRUD操作

    1.创建工程 使用之前使用的Spring提供的向导,快速创建一个包含web模板的SpringBoot工程:springboot-web-restful: 1.1 pom.xml如下 <?xml ...

  3. springmvc+swagger构建Restful风格文档

    本次和大家分享的是java方面的springmvc来构建的webapi接口+swagger文档:上篇文章分享.net的webapi用swagger来构建文档,因为有朋友问了为啥.net有docpage ...

  4. restFul风格实现CRUD

    后端代码 // 删@DeleteMapping("/delete/{id}")@ResponseBodypublic String delete(@PathVariable(&qu ...

  5. Material Design风格神框架vuetify 学习笔记(七) 基础组件3 抽屉 卡片

    一. 导航抽屉 v-navigation-drawer v-navigation-drawer是用户用于导航应用程序的组件. 导航抽屉被预先配置为可以在有或没有 vue-router 的情况下使用. ...

  6. Material Design风格神框架vuetify 学习笔记(十二) 组件的基础

    一. 窗口 v-window v-window 被设计成可以轻松地循环浏览内容,它提供了一个简单的接口来创建真正的自定义实现. v-window组件提供了将内容从一个窗格过渡到另一个窗格的基础功能. ...

  7. Material Design风格神框架vuetify 学习笔记(八) 基础组件4 头像 扩展面板 消息条 评分...

    一. 头像 v-avatar v-avatar 组件通常用于显示循环用户个人资料图片. 此组件将允许您动态尺寸并添加响应图像.图标和文字的边框半径. <v-avatar color=" ...

  8. Material Design风格神框架vuetify 学习笔记(一)

    一. 安装vuetify 1. vue插件式安装 首先我们使用vue_cli创建一个新的vue项目, 进入项目, 然后: vue add vuetify 他会问一个git问题, 直接选y 他会问版本问 ...

  9. SpringMVC(三)Restful风格及实例、参数的转换

    个人博客网:https://wushaopei.github.io/    (你想要这里多有) 一.Restful风格 1.Restful风格的介绍 Restful 一种软件架构风格.设计风格,而不是 ...

最新文章

  1. java 限制文本框长度_java中限制文本框输入长度的显示(转载)
  2. python3 lambda表达式
  3. xbox360 功率测试软件,【外星人 Alpha ASM100-1580 游戏主机使用总结】性能|电压|功耗|跑分_摘要频道_什么值得买...
  4. easyui的一个bug记录
  5. scrt配置服务器免密登录
  6. 代码走查(Code Review)25条疑问
  7. 微信小程序注册教程-详细图文教程
  8. 使用爱思助手备份苹果手机数据的方法
  9. _GLIBCXX_USE_CXX11_ABI 定义不一致带来的宕机问题
  10. 简述固定资产的全生命周期管理流程
  11. 出现Head https://registry-1.docker.io/v2/library/node/manifests/14-alpine的解决方法
  12. 如何在Tanzu Cluster中使用vSphere with Tanzu内置容器注册表
  13. POJ 1265 Area
  14. chrome模拟手机浏览器方法
  15. 【应用实例】基于单片机的激光相位测距仪
  16. 已知ip地址求子网掩码
  17. 动态网页和静态网页的差异
  18. 收藏的一些幽默搞笑文章
  19. LeetCode之打印零与奇偶数golang与java实现
  20. 高考状元学习方法分享:学习三十六计

热门文章

  1. SunFMEA培训-PFMEA中常见的预防措施
  2. CISCO数据中心虚拟化之VDC技术和配置
  3. 逻辑漏洞原理与实践练习题
  4. 【API】调用微软语音服务
  5. 前后端联调的一般步骤和Nginx简单配置
  6. PCL教程-PCLPlotter图表可视化类
  7. javaweb基于SSM开发金院二手书流通拍卖平台
  8. MySQL-排序加去重sql语句
  9. BAT批文件进行配置IP地址
  10. MySQL HA(High Availability) 数据库高可用工具Orchestrator安装