2014年6月3日火曜日

SpringMVCをつかってみた

なんとなく、以下のフレームワークやDBでサンプルを作ってみた。

Spring 4.x
SpringMVC
Mybatis 3.x
Tomcat 7.x
derby

Springは、言わずと知れたDIコンテナ。
SpringMVCは、MVCモデルを提供するStrutsに変わるもの。
Mybatisは、ibatisの後継にあたるORマッパー。
Tomcatも言わずと知れたWEBコンテナ。
derbyは、JDKに付属するDB。

こんな簡単なサンプルを作った(しょぼい)。


SpringMVCは便利です。こんな風に書ける。

@Controller   
@RequestMapping("/test")   
public class TestController {   
   
 @Autowired  
 TestService testService;  
   
 @RequestMapping(params = "!action")  
 public View init(Test test) {  
   
  System.out.println("初期"); 
  //testService.testMethod(); 
   
  List testDTOList = testService.disp(); 
   
  test.setTestDTOList(testDTOList); 
   
  return new InternalResourceView("/WEB-INF/jsp/Test.jsp"); 
 }  
   
 @RequestMapping(params = "action=登録")  
 public View reg(@Valid Test test, Errors errors) {  
   
  if (errors.hasErrors()) { 
   System.out.println("エラー有");
   return new InternalResourceView("/WEB-INF/jsp/Test.jsp");
  } 
   
  System.out.println("name: " + test.getName()); 
  System.out.println("no: " + test.getNo()); 
  System.out.println("memo: " + test.getMemo()); 
   
  testService.reg(test); 
  List testDTOList = testService.disp(); 
  test.setTestDTOList(testDTOList); 
   
  System.out.println("登録"); 
   
  return new InternalResourceView("/WEB-INF/jsp/Test.jsp"); 
 }  
   
}   

こんな風に、アノテーションで、リクエストのパラメータにより、リクエストを受けるメソッドを切り替えることができる。
Strutsに比べると、かなり楽。