SpringMVC-RESTRUL_CRUDmd

SpringMVC

RESTRUL_CRUD_需求

在这里插入图片描述

  • 向EmployeeHandle.java中写入一个方法

    • package com.atguigu.springmvc.crud.handlers;
      import java.util.Map;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.stereotype.Controller;
      import org.springframework.web.bind.annotation.RequestMapping;
      import org.springframework.web.bind.annotation.RequestMethod;
      import com.atguigu.springmvc.crud.dao.DepartmentDao;
      import com.atguigu.springmvc.crud.dao.EmployeeDao;
      import com.atguigu.springmvc.crud.entities.Department;
      import com.atguigu.springmvc.crud.entities.Employee;
      
      @Controller
      public class EmployeeHandle {
      	@Autowired
      	private EmployeeDao employeeDao;
      	@Autowired  //注意这个AutoWired必须要加 否则就会报错
      	private DepartmentDao departmentDao;
      		
      	@RequestMapping("/emps")
      	public String list(Map<String,Object> map) {
      		map.put("employees", employeeDao.getAll());
      		return "list";
      	}
      }
      
  • 配置springmvc.xml文件

    • <!-- 配置自动扫描的包 -->
      	<context:component-scan base-package="com.atguigu.springmvc"></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>
      
  • 在web.xml文件中加入如下配置

    • <!-- 配置 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>
      
  • index.jsp 进入页面

    <a href="emps">List All Employees</a>

  • list.jsp显示页面

    • <%@ page language="java" contentType="text/html; charset=UTF-8"
          pageEncoding="UTF-8"%>
      <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
      <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
      <html>
      <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>Insert title here</title>
      </head>
      <body>
      	<c:if test="${empty requestScope.employees }">
      		没有任何员工信息.
      	</c:if>
      	<c:if test="${!empty requestScope.employees }">
      		<table border="1" cellpadding="10" cellspacing="0">
      			<tr>
      				<th>ID</th>
      				<th>LastName</th>
      				<th>Email</th>
      				<th>Gender</th>
      				<th>Department</th>
      				<th>Edit</th>
      				<th>Delete</th>
      			</tr>
      			
      			<c:forEach items="${requestScope.employees }" var="emp">
      				<tr>
      					<td>${emp.id }</td>
      					<td>${emp.lastName }</td>
      					<td>${emp.email }</td>
      					<td>${emp.gender == 0 ? 'Female' : 'Male' }</td>
      					<td>${emp.department.departmentName }</td>
      					<td><a href="">Edit</a></td>
      					<td><a href="emp/${emp.id}">Delete</a></td>
      				</tr>
      			</c:forEach>
      		</table>
      	</c:if>
      	
      	<br><br>
      
      	<a href="emp">Add New Employee</a>
      
  • 最后检索出如上图所示页面

在这里插入图片描述

  • 向EmployeeHandle.java添加两个方法

    • @RequestMapping(value="/emp",method=RequestMethod.POST)
      	public String save(Employee employee) {
      		employeeDao.save(employee);
      		return "redirect:/emps";
      	}
      	//这是一个get请求
      	@RequestMapping(value="emp",method=RequestMethod.GET)
      	public String input(Map<String,Object> map) {
      		map.put("departments", departmentDao.getDepartments());
      		map.put("employee", new Employee());
      		return "input";
      	}
      
  • 添加input.jsp页面

    • <%@ page language="java" contentType="text/html; charset=UTF-8"
          pageEncoding="UTF-8"%>
      <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
      <%@page import="java.util.HashMap"%>
      <%@page import="java.util.Map"%>
      <!DOCTYPE html>
      <html>
      <head>
      <meta charset="UTF-8">
      <title>Insert title here</title>
      </head>
      <body>
      		<!--  
      		1. WHY 使用 form 标签呢 ?
      		可以更快速的开发出表单页面, 而且可以更方便的进行表单值的回显
      		2. 注意:
      		可以通过 modelAttribute 属性指定绑定的模型属性,
      		若没有指定该属性,则默认从 request 域对象中读取 command 的表单 bean
      		如果该属性值也不存在,则会发生错误。
      	-->
      		<form:form action="emp" method="POST" modelAttribute="employee">
      			<!-- path属性对应html表单标签的name属性值 -->
      			LastName:<form:input path="lastName"/>
      			<br>
      			Email: <form:input path="email"/>
      			<br>
      			<%
      				Map<String ,String> genders=new HashMap();
      				genders.put("1","Male");
      				genders.put("0", "Female");
      				request.setAttribute("genders", genders);
      
      			%>
      			Gender:
      			<br>
      			<form:radiobuttons path="gender" items="${genders}" delimiter="<br>"/>
      			<br>
      			Department: <form:select path="department.id" 
      			items="${departments }" itemLabel="departmentName" itemValue="id"></form:select>
      			<br>
      			<input type="submit" value="Submit"/>
      		</form:form>
      
      </body>
      </html>
      

