NIe mogę poradzic sobie z Postman metodami PUT i POST

0

Mam problem w rescie a Mianowicie kiedy sprawdzam w POSTMAN metody GET i DELETE działają poprawnie ale już POST czy PUT to nie. W czym jest problem ? Zaznaczę że jestem początkujący w Springu i w tworzeniu aplikacji restowych

package com.xxx.xxx.controller;

import com.xxx.xxx.model.User;
import com.xxx.xxx.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import java.lang.String;

import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder;

import javax.jws.soap.SOAPBinding;
import java.text.DateFormat;
import java.util.*;

@Controller
@RequestMapping("")
public class LoginController {


//    static Set User;
//
//    static{
//        User = new HashSet();
//        User foobar = null;
//        for (int i = 0; i < 10; i++){
//            foobar = new User(i , "User " + i);
//            User.add(foobar);
//        }
//    }


  private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
//
//
//    Map<Integer, User> userMap = new HashMap<>();
//
    @Autowired
    private UserService userService;




    //-------------------Retrieve All Users--------------------------------------------------------

    @RequestMapping(value = "/user/", method = RequestMethod.GET)
    public ResponseEntity<List<User>> listAllUsers() {
        List<User> users = userService.getAllUser();
        if(users.isEmpty()){
            return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND
        }
        return new ResponseEntity<List<User>>(users, HttpStatus.OK);
    }


    //-------------------Retrieve Single User--------------------------------------------------------

    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<User> getUser(@PathVariable("id") long id) {
        System.out.println("Fetching User with id " + id);
        User user = userService.getUser(id);
        if (user == null) {
            System.out.println("User with id " + id + " not found");
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<User>(user, HttpStatus.OK);
    }



    //-------------------Create a User--------------------------------------------------------

    @RequestMapping(value = "/user/", method = RequestMethod.POST)
    public ResponseEntity<Void> createUser(@RequestBody User user,    UriComponentsBuilder ucBuilder) {
        System.out.println("Creating User " + user.getName());

        if (userService.isUserExist(user)) {
            System.out.println("A User with name " + user.getName() + " already exist");
            return new ResponseEntity<Void>(HttpStatus.CONFLICT);
        }

        userService.add(user);

        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getUserId()).toUri());
        return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
    }


    //------------------- Update a User --------------------------------------------------------

    @RequestMapping(value = "/user/{id}", method = RequestMethod.PUT)
    public ResponseEntity<User> updateUser(@PathVariable("id") long id, @RequestBody User user) {
        System.out.println("Updating User " + id);

        User updateUser = userService.getUser(id);

        if (updateUser==null) {
            System.out.println("User with id " + id + " not found");
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }

        updateUser.setUserId(user.getUserId());
        updateUser.setName(user.getName());
        updateUser.setSurname(user.getSurname());
        updateUser.setMail(user.getMail());
        updateUser.setLogin(user.getLogin());

        userService.edit(updateUser);
        return new ResponseEntity<User>(updateUser, HttpStatus.OK);
    }

    //------------------- Delete a User --------------------------------------------------------

    @RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<User> deleteUser(@PathVariable("id") long id) {
        System.out.println("Fetching & Deleting User with id " + id);

        User user = userService.getUser(id);
        if (user == null) {
            System.out.println("Unable to delete. User with id " + id + " not found");
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }

        userService.delete(id);
        return new ResponseEntity<User>(HttpStatus.NO_CONTENT);
    }


//    //------------------- Delete All Users --------------------------------------------------------
//
//    @RequestMapping(value = "/user/", method = RequestMethod.DELETE)
//    public ResponseEntity<User> deleteAllUsers() {
//        System.out.println("Deleting All Users");
//
//        userService.deleteAllUsers();
//        return new ResponseEntity<User>(HttpStatus.NO_CONTENT);
//    }

    @RequestMapping( value = "/sukces", method = RequestMethod.GET)
    @ResponseBody
    public  String doLogin(){

        return "Sukces!!!";
    }

    @RequestMapping(value = "/time", method = RequestMethod.GET)
    public String home(Locale locale, Model model){
        logger.info("Sukces!!! {}", locale);

        Date date = new Date();
        DateFormat format = DateFormat.getDateInstance(DateFormat.LONG, Locale.UK);

        String formattedDate = format.format(date);

        model.addAttribute("serverTime", formattedDate);

        return "loginPage";
    }


}
0

ZIOM podaj jaki błąd masz, a nie mi nie działa. Jaki kod odpowiedzi?

0

No i powiedz nam co dokładnie wysyłasz. Bo chyba nie wysyłasz pustego żądania post ?

0

Wstawiam

{
    "userId": 3,
    "name": "daddadasasdadadaa",
    "surname": "fafadasdasaad",
    "login": "ddasdas",
    "mail": "dadada"
} 

