springmvc_day05_

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35537301/article/details/82499932

@RequestMapping的使用

  • 放在方法上使用:URL到方法之间的映射
  • 放在类上使用,多一级目录访问,分模块化管理
  • 限制请求方式访问

Controller返回值类型

ModelAndView

  • Model : 模型,封装数据
  • View  :视图,封装视图地址用的

String

简单String类型

不包含关键字:forward,redirect关键字的,被称为是简单类型的String

默认为视图名称,走视图解析器

复杂String类型

包含关键字的:forward,redirect

    URL Request域 传递参数
forward 请求转发 不变 不变 Request,Model
redirect 重定向 Session,Model

说明

  • Model底层是基于Request域来开发的,只封装了Request.setArr***(),
  • Request域变了以后不能传递参数,但是Model可以
  • Model重定向的情况下给后面加了?参数
  • Model不能接收请求参数,Model传递参数就行

void 类型

在企业中不用!!!

SpringMVC异常处理

运行时异常(系统异常)

BUG

int i = 1/0;

预期异常

根据我们的业务参数非法输入的这种异常被称为预期异常

捕获异常类:在容器中存在的,随时等待捕获异常!

步骤

  • 编写异常类
  • 编写捕获异常类(实现HandlerExceptionResolver接口)
  • springmvc配置文件中配置捕获异常类

案例

package com.itheima.exception;

/**
 * @ClassName: ItemException
 * @Description:异常类
 */
public class ItemException extends Exception{

	private String message;

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public ItemException() {
		super();
	}
	
	public ItemException(String message) {
		super();
		this.message = message;
	}

	
}
package com.itheima.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

/**
 * @ClassName: GlobalException
 * @Description:捕获异常
 * @author jsz
 * @date 2018年9月8日
 */
public class GlobalException implements HandlerExceptionResolver {

	@Override
	public ModelAndView resolveException(HttpServletRequest requset, HttpServletResponse response, Object arg2,
			Exception exc) {
		ItemException exception = null;

		// 判断捕获的异常是否为自定的商品异常
		if (exc instanceof ItemException) {
			exception = (ItemException) exc;
		} else {
			// 是系统异常
			// 企业化操作:
			// 1、通过栈中获取异常信息,写入日志
			// 2、发短信给维护人员,获取开发者
			// 3、发邮件维护人员,获取开发者

			exception = new ItemException("不好意思,系统繁忙请稍后重试...");
		}

		ModelAndView mv = new ModelAndView();
		// 封装数据
		mv.addObject("message", exception.getMessage());
		// 返回页面
		mv.setViewName("error");
		return mv;
	}

}
<!-- 配置捕获异常类 -->
<bean class="com.itheima.exception.GlobalException"></bean>

图片上传

图片服务器

  • 阿里云——OSS文件存储
  • 七牛云存储
  • FSDTDFS

Tomcat服务器

能不能直接访问图片,能

但是Nginx服务器负载均衡的时候,有的服务器会访问不到图片

什么实现图片上传

SpringMVC帮我们实现了图片上传的接口,但是没有实现,谁来实现?第三方jar:两个

我们需要在SpringMVC核心配置文件中配置图片上传的属性

步骤

  • 页面提交from表单的时候,enctype = "multipart/from-data"
  • 在方法形参中接收 MultiPartFile 形参名必须和input type = file name属性名一致
  • 获取文件全名
  • 截取文件后缀名
  • 起别名+后缀名
  • 写入磁盘
  • 保存数据库

案例

页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>修改商品信息</title>

</head>
<body> 
	<!-- 上传图片是需要指定属性 enctype="multipart/form-data" -->
	<form id="itemForm" action="${pageContext.request.contextPath }/updateItem.action" method="post" enctype="multipart/form-data">
		<input type="hidden" name="id" value="${item.id }" /> 修改商品信息:
		<table width="100%" border=1>
			<tr>
				<td>商品名称</td>
				<td><input type="text" name="name" value="${item.name }" /></td>
			</tr>
			<tr>
				<td>商品价格</td>
				<td><input type="text" name="price" value="${item.price }" /></td>
			</tr>
			 
			<tr>
				<td>商品生产日期</td>
				<td><input type="text" name="createtime"
					value="<fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/>" /></td>
			</tr>
		
			<tr>
				<td>商品图片</td>
				<td>
					<c:if test="${item.pic !=null}">
						<img src="/pic/${item.pic}" width=100 height=100/>
						<br/>
					</c:if>
					<input type="file"  name="pictureFile"/> 
				</td>
			</tr>
			
			<tr>
				<td>商品简介</td>
				<td><textarea rows="3" cols="30" name="detail">${item.detail }</textarea>
				</td>
			</tr>
			<tr>
				<td colspan="2" align="center"><input type="submit" value="提交" />
				</td>
			</tr>
		</table>

	</form>
