zoukankan      html  css  js  c++  java
  • springmvc学习第三天

    利用spring mvc 实现crud

    1.导入jar包

    commons-logging-1.2.jar
    jstl.jar
    spring-aop-4.1.6.RELEASE.jar
    spring-beans-4.1.6.RELEASE.jar
    spring-context-4.1.6.RELEASE.jar
    spring-core-4.1.6.RELEASE.jar
    spring-expression-4.1.6.RELEASE.jar
    spring-web-4.1.6.RELEASE.jar
    spring-webmvc-4.1.6.RELEASE.jar
    standard.jar

    2.配置web.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>

    3.配置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.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <!-- 配置自动扫描的包 -->
    <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>

    <!--

    为什么要使用default-servlet-handler(在jsp页面中使用jQuery,如果不设置,则会提示找不到资源文件)

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

    处理细节
    default-servlet-handler 将在 SpringMVC 上下文中定义一个 DefaultServletHttpRequestHandler,
    它会对进入 DispatcherServlet 的请求进行筛查, 如果发现是没有经过映射的请求, 就将该请求交由 WEB 应用服务器默认的
    Servlet 处理. 如果不是静态资源的请求,才由 DispatcherServlet 继续处理

    一般 WEB 应用服务器默认的 Servlet 的名称都是 default.
    若所使用的 WEB 服务器的默认 Servlet 名称不是 default,则需要通过 default-servlet-name 属性显式指定

    -->
    <mvc:default-servlet-handler/>

    <!--当配置了<mvc:default-servlet-handler/>,原先的正常的地址也会报404,配置这个就可以解决问题-->

    <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
    </beans>

    4、实体类

    Department类

    package com.atguigu.springmvc.crud.entities;

    public class Department {

    private Integer id;
    private String departmentName;

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

    public Department(int 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 + ", departmentName=" + departmentName
    + "]";
    }

    }

    Employee类

    package com.atguigu.springmvc.crud.entities;

    import java.util.Date;

    import javax.validation.constraints.Past;

    import org.hibernate.validator.constraints.Email;
    import org.hibernate.validator.constraints.NotEmpty;
    import org.springframework.format.annotation.DateTimeFormat;
    import org.springframework.format.annotation.NumberFormat;

    public class Employee {

    private Integer id;
    @NotEmpty
    private String lastName;

    @Email
    private String email;
    //1 male, 0 female
    private Integer gender;

    private Department department;

    @Past
    @DateTimeFormat(pattern="yyyy-MM-dd")
    private Date birth;

    @NumberFormat(pattern="#,###,###.#")
    private Float salary;

    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 Date getBirth() {
    return birth;
    }

    public void setBirth(Date birth) {
    this.birth = birth;
    }

    public Float getSalary() {
    return salary;
    }

    public void setSalary(Float salary) {
    this.salary = salary;
    }

    @Override
    public String toString() {
    return "Employee [id=" + id + ", lastName=" + lastName + ", email="
    + email + ", gender=" + gender + ", department=" + department
    + ", birth=" + birth + ", salary=" + salary + "]";
    }

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

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

    5、dao类

    DepartmentDao类

    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类

    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);//此处不可以写为employees.put(initId , 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);
    }
    }

    6、处理类

    EmployeeHandler 类

    package com.atguigu.springmvc.crud.handlers;

    import java.util.Map;

    import javax.validation.Valid;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.validation.Errors;
    import org.springframework.validation.FieldError;
    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.atguigu.springmvc.crud.dao.DepartmentDao;
    import com.atguigu.springmvc.crud.dao.EmployeeDao;
    import com.atguigu.springmvc.crud.entities.Employee;

    @Controller
    public class EmployeeHandler {

    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
    private DepartmentDao departmentDao;

    //更新操作

    @ModelAttribute

    //只有在更新的时候,前台通过<form:hidden path="id"/>才会传过来一个id的值,

    //使用@RequestParam可以取到,设置为不是一定要获取到此id :required=false,因为每一次请求都会调用该方法
    public void getEmployee(@RequestParam(value="id",required=false) Integer id,     
    Map<String, Object> map){
    if(id != null){
    map.put("employee", employeeDao.get(id));//键employee为Employee第一个字母小写
    }
    }

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

    return "redirect:/emps";
    }

    //表单回显 如果传回去的employee,有值,form标签将会自动显示出来
    @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";
    }

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

    //将departments放入到request域对象中,用于部门信息在前台的显示
    @RequestMapping(value="/emp", method=RequestMethod.POST)
    public String save(Employee employee, 
    Map<String, Object> map){

    map.put("departments", departmentDao.getDepartments());
    map.put("employee", new Employee());//用于设置<form:form modelAttribute="employee">
    return "input";


    }

    ///保存操作

    @RequestMapping(value="/add",method=RequestMethod.POST)
    public String save(Employee employee){
    employeeDao.save(employee);
    return "redirect:/springmvc/listall";
    }


    //显示全部employee信息
    @RequestMapping("/emps")
    public String list(Map<String, Object> map){
    map.put("employees", employeeDao.getAll());
    return "list";
    }

    }

    7、jsp页面

    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>
    <!--此处一定在要springmvc的配置文件中设置<mvc:default-servlet-handler/>-->
    <script type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script>
    <script type="text/javascript">

    //将delete 的get请求,通过jQuery变成delete请求
    $(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>

    <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="emp/${emp.id}">Edit</a></td>
    <td><a class="delete" href="emp/${emp.id}">Delete</a></td>
    </tr>
    </c:forEach>
    </table>
    </c:if>

    <br><br>

    <a href="emp">Add New Employee</a>

    </body>
    </html>

    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="form" uri="http://www.springframework.org/tags/form" %>
    <%@ 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>


    <!--
    1. WHY 使用 form 标签呢 ?
    可以更快速的开发出表单页面, 而且可以更方便的进行表单值的回显
    2. 注意:
    可以通过 modelAttribute 属性指定绑定的模型属性,
    若没有指定该属性,则默认从 request 域对象中读取 command 的表单 bean
    如果该属性值也不存在,则会发生错误。
    -->
    <br><br>
    <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>

    <!--
    本文主要记录一些作者在使用spring mvc过程中遇到的一些以及解决办法,以备日后查询或者供其他网友阅读,每个问题的解决办法肯定不止一种,如果你也遇到过类似问题,并且有独特的见解,我会很高兴你能留言给我,谢谢。 :)

    1、 前台提交form,tomcat返回 http status 400 The request sent by the client was syntactically incorrect,控制台无任何错误输出。

    这是因为前台form表单中的某些参数 和 后台接受的参数类型不一致导致的。即参数名称相同,但是类型不一致。spring mvc在绑定参数的时候出现异常,所以返回400错误。但是坑爹的地方在于,这个异常会被spring mvc吃掉,不会显示在控制台中。

    解决办法:检查form表单中的参数和后台的参数对应,看是否有参数名相同但是类型不一致的情况。或者把当前日志设为debug 级别,然后在日志中即可看到spring 抛出的异常信息,即可发现哪个参数出现了错误。 -->


    Department: <form:select path="department.id"  //注意此处的设置一定要为department.id 与itemValue="id"的类型保持一致,否则会出现400异常
    items="${departments }" itemLabel="departmentName" itemValue="id"></form:select>
    <br>
    <input type="submit" value="Submit"/>
    </form:form>

    </body>
    </html>

  • 相关阅读:
    (转)[Android实例] 关于使用ContentObserver监听不到删除短信会话的解决方案
    (转)Android 使用com.j256.ormlite
    Android中判断网络连接是否可用及监控网络状态
    2018/11/12-操作系统课笔记
    mysql的ONLY_FULL_GROUP_BY语义 --转自http://www.wtoutiao.com/p/19dh3ec.html
    nginx相关配置说明
    为重负网络优化 Nginx 和 Node.js --引用自https://linux.cn/article-1314-1.html
    windows环境下局域网内无法访问apache站点
    27个知名企业品牌VI视觉识别系统规范手册
    TopShelf&Quartz.Net实现多任务的值守
  • 原文地址:https://www.cnblogs.com/yydeyi/p/4722576.html
Copyright © 2011-2022 走看看