首页 > 解决方案 > 在 Postman 中使用 REST 控制器测试 Spring 应用

问题描述

所以,我的代码是这样的:

基本应用程序.java

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

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

控制器主页.java

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

课程控制器.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

@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(接口)

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

@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);
    }

}

使用 Postman 工具测试此应用程序时遇到问题。我知道在 Spring Tool Suite 中启动应用程序后,我会转到站点 (localhost:8080) 并在那里输入数据(基本讲座数据:姓名、简短内容、讲师...),但是当我键入 URL 时在邮递员中,例如。http://localhost:8080/lecture/1,结果什么也没打印出来,我不知道为什么。

我使用的模板是:index.html(主页)、login.html(登录页面)、output.html(显示之前输入的讲座数据的页面)、newLecture.html(输入讲座的表格)和allLectures。 html(显示所有已创建讲座的输出的页面)。我没有任何名为“lecture”的模板,就像 LectureRestController.java 类中提到的那样,是这个问题吗?因为如果是这样,我不知道如何创建一个会填充有关讲座的数据的模型。

更新:

这是 Postman 在输入http://localhost:8080/lecture时的响应 postman1 这是 Postman 在输入http://localhost:8080/lecture/1时的 响应 postman2

标签: javaspringhibernaterestpostman

解决方案


我已经解决了,问题是我实际上并没有.save()LessonController.java类中调用方法,特别是在processForm方法中,在 else 块中。我创建了一个@Autowired类的实例HibernateLectureRepository.java,然后在上面提到的地方,我插入了实例并调用了.save()方法。

感谢@EbertToribio 在评论中提供的帮助。


推荐阅读