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

根据: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.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">


   <!-- 配置自动扫描的包 -->
	<context:component-scan
		base-package="com.atguigu.springmvc,com.qst.hello,com.qst.Obj,com.qst.ObjDao"></context:component-scan>


   <!-- 配置视图解析器 -->
	<bean
		class="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;
	@Autowired
	private 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;
	}

	@Override
	public 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;
	}

	@Override
	public 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 {
    
    

	@Autowired
	private DepartmentDao departmentDao;
	
	
	public static Map<Integer, Student> students = null;
	static {
    
    
		students = new HashMap<Integer, Student>();
		students.put(1, new Student(1, "zs", "[email protected]", 0, "北京", new Department(101, "java开发")));
		students.put(2, new Student(2, "ls", "[email protected]", 1, "台湾", new Department(102, "php开发")));
		students.put(3, new Student(3, "ww", "[email protected]", 1, "天津", new Department(103, "C开发")));
		students.put(4, new Student(4, "zl", "[email protected]", 0, "武汉", new Department(104, "C#开发")));
		students.put(5, new Student(5, "wq", "[email protected]", 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";
	@Autowired
	private StudentDao studentDao;

	@Autowired
	private DepartmentDao departmentDao;

	@ModelAttribute
	public 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 生效

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

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

猜你喜欢

转载自blog.csdn.net/weixin_44763595/article/details/108171399