在这里插入图片描述

  • 删除操作

    • 先向EmployeeHandle.java添加一个方法

      • 	@RequestMapping(value="/emp/{id}",method=RequestMethod.DELETE)
          	public String delete(@PathVariable("id") Integer id) {
          		employeeDao.delete(id);
          		return "redirect:/emps";
          	}
        
    • 再向list.jsp中添加如下代码

      • <!--  
        	SpringMVC 处理静态资源:
        	1. 为什么会有这样的问题:
        	优雅的 REST 风格的资源URL 不希望带 .html 或 .do 等后缀
        	若将 DispatcherServlet 请求映射配置为 /, 
        	则 Spring MVC 将捕获 WEB 容器的所有请求, 包括静态资源的请求, SpringMVC 会将他们当成一个普通请求处理, 
        	因找不到对应处理器将导致错误。
        	2. 解决: 在 SpringMVC 的配置文件中配置 <mvc:default-servlet-handler/>
        -->
        <script type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script>
        <script type="text/javascript">
        			$(function(){
        				$(".delete").click(function(){
        					var href = $(this).attr("href");
        					$("form").attr("action", href).submit();			
        					return false;
        				});
        			})
        </script>
        
        <form action="" method="POST">
        		<input type="hidden" name="_method" value="DELETE"/>
        </form>
        <td><a class="delete" href="emp/${emp.id}">Delete</a></td> <!--还有这里也要添加-->
        
    • 在springmvc.xml中加入如下代码

      • <!--  
        		default-servlet-handler 将在 SpringMVC 上下文中定义一个 DefaultServletHttpRequestHandler,
        		它会对进入 DispatcherServlet 的请求进行筛查, 如果发现是没有经过映射的请求, 就将该请求交由 WEB 应用服务器默认的 
        		Servlet 处理. 如果不是静态资源的请求,才由 DispatcherServlet 继续处理
        
        		一般 WEB 应用服务器默认的 Servlet 的名称都是 default.
        		若所使用的 WEB 服务器的默认 Servlet 名称不是 default,则需要通过 default-servlet-name 属性显式指定
        		
        	-->
        	<mvc:default-servlet-handler/>
        	<mvc:annotation-driven></mvc:annotation-driven>
        
        
  • 修改操作

    • 显示修改页面

      • EmployeeHandle.java添加一个方法

        • @RequestMapping(value="/emp/{id}",method=RequestMethod.GET)
          	public String input(@PathVariable("id") Integer id,Map<String,Object> map) {
          		map.put("employee",employeeDao.get(id));
          		map.put("departments",departmentDao.getDepartments());
          		return "input";
          	}
          
    • 修改员工信息

      • EmployeeHandle.java添加两个方法

        • @ModelAttribute
          	public void getEmployee(@RequestParam(value="id",required = false) Integer id,
          				Map<String,Object> map) {
          		if(id!=null) {
          			map.put("employee", employeeDao.get(id));
          		}
          		
          	}
          	@RequestMapping(value="/emp",method=RequestMethod.PUT)
          	public String update(Employee employee) {
          		employeeDao.save(employee);
          		
          		return "redirect:/emps";
          	}
          
    • 修改input.jsp中信息,增加了c:if

      • <!-- 这里的action变成绝对路径了  以后都建议使用绝对路径 -->
        		<form:form action="${pageContext.request.contextPath}/emp" method="POST" 				modelAttribute="employee">
        			<c:if test="${employee.id ==null }">
        				<!-- path属性对应html表单标签的name属性值 -->
        				LastName:<form:input path="lastName"/>
        			</c:if>
        			<c:if test="${employee.id !=null }">
        				<form:hidden path="id"/>
        				<input type="hidden" name="_method" value="PUT"/>
        					<%-- 对于 _method 不能使用 form:hidden 标签, 因为 modelAttribute 对应的 bean 中							没有 _method 这个属性 --%>
        					<%-- 
        					<form:hidden path="_method" value="PUT"/>
        					--%>
        			</c:if>
        			<br>
        			Email: <form:input path="email"/>
        			<br>
        			<%
        				Map<String ,String> genders=new HashMap();
        				genders.put("1","Male");
        				genders.put("0", "Female");
        				request.setAttribute("genders", genders);
        
        			%>
        			Gender:
        			<br>
        			<form:radiobuttons path="gender" items="${genders}" delimiter="<br>"/>
        			<br>
        			Department: <form:select path="department.id" 
        			items="${departments }" itemLabel="departmentName" itemValue="id"></form:select>
        			<br>
        			<input type="submit" value="Submit"/>
        		</form:form>
        
      • 修改list.jsp中的超链接

        <td><a href="emp/${emp.id}">Edit</a></td>

