Spring MVC (6) spring MVC 는 첨삭 검사 의 작은 항목 을 쓴다.

36413 단어 SpringMVC
오늘 은 여기 서 이전에 쓴 직원 정보 에 대해 첨삭 검 사 를 하 는 작은 프로젝트 를 정리 합 니 다. 먼저 필요 한 환경 을 구축 하고 직원 과 부서 의 실체 류 와 대응 하 는 dao 는 다음 과 같 습 니 다.
부서 실체 클래스:
package com.tanla.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
                + "]";
    }

}

직원 실체 클래스: 그 중 몇 가지 주해 @ Past: 검 증 된 데이터 형식: java. util. Date, java. util. Calendar, Joda Time 라 이브 러 리 의 날짜 유형 설명: 주해 의 요소 값 (날짜 유형) 을 검증 하 는 것 이 현재 시간 보다 빠 른 주해 자세 한 내용 은 다음 과 같 습 니 다.http://www.cnblogs.com/easymind223/p/5841043.html
package com.tanla.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
    }
}

dao 층:
package com.tanla.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.tanla.springmvc.crud.entities.Department;
import com.tanla.springmvc.crud.entities.Employee;

@Repository
public class EmployeeDao {

    private static Map employees = null;

    @Autowired
    private DepartmentDao departmentDao;