Błąd:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html 
    xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>GlassFish Server Open Source Edition  4.1  - Error report</title>
        <style type="text/css">
            <!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}HR {color : #525D76;}-->
        </style>
    </head>
    <body>
        <h1>HTTP Status 415 - Unsupported Media Type</h1>
        <hr/>
        <p>
            <b>type</b> Status report
        </p>
        <p>
            <b>message</b>Unsupported Media Type
        </p>
        <p>
            <b>description</b>The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
        </p>
        <hr/>
        <h3>GlassFish Server Open Source Edition  4.1 </h3>
    </body>
</html> 
0

Dodałem ale nadal mam błąd:

 //-------------------Create a User--------------------------------------------------------

    @RequestMapping(value = "/user/", method = RequestMethod.POST,  produces={"application/json", "application/xml"},
            consumes={"application/json", "application/xml"})
    public ResponseEntity<Void> createUser(@RequestBody User user,    UriComponentsBuilder ucBuilder) {
        System.out.println("Creating User " + user.getName());

        if (userService.isUserExist(user)) {
            System.out.println("A User with name " + user.getName() + " already exist");
            return new ResponseEntity<Void>(HttpStatus.CONFLICT);
        }

        userService.add(user);

        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getUserId()).toUri());
        return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
    }


    //------------------- Update a User --------------------------------------------------------

    @RequestMapping(value = "/user/{id}", method = RequestMethod.PUT, produces={"application/json", "application/xml"},
            consumes={"application/json", "application/xml"})
    public ResponseEntity<User> updateUser(@PathVariable("id") long id, @RequestBody User user) {
        System.out.println("Updating User " + id);

        User updateUser = userService.getUser(id);

        if (updateUser==null) {
            System.out.println("User with id " + id + " not found");
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }

        updateUser.setUserId(user.getUserId());
        updateUser.setName(user.getName());
        updateUser.setSurname(user.getSurname());
        updateUser.setMail(user.getMail());
        updateUser.setLogin(user.getLogin());

        userService.edit(updateUser);
        return new ResponseEntity<User>(updateUser, HttpStatus.OK);
    }

Dodałem


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html 
    xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>GlassFish Server Open Source Edition  4.1  - Error report</title>
        <style type="text/css">
            <!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}HR {color : #525D76;}-->
        </style>
    </head>
    <body>
        <h1>HTTP Status 415 - Unsupported Media Type</h1>
        <hr/>
        <p>
            <b>type</b> Status report
        </p>
        <p>
            <b>message</b>Unsupported Media Type
        </p>
        <p>
            <b>description</b>The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
        </p>
        <hr/>
        <h3>GlassFish Server Open Source Edition  4.1 </h3>
    </body>
</html> 

Model:

@Entity
@Table
@JsonAutoDetect
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long userId;
    @Column
    private String name;
    @Column
    private String surname;
    @Column
    private String login;
    @Column
    private String mail;




    public User(String name, String surname, String login, String mail) {
        this.name = name;
        this.surname = surname;
        this.login = login;
        this.mail = mail;
    }

    public User() {
    }


    public User(Long userId, String name) {
        this.userId = userId;
        this.name = name;
    }

    public User(String surname) {
        this.surname = surname;
    }

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long id) {
        this.userId = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getMail() {
        return mail;
    }

    public void setMail(String mail) {
        this.mail = mail;
    }
}
0
{
    "userId": 3,
    "name": "daddadasasdadadaa",
    "surname": "fafadasdasaad",
    "login": "ddasdas",
    "mail": "dadada"
} 
 

a

@Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long userId;
    @Column
    private String name;
    @Column
    private String surname;
    @Column
    private String login;
    @Column
    private String mail;
 

sie rozni - popraw i bedzie dobrze ;]

0

W którym miejscu jest różnica? :(

Jeśli chodzi o Long to nic to nie daje

0

W Postmanie przy tworzeniu requesta masz zakładkę headers, tam musisz dodać Content-type: application/json

0

Nic to nie dało 41161aefd4.png

0

No ale teraz masz 500 a nie 415 - to całkowicie co innego.

0

Nie do końca rozumiem po co ci adnotacja JsonAutoDetect, która nie niesie ze sobą żadnej konfiguracji. To jest jednak szczegół...

  1. Co pojawia się w logu serwera? To, że na zwrocie masz jakiś błąd 4XX to nie jest istotne. Ważne jest co to oznacza na serwerze.
  2. Zamiast @Controller użyj @RestController to tylko konwencja, ale bardzo pomocna.
  3. produces i consumes won. To załatwia konwencja w Springu.
  4. podawanie userId i RequestBody w jednym żądaniu to przerost formy nad treścią. W repozytorium masz masz metodę exists, a przekazany obiekt powinien zawierać userId.
0

Log z serwera

[2015-10-11T14:14:23.682+0200] [glassfish 4.1] [WARNING] [] [javax.enterprise.web] [tid: _ThreadID=30 _ThreadName=http-listener-1(4)] [timeMillis: 1444565663682] [levelValue: 900] [[
  StandardWrapperValve[dispatcher]: Servlet.service() for servlet dispatcher threw exception
java.lang.NullPointerException
	at com.xxxx.xxxx.service.UserServiceImp.findByName(UserServiceImp.java:76)
	at com.xxxx.xxxx.service.UserServiceImp.isUserExist(UserServiceImp.java:86)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:497)
	at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
	at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:201)
	at com.sun.proxy.$Proxy198.isUserExist(Unknown Source)
	at com.xxxx.xxx.controller.LoginController.createUser(LoginController.java:85)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:497)
	at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
	at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
	at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
	at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
	at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
	at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
	at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
	at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
	at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
	at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
	at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:415)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
	at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
	at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
	at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
	at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
	at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
	at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
	at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
	at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
	at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
	at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
	at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
	at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
	at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
	at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
	at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
	at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
	at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
	at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
	at java.lang.Thread.run(Thread.java:745)
]]
 
1

at com.xxxx.xxxx.service.UserServiceImp.findByName(UserServiceImp.java:76)

Co tu wołasz i dlaczego jest to null?

0

To była metoda do sprowadzania czy nie dubluje mi sie nazwa. Po jej usunięciu już wszytko jest ok.

1 użytkowników online, w tym zalogowanych: 0, gości: 1