在这里插入图片描述

  • 相关的类

    • com.atguigu.springmvc.crud.dao

      • DepartmentDao.java

           package com.atguigu.springmvc.crud.dao;
        
        import java.util.Collection;
        import java.util.HashMap;
        import java.util.Map;
        
        import org.springframework.stereotype.Repository;
        
        import com.atguigu.springmvc.crud.entities.Department;
        
        @Repository
        public class DepartmentDao {
        
        	private static Map<Integer, Department> departments = null;
        	
        	static{
        		departments = new HashMap<Integer, Department>();
        		
        		departments.put(101, new Department(101, "D-AA"));
        		departments.put(102, new Department(102, "D-BB"));
        		departments.put(103, new Department(103, "D-CC"));
        		departments.put(104, new Department(104, "D-DD"));
        		departments.put(105, new Department(105, "D-EE"));
        	}
        	
        	public Collection<Department> getDepartments(){
        		return departments.values();
        	}
        	
        	public Department getDepartment(Integer id){
        		return departments.get(id);
        	}
        	
        }
        
      • EmployeeDao.java

        package com.atguigu.springmvc.crud.dao;
        
        import java.util.Collection;
        import java.util.HashMap;
        import java.util.Map;
        
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.stereotype.Repository;
        
        import com.atguigu.springmvc.crud.entities.Department;
        import com.atguigu.springmvc.crud.entities.Employee;
        
        @Repository
        public class EmployeeDao {
        
        	private static Map<Integer, Employee> employees = null;
        	
        	@Autowired
        	private DepartmentDao departmentDao;
        	
        	static{
        		employees = new HashMap<Integer, Employee>();
        
        		employees.put(1001, new Employee(1001, "E-AA", "aa@163.com", 1, new Department(101, "D-AA")));
        		employees.put(1002, new Employee(1002, "E-BB", "bb@163.com", 1, new Department(102, "D-BB")));
        		employees.put(1003, new Employee(1003, "E-CC", "cc@163.com", 0, new Department(103, "D-CC")));
        		employees.put(1004, new Employee(1004, "E-DD", "dd@163.com", 0, new Department(104, "D-DD")));
        		employees.put(1005, new Employee(1005, "E-EE", "ee@163.com", 1, new Department(105, "D-EE")));
        	}
        	
        	private static Integer initId = 1006;
        	
        	public void save(Employee employee){
        		if(employee.getId() == null){
        			employee.setId(initId++);
        		}
        		
        		employee.setDepartment(departmentDao.getDepartment(employee.getDepartment().getId()));
        		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);
        	}
        }
        
    • com.atguigu.springmvc.crud.entities

      • Department.java 里面有私有属性id departmentName 带参,不带参的构造器还有toString()方法

      • Employee.java 里面有私有属性id,lastName,email,gender,department 相关的构造器和toString()方法

使用Spring的表单标签

  • WHY 使用 form 标签呢 ?
    可以更快速的开发出表单页面, 而且可以更方便的进行表单值的回显

  • 在这里插入图片描述

  • 在这里插入图片描述

  • 在这里插入图片描述

  • 在这里插入图片描述

  • <!--  
    		1. WHY 使用 form 标签呢 ?
    		可以更快速的开发出表单页面, 而且可以更方便的进行表单值的回显
    		2. 注意:
    		可以通过 modelAttribute 属性指定绑定的模型属性,
    		若没有指定该属性,则默认从 request 域对象中读取 command 的表单 bean
    		如果该属性值也不存在,则会发生错误。
    	-->
    		<form:form action="emp" method="POST" modelAttribute="employee">
    			<!-- path属性对应html表单标签的name属性值 -->
    			LastName:<form:input path="lastName"/>
    			<br>
    			Email: <form:input path="email"/>
    			<br>
    			<%
    				Map<String ,String> genders=new HashMap();
    				genders.put("1","Male");
    				genders.put("0", "Female");
    				request.setAttribute("genders", genders);
    
    			%>
    			Gender:
    			<br>
    			<form:radiobuttons path="gender" items="${genders}" delimiter="<br>"/>
    			<br>
    			Department: <form:select path="department.id" 
    			items="${departments }" itemLabel="departmentName" itemValue="id"></form:select>
    			<br>
    			<input type="submit" value="Submit"/>
    		</form:form>
    

*在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
【优质项目推荐】 1、项目代码均经过严格本地测试,运行OK,确保功能稳定后才上传平台。可放心下载并立即投入使用,若遇到任何使用问题,随时欢迎私信反馈与沟通,博主会第一时间回复。 2、项目适用于计算机相关专业(如计科、信息安全、数据科学、人工智能、通信、物联网、自动化、电子信息等)的在校学生、专业教师,或企业员工,小白入门等都适用。 3、该项目不仅具有很高的学习借鉴价值,对于初学者来说,也是入门进阶的绝佳选择;当然也可以直接用于 毕设、课设、期末大作业或项目初期立项演示等。 3、开放创新:如果您有一定基础,且热爱探索钻研,可以在此代码基础上二次开发,进行修改、扩展,创造出属于自己的独特应用。 欢迎下载使用优质资源!欢迎借鉴使用,并欢迎学习交流,共同探索编程的无穷魅力! 基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip 基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip 基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值