SpringMVC框架(1)之(1.3 注解开发&Controller方法返回值)

一、 注解开发基础:

1. @RequestMapping 注解(在Controller类上或方法上,用于指定 url和请求方式):
1. 设置方法对应的URL(一个方法对应一个URL);
2. 设置请求的根路径;(eg:http:// localhost:8080/project/book/deleteBook)
3. 限制请求方式: GET/POST
@RequestMapping(value="/editItems",method=RequestMethod.GET/POST)

2. @RequestParam 注解(在方法的参数上,用于参数绑定):
如果 request请求参数与 Controller方法中的形参名一致,适配器自动进行参数绑定;
如果不一致,使用@RequestParam 注解 value属性 指明请求参数名;required属性 默认为 true,若没有参数则报错;defaultValue属性 设置默认值;
(即item_id=1)(eg:下 3.1 ItemsController.java
public void editItems(HttpServletRequest request,HttpServletResponse response, @RequestParam(value=“item_id”,required=true,defaultValue=“1”) Integer id ) throws Exception);
3. @ModelAttribute 注解(数据回显;① 可用于方法的参数上,用于参数绑定,表示将请求的 POJO数据放到 model中; ② 用于方法上,将公用的取数据的方法返回值传到页面,不需要在每个 Controller方法中通过 Model传数据。):
1.需求:表单提交出现错误,重新回到表单,用户填写的数据再次回显在页面;
① 简单类型数据回显: 形参-Model;
② POJO类型数据回显:
        方法一:Model(eg:model.addAttribute"item",itemsCustom);)
        方法二:使用注解 @ModelAttribute(value=“item”),作用:将请求的POJO数据放入到 Model中进行回显,value指明 JSP页面用于显示时所用的 key
如果形参名与 JSP页面中的 key相同,@ModelAttribute注解可以省略;
2.需求:按照类别查询(eg:3. itemsList.jsp 页面中添加类别显示)。
@ModelAttribute(value=“item”) 将方法返回值传到页面,将公用的取数据的方法返回值传到页面
优点:不需要用在每个 Controller方法中通过Model传数据
4.@RequestBody 注解:(用于Controller中方法的参数上,表示请求类型是 JSON格式数据;如果不是 JSON格式数据,则无需说明)将请求的 JSON数据转成 JAVA对象;
4’.@ResponseBody注解:(在 Ajax时,用于Controller中相应的方法上,方法可返回 POJO对象和 List集合; 用在方法的返回类型参数前,表示返回即响应 JSON格式数据;)将 JAVA对象转成 JSON数据输出;
eg:

//请求 JSON,响应 JSON
@RequestMapping("/requestJson")
	public @ResponseBody ItemsCustom requestJson(@RequestBody ItemsCustom itemsCustom)throws Exception{
		return itemsCustom;
	}
//请求 Key/Value,响应 JSON
	@RequestMapping("/responseJson")
	public @ResponseBody ItemsCustom responseJson(ItemsCustom itemsCustom)throws Exception{
		return itemsCustom;
	}

二、 Controller方法返回值:

1. ModelAndView

2. 返回字符串:(如果Controller返回jsp页面,方法返回值为字符串,则为最终的逻辑视图名,模型数据填充在 Model model)(eg:3.1 ItemsController.java中
① public String editItems(Model model) throws Exception;
model.addAttribute(“item”,itemsCustom);
③ return “editItems”;
);

3.返回 void(如果使用request转向页面,指定完整路径)
① public void editItems( HttpServletRequest request,HttpServletResponse response ,Integer id) throws Exception;(此处用 Integer包装类,不用 int,因为 int无法传空值,若用 int则传空值时会报错;)
request.setAttribute(“item”,itemsCustom);
③ request.getRequestDispatcher("/WEB-INF/jsp/editItems.jsp").forward(request,response);

4.redirect 重定向(方法返回值String “redirect:url”)
① public String editItems(Model model) throws Exception;
return “redirect:queryItems.action”;

