简体   繁体   English

在Postman中使用REST控制器测试Spring应用

[英]Testing a Spring app using REST controllers in Postman

So, my code is this: 所以,我的代码是这样的:

BasicApp.java BasicApp.java

@SpringBootApplication(exclude=HibernateJpaAutoConfiguration.class)
public class BasicApp {

    public static void main(String[] args) {
        SpringApplication.run(BasicApp.class, args);
    }
}

ControllerHome.java ControllerHome.java

@Controller
@RequestMapping()
public class ControllerHome {
    @RequestMapping(method = RequestMethod.GET)
    public String index() {
        return "index";
    }
}

LessonController.java LessonController.java

@Slf4j
@Controller
@RequestMapping
@SessionAttributes({"types", "positions", "lectureList", "published"})
public class ControllerLecture {

    List<Lecture> lectureList= new ArrayList<>();

    @RequestMapping
    public String newLecture() {

        return "newLecture";
    }

    @GetMapping("/newLecture")
    public String showForm(Model model, Lecture lecture) {

        log.info("Filling data to show form.");

        model.addAttribute("lecture", new Lecture ());
        model.addAttribute("types", Lecture.LectureType.values());
        model.addAttribute("positions", Lecturer.LecturerPositions.values());
        model.addAttribute("published", lecture.getPublished());

        return "newLecture";
    }

    @GetMapping("/allLectures")
    public String showLectures() {

        return "allLectures";
    }

    @GetMapping("/resetCounter")
    public String resetCounter(SessionStatus status) {

        lectureList.clear();
        status.setComplete();
        return "redirect:/newLecture";
    }

    @PostMapping("/newLecture")
    public String processForm(@Valid Lecture lecture, Errors errors, Model model) {

        log.info("Processing lecture: " + lecture);

        if(errors.hasErrors()) {

            log.info("Lecture has errors. Ending.");

            return "newLecture";

        } else {

            lectureList.add(lecture);

            model.addAttribute("numberOfLectures", lectureList.size());

            model.addAttribute("lecture", lecture);

            model.addAttribute("published", lecture.getPublished());

            model.addAttribute("lectureList", lectureList);

            log.info("Lecture successfully saved: " + lecture);

            return "output";
        }
    }
}

LectureRestController.java LectureRestController.java

@RestController
@RequestMapping(path="/lecture", produces="application/json")
@CrossOrigin(origins="*")
public class LectureRestController {

    @Autowired
    LectureRepository lectureRepository;

    @GetMapping
    public Iterable<Predavanje> findAll() {

        return lectureRepository.findAll();
    }

    @GetMapping("/{id}")
    public ResponseEntity<Lecture> findOne(@PathVariable Long id) {

        Lecture lecture = lectureRepository.findOne(id);

        if(lecture != null) {

            return new ResponseEntity<>(lecture, HttpStatus.OK);
        } else {

            return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
        }
    }

    @ResponseStatus(HttpStatus.CREATED)
    @PostMapping(consumes="application/json")
    public Lecture save(@RequestBody Lecture lecture) {

        return lectureRepository.save(lecture);
    }

    @PutMapping("/{id}")
    public Predavanje update(@RequestBody Lecture lecture) {

        lectureRepository.update(lecture);

        return lecture;
    }

    @ResponseStatus(HttpStatus.NO_CONTENT)
    @DeleteMapping("/{id}")
    public void delete (@PathVariable Long id) {

        lectureRepository.delete(id);
    }
}

LectureRepository.java (interface) LectureRepository.java(接口)

import ... .Lecture;

public interface LectureRepository {

    Iterable<Lecture> findAll();

    Lecture findOne(Long id);

    Lecture save(Lecture lecture);

    Lecture update(Lecture lecture);

    void delete(Long id);
}

HibernateLectureRepository.java HibernateLectureRepository.java

@Primary
@Repository
@Transactional
public class HibernateLectureRepository implements LectureRepository {

    private SessionFactory sessionFactory;

    @Autowired
    public HibernateLectureRepository(SessionFactory sessionFactory) {

        this.sessionFactory = sessionFactory;
    }

    @Override
    public Iterable<Lecture> findAll() {

        return sessionFactory.getCurrentSession().createQuery("SELECT p FROM Lecture p", Lecture.class).getResultList();
    }

    @Override
    public Lecture findOne(Long id) {

        return sessionFactory.getCurrentSession().find(Lecture.class, id);
    }

    @Override
    public Lecture save(Lecture lecture) {

        lecture.setEntryDate(new Date());
        Serializable id = sessionFactory.getCurrentSession().save(lecture);
        lecture.setId((Long)id);

        return lecture;
    }

    @Override
    public Lecture update(Lecture lecture) {

        sessionFactory.getCurrentSession().update(lecture);

        return lecture;
    }

    @Override
    public void delete(Long id) {

        Lecture lecture = sessionFactory.getCurrentSession().find(Lecture.class, id);
        sessionFactory.getCurrentSession().delete(lecture);
    }

}

I have a problem when testing this app with the Postman tool. 使用Postman工具测试此应用程序时出现问题。 I know that after I start the app in Spring Tool Suite, I go to the site (localhost:8080) and enter the data there (basic lecture data: name, short content, lecturer...), but when I type the URL in the Postman eg. 我知道在Spring Tool Suite中启动应用程序后,我转到站点(localhost:8080)并在那里输入数据(基本讲义数据:名称,简短内容,讲师...),但是当我键入URL时在邮递员里 http://localhost:8080/lecture/1 , it prints out nothing as a result, and I don't know why. http:// localhost:8080 / lecture / 1 ,结果什么也没打印出来,我也不知道为什么。

The templates that I use are: index.html (homepage), login.html (login page), output.html (page which displays data of the before entered lecture), newLecture.html (a form for entering lectures) and allLectures.html (page which displays the output of all the created lectures). 我使用的模板是:index.html(主页),login.html(登录页面),output.html(显示之前输入的讲座数据的页面),newLecture.html(用于输入讲座的表单)和allLectures。 html(显示所有已创建演讲的输出的页面)。 I don't have any templates named "lecture", like referred to in the LectureRestController.java class, is that the problem? 我没有LectureRestController.java类中提到的任何名为“ lecture”的模板,这是问题吗? Because if it is, I don't know how to create one which will fill itself with data about the lectures. 因为如果是这样,我不知道该如何创建一个将填充有关讲座数据的文件。

Update: 更新:

This is Postman's response when typing in http://localhost:8080/lecture postman1 This is Postman's response when typing in http://localhost:8080/lecture/1 postman2 这是邮差的反应在打字时的http://本地主机:8080 /演讲 postman1这是邮差的反应在打字时的http://本地主机:8080 /演讲/ 1 postman2

I've solved it, the problem was that I wasn't actually calling the method .save() in the LessonController.java class, specifically in the processForm method, in the else block. 我已经解决了,问题是我实际上没有在LessonController.java类中,特别是在else块中的processForm方法中调用方法.save() I've created an @Autowired instance of the class HibernateLectureRepository.java , and then at the above mentioned spot, I've inserted the instance and called the .save() method. 我已经创建了HibernateLectureRepository.java类的@Autowired实例,然后在上述位置插入了该实例,并调用了.save()方法。

Thank you @EbertToribio for the help provided in the comments. 感谢@EbertToribio在评论中提供的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM