2.RailsをSpringBootに移行する
2.5 コントローラの作成
①パッケージ・エクスプローラーから、右クリックで新規>クラスを選択し、WebNoteController.javaを作成し 以下のコードを入力します
WebNoteController.java
package com.example.demo;
import java.security.Principal;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class WebNoteController {
@Autowired
WebnoteRepository repos;
@GetMapping("/")
public ModelAndView index(
@ModelAttribute("formModel") Webnote webnote,
ModelAndView mav) {
mav.setViewName("index");
Iterable list = repos.findAll();
mav.addObject("data", list);
return mav;
}
@GetMapping("/new")
ModelAndView add() {
ModelAndView mav = new ModelAndView();
Webnote webnote = new Webnote();
mav.addObject("webnote", webnote);
mav.setViewName("new");
return mav;
}
@GetMapping("/edit")
ModelAndView edit(@RequestParam int id) {
ModelAndView mav = new ModelAndView();
Webnote webnote = repos.findById(id);
mav.addObject("webnote", webnote);
mav.setViewName("new");
return mav;
}
@GetMapping("/show")
ModelAndView show(@RequestParam int id) {
ModelAndView mav = new ModelAndView();
Webnote webnote = repos.findById(id);
mav.addObject("webnote", webnote);
mav.setViewName("show");
return mav;
}
@PostMapping("/create")
@Transactional(readOnly=false)
public ModelAndView save(
@ModelAttribute("webnote") @Validated Webnote webnote,
BindingResult result,
Principal principal) {
webnote.setCreatedAt(new Date());
webnote.setUpdatedAt(new Date());
repos.saveAndFlush(webnote);
return new ModelAndView("redirect:index");
}
@PostMapping("/delete")
@Transactional(readOnly=false)
public ModelAndView delete(@RequestParam int id) {
repos.deleteById(id);
return new ModelAndView("redirect:index");
}
}