5.forward 转发(方法返回值String “forward:url”)
① public String editItems(Model model) throws Exception;
return “forward:queryItems.action”;

三、 参数绑定过程:

早期SpringMVC是使用PropertyEditor属性编辑器进行参数绑定(仅支持字符串传入);后期使用Convert转换器进行参数绑定(支持任意数据类型转换);
适配器 ——>Handler(以方法为单位进行编写,方法形参);

默认支持的参数类型:
HttPServletRequest、HttpServletResponse、HttpSession、Model

需求:商品信息修改

1. 操作流程:

1.在商品列表页面中点击修改按钮;
2.打开商品修改页面,显示当前商品信息;
    (根据商品 ID查询)
3.修改商品信息,点击提交;
    (更新商品信息)

【1. mapper:】 使用逆向工程生成(ItemsMapper.xml、ItemsMapper.java);
【2. service:】
【3. controller:】
【4. jsp:】

【2. service:】
2.1 ItemsService.java
(接口:更新商品信息方法中:id:要修改的商品的 id、itemsCustom:要修改的商品;)

public interface ItemsService{
	//查询所有商品
	public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo)throws Exception;
	//根据ID查询商品
	public ItemsCustom findItemsById(int id)throws Exception;
	//更新商品信息
	public void updateItems(Integer id,ItemsCustom itemsCustom)throws Exception;
}

2.2 ItemsServiceImpl.java
(查询所有商品的方法是在 itemsCustomMapper中; 根据ID查询商品、更新商品信息两个方法是在 itemsMapper.java(逆向工程自动生成的方法)中,所以也要注入 itemsMapper; 根据ID查询商品的方法中 itemsMapper.selectByPrimaryKey返回的是 Items类型,方法本身要返回的是 ItemsCustom类型:可以强转,但当需要能查询其他相关信息时,强转不适合,所以:先new、再调用方法将 items属性的值 copy到 itemsCustom中;)

public class ItemsServiceImpl implements ItemsService{
	@Autowired 
	private ItemsCustomMapper itemsCustomMapper;
	@Autowired 
	private ItemsMapper itemsMapper;

	public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo)throws Exception{
		return itemsCustomMapper.findItemsList(itemsQueryVo); //查询所有商品
	}
	public ItemsCustom findItemsById(int id)throws Exception{
		Items items=itemsMapper.selectByPrimaryKey(id);
		//需求:能查询其他相关信息,强转不适合;所以:先new、再将items属性的值copy到itemsCustom中
	    ItemsCustom itemsCustom=new ItemsCustom();
	    BeanUtils.copyProperties(items,itemsCustom);
		return itemsCustom;
	}
	public void updateItems(Integer id,ItemsCustom itemsCustom)throws Exception{
		//写业务代码:如希望对关键业务数据进行非空校验.参数要传一个id值(是希望能修改的商品的id)
		if(id=null){
			//抛异常,提示调用接口的用户,id不能为空
		}
		itemsMapper.updateByPrimaryKey(itemsCustom);
	}
}

itemsCustom.java

public class ItemsCustom extends Items{
}

【3. controller:】
3.1 ItemsController.java
(通过@RequestMapping注解的 url请求modelAndView.setViewName("?")中的 ?;jsp页面拿到modelAndView .addObject (“item”,itemsCustom)中的 item;)

@Controller
@RequestMapping("/items")
public class ItemsController{
	@Autowired
	private ItemsService itemsService;

