iT邦幫忙

DAY 10
1

無痛學習SpringMVC與Spring Security系列 第 10

[Controller]Spring MVC Controller CRUD常用annotations介紹(I)

  • 分享至 

  • xImage
  •  

今天要跟大家分享Spring MVC中常用的Controller CRUD常用的annotations。

建一個class DCNController,加入@Controller annotation在component scan時告訴spring這個是一個bean,

@Controller
public class DCNController {
	
}

再來通常我們會呼叫persistence layer的service來取得資料給view,所以接著加入昨天的DCNRepository及DCNService,並標註@Autowired,注入dependency。

@Controller
public class DCNController {
	
	@Autowired
	private DCNRepository dcnRepository;
	
	@Autowired
	private DCNService dcnService;
	
}
請Controller處理URL Request,我們需要宣告一個方法,並加入@RequesMapping(value="url", method=RequestMethod.GET/PUT/POST/DELETE),value參數代表這個方法要處理的網址,method參數支援http的四種request,對於一般網頁,比較常用GET取得網頁資料,POST提送表單,其餘兩種比較常用在RestController,之後再分享,如果傳回client的是jsp,通常這個方法回傳String,這個String即為jsp的檔名,另外會用到Model物件來傳送java物件給jsp,通常呼叫addAttribute(arg1, arg2),第一個變數是要傳到jsp的變數名稱,第二個變數是對應的java物件





@Controller
@RequestMapping("/dcn")
public class DCNController {
	
	@Autowired
	private DCNRepository dcnRepository;
	
	@Autowired
	private DCNService dcnService;
	
	@RequestMapping(value="/list",  method=RequestMethod.GET)
	public String DCNList(Model model){
		model.addAttribute("dcns", dcnRepository.findAll());
		return "DCNList"; //將傳DCNList.jsp至client端
	}
}

如果method不寫,預設則是RequestMethod.GET,以下程式碼回傳的網頁跟上面是一樣的

@RequestMapping("/list")
	public String DCNList(Model model){
		model.addAttribute("dcns", dcnRepository.findAll());
		return "DCNList";//將傳DCNList.jsp至client端
}

如果我們要先取得表單網頁,填寫好後再submit,伺服器把表單資料儲存起來,最後再重新導向到特定網頁,順序則是先GET 表單網頁,在POST 表單資料到伺服器,另@ModelAttribute可使jsp存取java物件變數,常用在表單中,code如下:

@Controller
public class DCNController {
	
	@Autowired
	private DCNRepository dcnRepository;
	
	@Autowired
	private DCNService dcnService;
	
	@RequestMapping("/list")
	public String DCNList(Model model){
		model.addAttribute("dcns", dcnRepository.findAll());
		return "DCNList";
	}
	
	@RequestMapping(value="/add", method=RequestMethod.GET)
	public String getAddDCNForm(@ModelAttribute("newDCN") DCN newDCN){
		return "addDCN"; //傳回addDCN.jsp
	}
	@RequestMapping(value="/add", method=RequestMethod.POST)
	public String processDCNForm(@ModelAttribute("newDCN") DCN newDCN){
		dcnService.add(newDCN); //新增新的資料到資料庫
		return "redirect:/"; //redirect至 "/",相關表單資料將遺失
	}	
}	

編輯addDCN.jsp時,需要加入以下tags,spring form tags作data binding很方便。

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"  %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>

addDCN.jsp code如下,form tag中,需指定modelAttribute參數,來做Data Binding,在input tag中 path參數就是物件參數的binding。

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>



<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Add New DCN</title>


	<div class="grid">
		<div class="row">
			<div class="span1"></div>
			<div class="span3">
				<form:form modelAttribute="newDCN">
				<fieldset>
						<legend>New DCN Record</legend>
						<label>DCN No</label>
						<div class="input-control text size3">
							<form:input type="text" value=""
								placeholder="e.g.NED-LM1-H-N15254" path="no" />
							<button class="btn-clear" tabindex=-1 type="button"></button>
						</div>
						<label>DCN Rev</label>
						<div class="input-control text size1">
							<form:input type="text" value="" placeholder="" path="rev" />
							<button class="btn-clear" tabindex=-1 type="button"></button>
						</div>
						<label>Category</label>
						<div class="input-control select">
							<form:select path="category">
								<option>A</option>
								<option>B</option>
								<option>C</option>
								<option>D</option>
							</form:select>
						</div>
						<label>Tracking Number</label>
						<div class="input-control text size1">
							<form:input type="text" value="" placeholder=""
								path="trackNumber" />
							<button class="btn-clear" tabindex=-1 type="button"></button>
						</div>
						<label>Issued Date</label>
						<div class="input-control text siez1">
							<form:input type="text" placeholder="yyyy/mm/dd"
								path="issuedDate" />
							<button class="btn-clear" tabindex=-1 type="button"></button>
						</div>
						<input type="submit" value="Add" /> <input type="reset"
							value="Clear" />
					</fieldset>
				</form:form>
			</div>
		</div>
	</div>

這樣大概就可以run看看了,啟動Tomcat後當打入網址http://localhost:8080/SpringMVC/add,但不幸的.....log4j顯示訊息顯示

22:35:10 [http-nio-8080-exec-3] DispatcherServlet - DispatcherServlet with name 'dispatcher' processing GET request for [/SpringMVC/add]
22:35:10 [http-nio-8080-exec-3] RequestMappingHandlerMapping - Looking up handler method for path /add
22:35:10 [http-nio-8080-exec-3] RequestMappingHandlerMapping - Did not find handler method for [/add]
22:35:10 [http-nio-8080-exec-3] PageNotFound - No mapping found for HTTP request with URI [/SpringMVC/add] in DispatcherServlet with name 'dispatcher'
22:35:10 [http-nio-8080-exec-3] DispatcherServlet - Successfully completed request

這個訊息似乎是Controller沒有註冊到,以致於沒有找到handle mapping URL的方法,稍微檢查一下MVCConfig,確認controller的package已有被component scan。

@Configuration
@EnableWebMvc
@ComponentScan(basePackages={"tw.blogger.springtech.springmvc.controller, tw.blogger.springtech.springmvc.model"})
public class MVCConfig extends WebMvcConfigurerAdapter{
	....
}

今天先到這吧,除錯看看,第一次用Java Config真的不太順利,如果還是找不到原因,就換回XML組態檔的方式試試看。


上一篇
[Model]Spring MVC Repository及Service Annotation介紹
下一篇
[Controller]混用xml組態檔及Java Config,"Handler Method Not Found"問題暫時解決
系列文
無痛學習SpringMVC與Spring Security31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言