2017-03-26 1 views
0

저는 스프링 프레임 워크에서 초보자이며 질문하고 싶습니다. 내 사용자 DB에 등록하려면 POST 요청을 올바르게 전달해야합니까?POST 요청을 전달 중입니다. 안전 보안. 나머지 템플릿. 잭슨 변환기

나는 안드로이드 클라이언트를 가지고 있으며 웹 서비스를 사용하는 유일한 방법을 찾았습니다. AsyncTask를 사용하여 요청을 관리하고 있습니다.

그러나 User 클래스의 POST 요청을 데이터베이스에 등록하는 방법을 모르겠습니다. 데이터베이스가 이미있는 로직입니다.

요청을 게시하는 방법과 서버에서 그를 관리하는 방법을 도와 달라는 부탁드립니다.

서버 측, 사용자 컨트롤러 : 그래서 여기

내 코드입니다

@RestController 
@RequestMapping("/user") 
public class UserController { 

    @Autowired 
    private UserService userService; 

    @Autowired 
    private SecurityService securityService; 

    @Autowired 
    private UserValidator userValidator; 


    @RequestMapping(value = "/registration", method = RequestMethod.POST) 
    @ResponseBody 
    public User registration(@RequestBody User user, BindingResult bindingResult, Model model) { 
     userValidator.validate(user, bindingResult);// here is validate logic 
     if (bindingResult.hasErrors()) { 
      //What should i return here to my Android client ? 
     } 
     userService.save(user); 
     securityService.autoLogin(user.getUserName(), user.getConfirmPassword()); 
     return user; 
    } 

    @RequestMapping(value = "/login", method = RequestMethod.GET) 
    public String login(Model model, String error, String logout) { 
     if (error != null) { 
      model.addAttribute("error", "Username or password is incorrect."); 
     } 

     if (logout != null) { 
      model.addAttribute("message", "Logged out successfully."); 
     } 

     return "login";// what should I return to the client ??? 
     //How my android client will understand that user is loged in ? 
    } 
} 

다음으로 (여기에 몇 가지 MVP 논리지만, NVM) 클라이언트 측이 :

public class CreateAccountPresenter implements CreateAccountContract.Presenter { 
    private CreateAccountContract.View view; 
    private String userName; 
    private String userPassword; 
    private String confirmUserPassword; 


    public CreateAccountPresenter(CreateAccountContract.View view) { 
     this.view = view; 
    } 

    @Override 
    public void onCreateAccountClick() { 
     userName = view.getUserName(); 
     userPassword = view.getPassword(); 
     confirmUserPassword = view.getPasswordConfirmation(); 
     new CreateAccountTask().execute(); 

    } 

    private class CreateAccountTask extends AsyncTask<Void, Void, User>{ 
     // How do I properly pass the post request with my User object ? 
     @Override 
     protected User doInBackground(Void... voids) { 
      RestTemplate restTemplate = new RestTemplate(); 
      restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); 
      User user = new User(userName, userPassword, confirmUserPassword); 
      return restTemplate.postForObject(URL.getUserRegistration(), user, User.class); 
     } 

     @Override 
     protected void onPostExecute(User user) { 
      view.makeToast("User registration complited " + user.getUserName()); 
     } 
    } 

} 

마 클라이언트 측에서 변환기를 초기화해야합니까? 의견을 말하면 코드를 게시하면 도움을 요청할 수도 있습니다. 나는 약간의 클라이언트 측 코드를 변경

UPDATE는 NAD는 지금은 클라이언트 측에서 다음 오류가 점점 오전 :

W/RestTemplate: POST request for "http://192.168.0.80:8080/user/registration" resulted in 400 (Bad Request); invoking error handler E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1 Process: com.example.user.userauthorisation, PID: 4676 java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:300) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) at java.util.concurrent.FutureTask.setException(FutureTask.java:222) at java.util.concurrent.FutureTask.run(FutureTask.java:242) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:818) Caused by: org.springframework.web.client.HttpClientErrorException: 400 Bad Request at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:88) at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:585) at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:541) at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:499) at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:348) at com.example.user.userauthorisation.createaccount.CreateAccountPresenter$CreateAccountTask.doInBackground(CreateAccountPresenter.java:42) at com.example.user.userauthorisation.createaccount.CreateAccountPresenter$CreateAccountTask.doInBackground(CreateAccountPresenter.java:35) at android.os.AsyncTask$2.call(AsyncTask.java:288) at java.util.concurrent.FutureTask.run(FutureTask.java:237) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)  at java.lang.Thread.run(Thread.java:818)  W/EGL_emulation: eglSurfaceAttrib not implemented W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xeb89dde0, error=EGL_SUCCESS 

그리고 서버 측

:

어떤 도움
2254021 [http-apr-8080-exec-2] WARN org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Unrecognized field "confirmationPassword" (class com.webserverconfig.user.entity.User), not marked as ignorable (4 known properties: "id", "confirmPassword", "userName", "userPassword"]) 
at [Source: [email protected]; line: 1, column: 26] (through reference chain: com.webserverconfig.user.entity.User["confirmationPassword"]); nested exception is com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "confirmationPassword" (class com.webserverconfig.user.entity.User), not marked as ignorable (4 known properties: "id", "confirmPassword", "userName", "userPassword"]) 
at [Source: [email protected]; line: 1, column: 26] (through reference chain: com.webserverconfig.user.entity.User["confirmationPassword"]) 

하십시오 ?

답변

0

User 빈을 공유하지 않았지만 오류 로그에 confirmationPassword 필드에 액세스하려는 것으로 표시되어 있지만 confirmPassword 만있는 것으로 나타납니다. 빈의 getter 이름을 확인하십시오.

+0

예, 해결했습니다. 이제 등록 방법이 잘 작동합니다. 나는 로그인 방법에 문제가있다. – Andrew