	@RequestMapping("/queryItems")
	public ModelAndView queryItems() throws Exception{
		//调用service查询出的商品,要用到itemsService
		List<ItemsCustom> itemList=itemsService.findItemsList();
		ModelAndView modelAndView=new ModelAndView();
		modelAndView.addObject("items",itemsList);//jsp页面拿到items
		modelAndView.setViewName("itemsList");
		return modelAndView;
	}
	/* @RequestMapping(value="/editItems",method=RequestMethod.GET)
	public ModelAndView editItems() throws Exception{
		//通过id查询商品
		ItemsCustom itemsCustom=itemsService.findItemById(1);
		ModelAndView modelAndView=new ModelAndView();
		modelAndView.addObject("item",itemsCustom);//jsp页面拿到item
		modelAndView.setViewName("editItems");
		return modelAndView;
	}*/
	/* @RequestMapping(value="/editItems",method=RequestMethod.GET)
	public String editItems(Model model) throws Exception{
		//通过id查询商品
		ItemsCustom itemsCustom=itemsService.findItemById(1);
		model.addAttribute("item",itemsCustom);
		return "editItems";
	}*/
	/* @RequestMapping(value="/editItems",method=RequestMethod.GET)
	public void editItems(HttpServletRequest request,HttpServletResponse response,
		@RequestParam(value="item_id",required=true,defaultValue="1")
		Integer id) throws Exception{
		//通过id查询商品
		ItemsCustom itemsCustom=itemsService.findItemById(id);
		request.setAttribute("item",itemsCustom);
		// 如果使用request转向页面,要指定完整路径
		request.getRequestDispatcher("/WEB-INF/jsp/editItems.jsp").forward(request,response);
	} */
	/* @RequestMapping(value="/editItems",method=RequestMethod.GET)
	public String editItems(Model model) throws Exception{
		return "redirect:queryItems.action"; //重定向
		//return "forward:queryItems.action"; //转发
	}  */
}

【4. jsp:】
4.1 itemsList.jsp
(查询到 items,遍历出来;再根据 item.id 修改;)

<body>
    <table width="100%" border="1">
       <tr><td>商品名称</td><td>商品价格</td><td>商品描述</td><td>操作</td></tr>
       <c:forEach items="${items}" var="item">
          <tr><td>${item.name}</td><td>${item.price}</td><td>${item.detail}</td>
              <td>
                <a href="${pageContext.request.contextPath}/items/editItems.action?id=${item.id}">修改</a>
              </td>
          </tr>
       </c:forEach>
    </table>
</body>

4.2 editItems.jsp

<body>
  <form action="">
  <table>
     <tr><td>商品名称:</td>
         <td><input type="text" name="name" value="${item.name}"></td></tr>
     <tr><td>商品价格:</td>
         <td><input type="text" name="name" value="${item.price}"></td></tr>
     <tr><td>商品描述:</td>
         <td><input type="text" name="name" value="${item.detail}"></td></tr>
     <tr><td colspan="2" align="center"><input type="submit" value="提交"/></td></tr>
  </table>
  </form>
</body>

3. @ModelAttribute注解(数据回显;在方法的参数上,用于参数绑定,表示将请求的 POJO数据放到 model中):
简单类型数据回显:1. ItemsController.java 中 public String editItemsSubmit()方法中将 id添加到 model中(model.addAttribute(“id”,id)); 2. editItems.jsp 中 hidden隐藏域中 value="$ {id}" 得到 id。但页面显示的其他字段name、price、createtime、detail(如value=" $ {item.detail}")等一开始是从 public String editItems()方法的 model中得到的,是 item,所以要想从一开始进入此页面 id也显示,则隐藏域中 value="$ {item.id}";若想 jsp页面隐藏域显示 value="$ {id}",则 public String editItems()方法中将 id添加到 model(即model.addAttribute(“id”,id); )
POJO类型数据回显:方法一:1. ItemsController.java 中 public String editItemsSubmit()方法中将 itemsCustom添加到 model中(即model.addAttribute(“item”,itemsCustom),key为 item,value为 itemsCustom) 方法二:1. ItemsController.java 中 public String editItemsSubmit()方法中直接将参数 ItemsCustom itemsCustom改为 ItemsCustom item,直接添加 @ModelAttribute 注解(表示将此形参 item添加到Model中),再注释掉 /* model.addAttribute(“item”,itemsCustom); */;
若将 1. ItemsController.java 中 public String editItemsSubmit()方法中参数(ItemsCustom item)改为(ItemsCustom itemsCustom)且去掉@ModelAttribute注解; public String editItems()方法中 model.addAttribute(“item”,itemsCustom)改为 model.addAttribute(“itemsCustom”,itemsCustom);
2. editItems.jsp 中 value="$ {item.xx}“改为 value=”$ {itemsCustom.xx}"

