2017-10-20 8 views
0

컨트롤러/VM 데이터 전송에 문제가있어서 해결책을 찾지 못했습니다. 필자는Spring + Velocity 객체 저장 시도 실패

package com.Controllers; 

import com.Entity.AgentType; 
import com.Entity.User; 
import com.Services.AgentService; 
import com.Services.UserService; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Controller; 
import org.springframework.ui.Model; 
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.servlet.ModelAndView; 
import java.util.List; 

//TODO: TEST CONTROLLER SUBJECT TO DELETE 
@Controller 
public class ViewController { 

    @Autowired 
    private UserService userService; 
    @Autowired 
    private AgentService agentService; 

    @RequestMapping(value = "/list", method = RequestMethod.GET) 
    public ModelAndView listUsersPage(){ 
     List<User>list = userService.getAll(); 
     return new ModelAndView("fragments/userss.vm","users",list); 
    } 

    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET) 
    public ModelAndView edit(@PathVariable Long id){ 
    return new ModelAndView("fragments/edit.vm", 
      "user", (User)userService.getById(id)); 
    } 

    //FUNCTIONAL 
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET) 
    public ModelAndView delete(@PathVariable Long id){ 
     userService.delete(userService.getById(id)); 
     return new ModelAndView("redirect:/list"); 
    } 

    @RequestMapping(value = "/update", method = RequestMethod.POST) 
    public ModelAndView update(User user){ 
     User user1 = user; 
     //userService.update(user1); 
     return new ModelAndView("redirect:/list"); 
    } 



    //Model Attributes 
    @ModelAttribute 
    public void userTypesList(Model model){ 
     model.addAttribute("types", userService.getPositions()); 
    } 
    @ModelAttribute 
    public void officesList(Model model){ 
     model.addAttribute("offices", agentService.getAllByType(AgentType.OFFICE)); 
    } 
} 

와 페이지 (.vm)가 새로운 추가하거나 기존 사용자 (한 예에 불과에게 편집 페이지)를 편집하는 사용자 (아래 클래스 참조)

package com.Entity; 

import org.springframework.transaction.annotation.Transactional; 
import javax.persistence.*; 
import java.util.Date; 

@Entity 
@Transactional 
@Table(name = "USERS") 
public class User { 
    private Long id; 
    private UserType type; 
    private String email; 
    private String password; 
    private String name; 
    private String tel; 
    private Date regDate; 
    private Date lastActive; 
    private Agent office; 

    //Constructors 
    public User(){ 

    } 

    public User(UserType type, String email, String password, String name, String tel, Agent office) { 
     this.type = type; 
     this.email = email; 
     this.password = password; 
     this.name = name; 
     this.tel = tel; 
     this.regDate = new Date(); 
     this.lastActive = null; 
     this.office = office; 
    } 

    //Getters 
    @Id 
    @SequenceGenerator(name = "USERID_SEQ", sequenceName = "USERID_SEQ",allocationSize = 1) 
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "USERID_SEQ") 
    @Column(name = "ID") 
    public Long getId() { 
     return id; 
    } 
    @Column(name = "TYPE") 
    public UserType getType(){ 
     return type; 
    } 
    @Column(name = "EMAIL") 
    public String getEmail() { 
     return email; 
    } 
    @Column(name = "PASSWORD") 
    public String getPassword() { 
     return password; 
    } 
    @Column(name = "NAME") 
    public String getName() { 
     return name; 
    } 
    @Column(name = "TEL") 
    public String getTel() { 
     return tel; 
    } 
    @Column(name = "DATE_REG") 
    public Date getRegDate() { 
     return regDate; 
    } 
    @Column(name = "LAST_ACTIVE") 
    public Date getLastActive() { 
     return lastActive; 
    } 
    @ManyToOne (targetEntity = Agent.class, fetch = FetchType.EAGER) 
    @JoinColumn(name = "OFFICEID") 
    public Agent getOffice() { 
     return office; 
    } 

    // Setters 
} 

컨트롤러를 가지고 :

<title>EDIT USER</title> 
<body> 
<form method="post" action="/update"> 
    id: 
    <input type="text" name="id" path="id" value="$user.id"/> <br> 

    Type: 
    <select name="type" path="type"> 
     <option hidden selected>$user.type</option> 
     #foreach($type in $types) 
      <option value="$type">$type</option> 
     #end 
    </select> <br> 

    e-mail: 
    <input type="text" name="email" path="email" value="$user.email"/> <br> 

    Password: 
    <input type="text" name="password" path="password" value="$user.password"/> <br> 

    Name: 
    <input type="text" name="name" path="name" value="$user.name"/> <br> 

    Tel: 
    <input type="text" name="tel" path="tel" value="$user.tel"/> <br> 

    Reg Date: 
    <input type="date" name="regDate" path="regDate" value="$user.regDate"/> <br> 

    Last Active: 
    <input type="date" name="lastActive" path="lastActive" value="$user.lastActive"/> <br> 

    Office: 
    <select name="office" path="office"> 
     <option hidden selected value="$user.office">$user.office.name</option> 
     #foreach($office in $offices) 
      <option value="$office">$office.name</option> 
     #end 
    </select> <br> 

    <input type="submit" value="Update"/> 

</form> 

</body> 

문제는 내가 t manage to save the updated User via /update(User user). I 더 성공을 여러 가지 방법을 시도하지,하지만 여전히했습니다 수 있다는 것입니다. Whis this code 나는 HTTP Status 400 - Bad Request를 얻고있다. 서버는 클라이언트 오류 (예 : 잘못된 요청 구문, 잘못된 요청 메시지 프레임 또는 사기성 요청 라우팅)로 인식되는 문제로 인해 요청을 처리 할 수 ​​없거나 처리하지 못합니다. 나를 도울 수 있겠습니까? 그게 뭐가 잘못 되었 니?

+0

이 줄의 주석 처리를 해제하면 다음과 같은 메시지가 나타날 수 있습니다 :'//userService.update (user1);'... – Henry

+0

유감스럽게도 이것은 문제를 해결하지 못합니다. 오류의 원인이 아닌지 확인하기 위해 주석을 달았습니다. – Vampirenostra

답변

0

코드에 몇 가지 누락되었습니다. 모든 프리스트, 당신은 양식으로 지정 모델 속성을 그리워 :

<form method="post" action="/update" modelAttribute="user"> 

둘째, 포스트 방법에 지정된 모델 속성 누락 :

@RequestMapping(value = "/update", method = RequestMethod.POST) 
public ModelAndView update(@ModelAttribute("user") User user){ 
    User user1 = user; 
    userService.update(user1); 
    return new ModelAndView("redirect:/list"); 
} 

당신은 자세한 내용이 필요한 경우, 읽을 수 있습니다 Getting Started with Forms in Spring MVC

+0

포인트를 제공해 주셔서 감사합니다. 그러나 그것은 나에게별로 도움이 안된다. 나는 아직도 HTTP Status 400을 얻고있다. (그리고 .vm은 modelAttrinbute를 인식하지 못한다. Idea는 그것에 대한 조언을하지 않는다 .Maby에는 태그가 있어야한다. 라이브러리, jsp처럼?하지만 자습서에 나와있는 방식으로 ID를 보지 못했습니다.) – Vampirenostra

+0

요청에 의해 전달 된 매개 변수를 확인하면 전달 된 매개 변수가 유형과 사무실이라는 것을 알 수 있습니다. 나머지는 't 얼마나 (( – Vampirenostra

+0

) HTTP 400이 사무실 분야에서 발생한다는 사실을 알게되었습니다. 실제 객체가 전송되는 곳입니다. – Vampirenostra