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

时间:2018-10-24 14:01:27

标签: java spring hibernate rest postman

所以,我的代码是这样:

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(显示所有已创建演讲的输出的页面)。我没有LectureRestController.java类中提到的任何名为“ lecture”的模板,这是问题吗?因为如果是这样,我不知道如何创建一个可以用有关演讲的数据填充的内容。

更新:

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

1 个答案:

答案 0 :(得分:1)

我已经解决了问题,问题是我实际上没有在else块的ObservableCollection<MyObjectINotifyImplemented>类中,特别是在CollectionChanged方法中调用方法$results = Foreach ($line in $list) { $val = [double]$line.Split('=')[3].Trim().TrimEnd('s') if($val -lt 5) { $val } } 。我已经创建了.save()类的LessonController.java实例,然后在上述位置插入了该实例并调用了processForm方法。

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