1. ItemsController.java

@Controller
@RequestMapping("/items")
public class ItemsController{
	@Autowired
	private ItemsService itemsService;
		
	@ModelAttribute(value="itemsType") //表示将itemsType添加到model中
	public Map<String,String> getItemsType(){
		Map<String,String> itemsType=new HashMap<String,String>();
		itemsType.put("001","数码");
		itemsType.put("002","服装");
		return itemsType;
	}	
	@RequestMapping(value="/editItems",method=RequestMethod.GET)
	public String editItems(Model model,Integer id) throws Exception{
		model.addAttribute("id",id);
		ItemsCustom itemsCustom=itemsService.findItemById(id);
		/*model.addAttribute("item",itemsCustom);*/
		model.addAttribute("itemsCustom",itemsCustom);
		return "editItems";
	}

	@RequestMapping(value="/editItemsSubmit")
	public String editItemsSubmit(Model model,Integer id,
	/*ItemsCustom itemsCustom*/ 
	/*@ModelAttribute(value="item") ItemsCustom item*/
	ItemsCustom itemsCustom) throws Exception{
		model.addAttribute("id",id);
		// model.addAttribute("item",itemsCustom);
		return "editItems";
	}  
}

2. editItems.jsp

<body>
  <form action="${pageContext.request.contextPath}/items/editItemsSubmit.action" method="post">
  <input type="hidden" name="id" value="${id}"/>
  <table>
     <tr><td>商品名称:</td>
         <td><input type="text" name="name" value="${item/itemsCustom.name}"></td></tr>
     <tr><td>商品价格:</td>
         <td><input type="text" name="price" value="${item/itemsCustom.price}"></td></tr>
     <tr><td>订购日期:</td>
         <td><input type="text" name="createtime" value="<fmt:formatDate value='${item/itemsCustom.createtime}' pattern="yyyy-MM-dd"/>"></td></tr>
     <tr><td>商品描述:</td>
         <td><input type="text" name="detail" value="${item/itemsCustom.detail}"></td></tr>
     <tr><td colspan="2" align="center"><input type="submit" value="提交"/></td></tr>
  </table>
  </form>
</body>

3. itemsList.jsp 页面中添加查询按钮,以及下拉框,点击下拉框时内容显示类别;1. ItemsController.java 类中添加 public Map<String,String> getItemsType() 方法,方法上添加 @ModelAttribute(value=“itemsType”) 注解,value指明 key;)
3. itemsList.jsp

<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<body>
    <table width="100%" border="1">
    <tr><td><input type="button" value="查询"/></td>
	    <td colspan="3">
		    <select>
			    <c:forEach items="${itemsType}" var="itemsType">
			    	<option value="${itemsType.key}">${itemsType.value}</option>
			    </c:forEach>
		    </select>
	    </td></tr>
       <tr><td>商品名称</td><td>商品价格</td><td>订购日期</td><td>商品描述</td><td>操作</td></tr>
       <c:forEach items="${items}" var="item">
          <tr><td>${item.name}</td>
              <td>${item.price}</td>
              <td><fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd"/></td>
              <td>${item.detail}</td>
              <td>
                <a href="${pageContext.request.contextPath}/items/editItems.action?id=${item.id}">修改</a>
              </td>
          </tr>
       </c:forEach>
    </table>
</body>

猜你喜欢

转载自blog.csdn.net/qq_41029923/article/details/84634506
今日推荐