SpringMVC学习(五)-RESTFUl_CRUD操作

本文介绍了一个基于SpringMVC的简单CRUD应用程序的实现细节,包括如何通过配置实现HTTP方法的转换,处理静态资源,以及如何利用DAO层进行数据访问。通过具体代码示例,展示了如何创建、读取、更新和删除Employee实体。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用SpringMVC静态模仿从数据提取数据完成CRUD操作

重点知识详解:

1.将post请求改为DELETE和PUT请求(将GET请求,通过JQUERY完成转化为DELETE请求)

2.使用配置文件将get请求转换为post请求

3.静态资源问题的处理

1.Employee.java封装类

package com.springmvc.crud.entiry;


public class Employee {


    private Integer id;
    private String lastname;
    private String email;
    //1 male 0 female
    private Integer gender;
    private Department department;

    public Employee() {
        super();
        // TODO Auto-generated constructor stub
    }



    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 Department getDepartment() {
        return department;
    }
    public void setDepartment(Department department) {
        this.department = department;
    }



    public Employee(Integer id,String lastname, String email, Integer gender, Department department) {
        super();
        this.id=id;
        this.lastname = lastname;
        this.email = email;
        this.gender = gender;
        this.department = department;
    }



}

2.Department.java封装类

package com.springmvc.crud.entiry;

public class Department {


    private Integer id;
    private String departmentName;


    public Department() {
        super();
        // TODO Auto-generated constructor stub
    }

    public Department(Integer id, String departmentName) {
        super();
        this.id = id;
        this.departmentName = departmentName;
    }

    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;
    }


}

3.EmployeeDao.java Dao层实现

package com.springmvc.crud.dao;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.springmvc.crud.entiry.Department;

@Repository
public class DepartmentDao {

    private static Map<Integer, Department> departments = null;

    static{
        departments = new HashMap<>();
        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> getDepartment() {

        return departments.values();
    }
    public Department getDepartment(Integer id){
        return departments.get(id);
    }

}

4.DepartmentDao.java Dao层实现

package com.springmvc.crud.dao;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.springmvc.crud.entiry.Department;

@Repository
public class DepartmentDao {

    private static Map<Integer, Department> departments = null;

    static{
        departments = new HashMap<>();
        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> getDepartment() {

        return departments.values();
    }
    public Department getDepartment(Integer id){
        return departments.get(id);
    }

}

5.EmployeeHandler.java实现类

package com.springmvc.crud.handler;

import java.util.Map;

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.springmvc.crud.dao.DepartmentDao;
import com.springmvc.crud.dao.EmployeeDao;
import com.springmvc.crud.entiry.Employee;

@Controller
public class EmployeeHandler {

    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
    private DepartmentDao departmentDao;

    @RequestMapping("/emps")
    public String list(Map<String,Object> map) {
        map.put("employees",employeeDao.getAll());
        return "list";
    }

    @RequestMapping(value="/emp",method=RequestMethod.GET)
    public String inputAdd(Map<String,Object> map) {
        map.put("departments", departmentDao.getDepartment());
        map.put("employee", new Employee());
        return "input";
    }

    @RequestMapping(value="/emp",method=RequestMethod.POST)
    public String add(Employee employee) {

        employeeDao.save(employee);
        return "redirect:/emps";
    }

    @RequestMapping(value="/emp/{id}",method=RequestMethod.DELETE)  
    public String delete(@PathVariable("id")Integer id){  
        employeeDao.delete(id);   
        return "redirect:/emps";  
    }

    @RequestMapping(value="/emp/{id}",method=RequestMethod.GET)
    public String inputEdit(@PathVariable("id") Integer id,Map<String,Object> map) {
        map.put("employee", employeeDao.get(id));
        map.put("departments", departmentDao.getDepartment());
        return "input";
    }


    @RequestMapping(value="/emp",method=RequestMethod.PUT)
    public String update(Employee employee) {
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    @ModelAttribute
    public void getEmployee(@RequestParam(value="id",required=false) Integer id,Map<String,Object> map) {
        if(id!=null) {
            map.put("employee", employeeDao.get(id));
        }
    }


}

6.web.xml配置

<?xml version="1.0" encoding="utf-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <!--  
        配置org.springframework.web.filter.HiddenHttpMethodFilter:
        把POST请求转为DELETE或POST请求
    -->
    <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>

    <!-- 配置DispatcherServlet -->
    <!-- 配置DispatcherServlet的作用是:如果在某个方法上配置了@RequestMapping("/helloworld"),
         当浏览器访问helloworld时,DispatcherServlet会将这个请求发送给@RequestMapping("/helloworld")
         所在的方法上,执行这个方法 -->
    <servlet>
        <servlet-name>SpringDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 配置DispatcherServlet的一个初始化参数:配置springMVC配置文件的位置和名称 -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
    <!--SpringDispatcherServlet在当前web应用被加载的时候被创建,而不是等第一次请求的时候被创建  -->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>  <!-- 可以应答所有请求 -->
    </servlet-mapping>

</web-app>

7.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:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
                           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
                           http://www.springframework.org/schema/context 
                           http://www.springframework.org/schema/context/spring-context-3.2.xsd
                           http://www.springframework.org/schema/mvc 
                           http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
    <!-- 配置自动扫描的包 -->
    <context:component-scan base-package="com.springmvc"></context:component-scan>

    <!-- 配置视图 BeanNameViewResolver解析器:使用视图的名字来解析视图
        order属性越低优先级越高
    -->
    <bean class="org.springframework.web.servlet.view.BeanNameViewResolver">  
        <property name="order" value="10" />  
    </bean>

    <!-- 配置视图解析器:如何把handler方法返回值解析为实际视图 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- 配置国际化资源文件 -->
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value="i18n"></property>
</bean>

<!--  -->
<mvc:default-servlet-handler/>
<mvc:annotation-driven></mvc:annotation-driven>
</beans>

8.index.jsp页面

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <a href="emps">listAllEmployees</a>

</body>
</html>

9.list.jsp页面

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ 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=ISO-8859-1">
<title>Insert title here</title>
<!-- SpringMVC处理静态-->
<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>  
</head>
<body>
 <form action="" method="post">  
  <input type="hidden" name="_method" value="DELETE">  
  </form>
    <h1>hello world</h1>

    <c:if test="${empty requestScope.employees }">
        <h1>no employee</h1>
    </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="emp/${emp.id}">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>

</body>
</html>

10.input.jsp页面

<%@page import="java.util.HashMap"%>
<%@page import="java.util.Map"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!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>
<form:form action="${pageContext.request.contextPath }/emp" method="POST" 
    modelAttribute="employee"/>
    <!-- path 属性对应html表单标签的name属性 -->
    <form:form action="springmvc/add" method="POST" modelAttribute="employee">  
    <c:if test="${employee.id==null }">  
        LastName:<form:input path="lastname"/> <br>  
    </c:if>  
    <c:if test="${employee.id!=null }">  
        <form:hidden path="id"/>  
        <%--对于_method不能使用form:hidden标签,因为modelAttribute对应的bean中没有_method这个属性 --%>
        <input type="hidden" name="_method" value="PUT">  
    </c:if> 
    Email:<form:input path="email"></form:input><br>
    <%
        Map<String, String> genders = new HashMap<String, String>();
        genders.put("1", "male");
        genders.put("0", "female");
        request.setAttribute("genders", genders);
    %>
    Gender:<form:radiobuttons path="gender" items="${genders }"/><br>
    Department:<form:select path="department" 
        items="${departments }" itemLabel="departmentName" itemValue="id"></form:select><br>
    <input type="submit" value="Submit"/>
 </form:form>

</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值