【问题标题】:Testing a Spring app using REST controllers in Postman在 Postman 中使用 REST 控制器测试 Spring 应用
【发布时间】:2019-03-28 23:39:25
【问题描述】:

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

BasicApp.java

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

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

ControllerHome.java

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

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

@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 类中提到的那样,是这个问题吗?因为如果是这样,我不知道如何创建一个会填充有关讲座的数据。

更新:

这是邮递员在输入http://localhost:8080/lecture 时的回复 postman1 这是邮递员在输入http://localhost:8080/lecture/1 时的回复 postman2

【问题讨论】:

  • 可以分享localhost:8080/lecture/1的邮递员回复吗?据我所知,如果存在,您的控制器应该检索 id 为 1 的讲座,否则它将返回空(可能是您的情况)。
  • @EbertToribio 我已经更新了帖子,似乎是空的,但我不知道为什么
  • 我看不到响应的 Http 状态。是 200 吗?
  • @EbertToribio 在第一张照片上是,在第二张照片上是 404 Not Found
  • 错误 404 是因为您的数据库中不存在 id=1 的讲座。当 LectureRepository.findOne("1") 返回 null 时,您正在发送 HttpStatus.NOT_FOUND。也许您需要找出为什么该讲座 ID 未在您的数据库中注册

标签: java spring hibernate rest postman


【解决方案1】:

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

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

【讨论】:

  • 不行,我的rep太低了:/
猜你喜欢
  • 1970-01-01
  • 2018-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-07
  • 1970-01-01
  • 2016-02-08
  • 2013-02-19
相关资源
最近更新 更多