I'm writing a function in controller which should add an object 'Post' into a property of another object 'Topic' which is an arraylist. The parameters required for this function is a 'Post'(p) and the id (topicID) of 'Topic'. I want to know how to send them in Postman.
When I try to send them by filling all parameters of the 'Post' + topicID of 'Topic' in Postman, I got an error message as below.
The function in controller:
@RestController
@RequestMapping("/TopicController")
public class TopicController {
@Autowired
TopicRepository topicRepository;
@Autowired
PostRepository postRepository;
@RequestMapping(method = RequestMethod.POST, value = "/AddPost")
public void addPost(Post p, @RequestParam(value="topicID") int topicID) {
if (topicRepository.existsById(topicID)) {
Optional<Topic> ot = topicRepository.findById(topicID);
Topic t = ot.get();
t.addPost(p);
p.setTopic(t.getName());
postRepository.save(p);
topicRepository.save(t);
}
}
}
Class Post :
@Entity
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String topic;
private String title;
@Temporal(TemporalType.TIMESTAMP)
private Date posteDate;
private String auther;
@Lob
private String content;
private int readTimes;
public void setTopic(String topic) {
this.topic = topic;
}
}
Class Topic :
@Entity
public class Topic {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(unique=true)
private String name;
@Lob
private String presentation;
private ArrayList<String> coverPhotos;
private ArrayList<Post> posts;
public void addPost(Post post) {
this.posts.add(post);
}
public void setPosts(ArrayList<Post> posts) {
this.posts = posts;
}
}
Error message:
2019-05-07 11:56:22.907 ERROR 24900 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException: null
You need to create the array before using .add(), change your addPost() like this:
public void addPost(Post post) {
if(posts == null) posts = new ArrayList<>();
this.posts.add(post);
}
You are missing @RequestBody
annotation in your controller method. Your controller method should look something like below, this way the body will be mapped to your Post
object and the query parameter topicId
will be mapped to your topicId
object.
public void addPost(@RequestBody Post p, @RequestParam(value="topicID") int topicID)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.