    static{
        employees = new HashMap();

        employees.put(1001, new Employee(1001, "E-AA", "[email protected]", 1, new Department(101, "D-AA")));
        employees.put(1002, new Employee(1002, "E-BB", "[email protected]", 1, new Department(102, "D-BB")));
        employees.put(1003, new Employee(1003, "E-CC", "[email protected]", 0, new Department(103, "D-CC")));
        employees.put(1004, new Employee(1004, "E-DD", "[email protected]", 0, new Department(104, "D-DD")));
        employees.put(1005, new Employee(1005, "E-EE", "[email protected]", 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 getAll(){
        return employees.values();
    }

    public Employee get(Integer id){
        return employees.get(id);
    }

    public void delete(Integer id){
        employees.remove(id);
    }
}
package com.tanla.springmvc.crud.dao;

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

import org.springframework.stereotype.Repository;

import com.tanla.springmvc.crud.entities.Department;

@Repository
public class DepartmentDao {

    private static Map 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 getDepartments(){
        return departments.values();
    }

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

}

그리고 Spring mvc 의 환경 을 구축 합 니 다. 주의: 웹. xml 에 다음 차단 기 를 추가 하여 post 요청 을 delete 또는 put 요청 으로 변경 합 니 다.

    <filter>
      <filter-name>HiddenHttpMethodFilterfilter-name>
      <filter-class>org.springframework.web.filter.HiddenHttpMethodFilterfilter-class>
    filter>

    <filter-mapping>
      <filter-name>HiddenHttpMethodFilterfilter-name>
      <url-pattern>/*url-pattern>
    filter-mapping>   

다음은 이 작은 프로젝트 가 실현 하 는 기능 과 그 절 차 를 말한다.첫 번 째, index. jsp 를 새로 만 듭 니 다.
"java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title heretitle>
head>
<body>
   
   <a href="emps">Get All Employeea>
body>
html>

두 번 째 단 계 는 이 페이지 의 하이퍼링크 에 처리 방법 을 쓰 고 새로운 종 류 를 만 듭 니 다. EmployeeHandler 라 는 이름 으로 그 안에 방법 을 쓰 고 그 중의 반환 값 은 jsp 보기 에 대응 하 며 list 라 고 합 니 다.
@RequestMapping("/emps")
    public String list(Map<String, Object> map) {

        map.put("employees", employeeDao.getAll());
        return "list";
    }

세 번 째 단 계 는 Springmvc. xml 의 설정 정보 에 따라 보 기 를 만 듭 니 다. 이 예 에서 Springmvc. xml 는 다음 과 같이 설정 되 어 있 습 니 다. EmployeeHandler 류 에서 의 처리 방법 이 되 돌아 오 는 모든 보 기 는 / WEB - INF / views / 경로 에 있 음 을 설명 합 니 다.그래서 모든 직원 정 보 를 표시 하기 위해 list. jsp 를 새로 만 듭 니 다.
 <context:component-scan base-package="com.tanla.springmvc.crud">context:component-scan>
    "org.springframework.web.servlet.view.InternalResourceViewResolver">

       <property name="prefix" value="/WEB-INF/views/">property>
       <property name="suffix" value=".jsp">property>

    

list.jsp:
<c:if test="${empty requestScope.employees }">
                     
    c:if>

    <c:if test="${!empty requestScope.employees }">
      <table border="1" cellpadding="10" cellspacing="0">
         <tr>
           <td>IDtd>
           <td>LAST NAMEtd>
           <td>EMAILtd>
           <td>GENDERtd>
           <td>DEPARTMENTtd>
           <td>EDITtd>
           <td>DELETEtd>
         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}">edita>td>
              <td><a class="delete" href="emp/${emp.id}">deletea>td>
            tr>
         c:forEach>

      table>
    c:if>

    <a href="emp">Add New Employeea>

네 번 째 단 계 는 신 입 사원 을 추가 하 는 기능 을 쓴다.list. jsp 에 있 는 신 입 사원 추가 단 추 를 누 르 면 해당 하 는 handler 클래스 의 방법 으로 이동 한 후 input. jsp 페이지 로 이동 합 니 다.
@RequestMapping(value="/emp" , method = RequestMethod.GET)
    public String input(Map maps) {
            //                   
        maps.put("departments",departmentDao.getDepartments() );
        //       ,                  bean
        maps.put("employee", new Employee());
        return "input";
    }

input. jsp 에서 주의해 야 할 사항: 1) action 의 경 로 는 ${pageContext. request. contextPath} 2) 페이지 의 속성 은 실체 클래스 의 속성 과 일일이 대응 해 야 합 니 다.
"java.util.HashMap"%>
"java.util.Map"%>
"java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
"form" uri="http://www.springframework.org/tags/form"  %>
"c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title heretitle>
head>
<body>

  <form:form action="${pageContext.request.contextPath }/emp" method="POST" modelAttribute="employee">
    
    <c:if test="${employee.id == null }">
      LastName:<form:input path="lastName" />
    c:if>

    <c:if test="${employee.id != null }">
      <form:hidden path="id"/>
      <input type="hidden" name="_method" value="PUT"/>
    c:if>
    <br><br>
    Email:<form:input path="email"/>
    <br><br>
    String> genders = new HashMapString>();
      genders.put(1, "male");
      genders.put(0, "female");

      request.setAttribute("genders",genders);
    %>
    Gender:<form:radiobuttons path="gender" items="${genders }"/>
    <br><br>
    Department:<form:select path="department.id" items="${departments }" itemLabel="departmentName" itemValue="id">form:select>
    <br><br>
    <input type="submit" value="Submit">

  form:form>

body>
html>

다섯 번 째 단 계 는 제출 을 클릭 한 후 제출 방법 에 따라 save 방법 으로 넘 어 갑 니 다.
@RequestMapping(value="/emp" , method = RequestMethod.POST)
    public String save(Employee employee) {
        System.out.println(employee);
        employeeDao.save(employee);
        return "redirect:/emps";
    }

여섯 번 째 단 계 는 list. jsp 페이지 에 다음 코드 를 추가 해 야 합 니 다.
"" method="post"> type="hidden" name="_method" value="DELETE">
<script type="text/javascript">

  $(function(){

         $(".delete").click(function(){

             var href = $(this).attr("href");

             $("form").attr("action",href).submit();

             return false;
         });


      })

  script>

정적 페이지 가 효과 가 있 도록 springmvc. xml 설정 파일 에 추가 해 야 합 니 다:
 

     <mvc:default-servlet-handler/>
     <mvc:annotation-driven>mvc:annotation-driven>
@RequestMapping(value="/emp/{id}",method = RequestMethod.DELETE)
    public String delete(@PathVariable("id") Integer id) {

        employeeDao.delete(id);
        return "redirect:/emps";
    }

일곱 번 째 단계, 수정 작업 주의사항: handler 클래스 에 다음 과 같은 방법 을 추가 해 야 합 니 다. 페이지 에 lastName 속성 이 없 기 때문에 페이지 에 있 는 값 을 직접 가 져 갈 수 없습니다. lastName 이 비어 있 을 수 있 습 니 다. 데이터 베 이 스 를 데이터베이스 에서 꺼 낸 다음 페이지 의 값 으로 덮어 야 합 니 다. 수정 되 지 않 은 값 이 비어 있 지 않도록 해 야 합 니 다.
@ModelAttribute
    public void getEmployee(@RequestParam(value="id",required=false)Integer id,
            Map maps) {
        if(id!=null) {
            maps.put("employee", employeeDao.get(id));
        }
    }
@RequestMapping(value="/emp",method=RequestMethod.PUT)
    public String update(Employee employee) {
        employeeDao.save(employee);
        return "redirect:/emps";
    }

좋은 웹페이지 즐겨찾기