java - 在 Postman 中使用 REST Controller 测试 Spring 应用程序

标签 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(接口(interface))

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 时在 postman 例如。 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

最佳答案

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

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

关于java - 在 Postman 中使用 REST Controller 测试 Spring 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52970972/

相关文章:

java - h : component and a4j:components? 之间的差异

java - 为什么我在 RecyclerView 上得到一个空引用

java - weblogic.deployment.PersistenceUnitInfoImpl.getSharedCacheMode()Ljavax/persistence/SharedCaheMode

java - Spring MVC + 2 JNDI 数据源

spring - 没有将Spring DAO注入(inject)JSF管理的bean中

java - 二维数组按字母顺序选择排序

java - 构造函数和字符串第 2 部分字母示例

Spring RestTemplate初学者: The request sent by the client was syntactically incorrect ()

java - Struts 2 中的多表单执行

java - SessionFactory.openSession() 和 SessionFactory.getCurrentTransaction().commit() 之间的区别