</body>

</html>

controller

package com.itheima.controller;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.itheima.exception.ItemException;
import com.itheima.pojo.Items;
import com.itheima.pojo.QueryVo;
import com.itheima.service.ItenService;

@Controller
public class ItemController {

	@Autowired
	private ItenService itemService;

	/**
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("itemEdit")
	public String itemEdit(HttpServletRequest request, Model model) throws Exception {// Model:模型,封装数据传递用的
		// 获取参数
		String idStr = request.getParameter("id");
		// 根据商品ID查询商品信息
		Items items = itemService.findItemById(Integer.parseInt(idStr));

		if (items == null) {
			throw new ItemException("不好意思,没有找到商品");
		}
		// 封装数据传给页面
		model.addAttribute("item", items);

		return "editItem";
	}

	
	/**
	 * @MethodName:updateItem
	 * @Description:
	 * @param pictureFile
	 * @param item
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("updateItem")
	public String updateItem(MultipartFile pictureFile, Items item, Model model) throws Exception {
		@RequestMapping("updateItem")
	public String updateItem(MultipartFile pictureFile, Items item, Model model) throws Exception {
		// 获取上传的图片名称
		String fileName = pictureFile.getOriginalFilename();
		// 获取图片的后缀名
		String houzhui = fileName.substring(fileName.lastIndexOf("."));
		// 起别名
		String newFileName = UUID.randomUUID().toString() + houzhui;
		// 写入磁盘
		pictureFile.transferTo(new File("D:/picture"));
		// 保存
		item.setPic(newFileName);
		// 根据商品ID修改商品信息
		itemService.updateItemById(item);
		// 请求转发到商品修改页面
		model.addAttribute("id", item.getId());
		// 当重定向本Controller中的方法的话,不用加/
		return "redirect:itemEdit.action";
	}

}

JSON数据交互

注解驱动下的数据交互

SpringMVC帮我们写了json数据交互的接口但是没有实现,谁来实现的?第三方jar:三个

只要我们配置了注解驱动那么就和SpringMVC框完美结合了,不用再SpringMVC核心配置问中配置了

常用注解

  • @RequestBody

作用:

读取http请求的内容(字符串),通过springmvc提供的HttpMessageConverter接口将读到的内容(json数据)转换为java对象并绑定到Controller方法的参数上

把json数据转成java对象,根据json中Key和对象属性之间映射的

  • @ResponseBody

将Controller的方法返回的对象,通过springmvc提供的HttpMessageConverter接口转换为指定格式的数据如:json,xml等,通过Response响应给客户端

把java对象转成json数据

案例

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.4.4.min.js"></script>
<title>查询商品列表</title>
<script type="text/javascript">
		function requestJSON(){
			$.ajax({
				type:"post",
				url:"${pageContext.request.contextPath }/requestJson.action",
				contentType:"application/json;charset=utf-8",
				data:'{"name":"测试商品","price":99.9}',
				success:function(data){
					alert(data);
				}
			});
		}

</script>
</head>
<body> 
<form action="${pageContext.request.contextPath }/item/queryitem.action" method="post">
查询条件:
<table width="100%" border=1>
<tr>
<td><input type="button" value="requestJSON" onclick="requestJSON()"/></td>
<td><input type="submit" value="查询"/></td>
</tr>
</table>
商品列表:
<table width="100%" border=1>
<tr>
	<td>商品名称</td>
	<td>商品价格</td>
	<td>生产日期</td>
	<td>商品描述</td>
	<td>操作</td>
</tr>
<c:forEach items="${itemList }" var="item">
<tr>
	<td>${item.name }</td>
	<td>${item.price }</td>
	<td><fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/></td>
	<td>${item.detail }</td>
	
	<td><a href="${pageContext.request.contextPath }/itemEdit.action?id=${item.id}">修改</a></td>

</tr>
</c:forEach>

</table>
</form>
</body>

</html>
package com.itheima.controller;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.itheima.exception.ItemException;
import com.itheima.pojo.Items;
import com.itheima.pojo.QueryVo;
import com.itheima.service.ItenService;

@Controller
public class ItemController {

	@Autowired
	private ItenService itemService;

	@RequestMapping("list")
	public String itemList(Model model) {
		List<Items> list = itemService.findAllItem();
		// 封装数据传给页面
		model.addAttribute("itemList", list);
		return "itemList";
	}
	
	@RequestMapping("requestJson")
	@ResponseBody
	public Items requestJson(@RequestBody Items item){
		return item;
	}

}

不使用注解驱动

需要给处理器适配器配置json转换器,参考之前学习的自定义参数绑定

<!--处理器适配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
	<property name="messageConverters">
		<list>
			<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
		</list>
	</property>
</bean>

 

猜你喜欢

转载自blog.csdn.net/qq_35537301/article/details/82499932