SSM框架---SpringMVC的图片上传&json数据交互&异常处理思路(七)

目录

一、图片上传

1、JSP代码

2、springmvc框架的配置

3、controller的要素

二、json交互

1、页面引入

2、springmvc框架的配置:即支持

3、controller的要素

三、ssm框架的异常处理思路

1、自定义异常处理器,继承HandlerExceptionResolver 接口

2、自定义错误页面

3、springmvc.xml异常处理器配置

4、异常测试:在controller、service、dao层均适用

5、结果展示


一、图片上传

1、文件上传页面要素
    1)表单的提交方式method一定是post,且enctype的值一定是multipart/form-data:<form action="" method="post" enctype="multipart/form-data">
    2) input的类型一定是file:<input type="file"  name="pictureFile"/> 
2、springmvc框架的要素
   1)需要添加两个jar  commons-io.jar  commons-fileupload.jar
   2)  在springmvc.xml容器中配置文件解析器   
3、controller的要素
   1)方法中绑定形参的参数类型为 MultipartFile ,参数的名字要和 input的name属性值保持一致:public String updateitem(MultipartFile pictureFile){...}
   2)获取上传文件的完整名称(带扩展名):String pictureFile_name = pictureFile.getOriginalFilename();//XXX.png


1、JSP代码

<form action="${pageContext.request.contextPath }/updateitem.do" method="post" enctype="multipart/form-data">
	...
	<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>
	...

2、springmvc框架的配置

导入jar包:commons-fileupload-1.2.2.jar和commons-io-2.4.jar

springmvc-servlet.xml
<!-- 文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 设置上传文件的最大尺寸为5MB -->
    <property name="maxUploadSize">
        <value>5242880</value>
    </property>
</bean>

3、controller的要素

@RequestMapping("/updateitem")
public String updateitem(Items item,Model model,MultipartFile pictureFile) throws IllegalStateException, IOException{
	
	//1、获取上传文件的完整名称(带扩展名)
	String pictureFile_name = pictureFile.getOriginalFilename();//XXX.png

	//2、使用UUID创建一个随机数,作为即将保存图片的名字 UUID+后缀名
	String newFileName = UUID.randomUUID().toString()+pictureFile_name.substring(pictureFile_name.lastIndexOf("."));
	//6ec24d06-746d-4f76-8c8b-670cd635b94e.png
	
	//3、创建上传地址
	File upload = new File("E:\\上传地址\\upload\\"+newFileName);
	
	//4、文件的保存,spring框架封装的上传方法:transferTo()
	pictureFile.transferTo(upload);
	
	//5、将新的图片文件名6ec24d06-746d-4f76-8c8b-670cd635b94e.png提交数据库,只上传文件名,不上传地址,为了以后迁移方便
	item.setPic(newFileName);
	
	itemService.update(item);//更新数据库
	
	//重定向或请求转发
	//return "redirect:list.do";//重定向
	return "forward:list.do";//请求转发
}

二、json交互

  @ResponseBody(重点)  //作用 把即将返回的对象转成json字符串并且回写到浏览器
  @RequestBody(了解,没人用)   //强制jsp的ajax方法请求的参数是json对象  public Items Xxx(@RequestBody Items items){...}与contentType:'application/json;charset=utf-8',

  @ResponseBody的实践

1、页面引入
    1)页面引入js方法:<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.4.4.min.js"></script>
    2) ajax方法:$.ajax({});
2、springmvc框架的配置
   1)需要添加三个jar  jackson-annotations-2.4.0.jar、jackson-core-2.4.2.jar、jackson-databind-2.4.2.jar
   2)  在springmvc.xml容器中配置注解映射的支持,支持json
3、controller的要素
   1)对方法添加@ResponseBody注解


1、页面引入

<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
 function save(){
         alert($("#itemForm").serialize());
	//Ajax异步提交
	//$("#itemForm").serialize()提交form表单的值,格式:id=9&name=%E5%8D%8E&price=9000&createtime=2019-12-16
	$.ajax({
		url:'${pageContext.request.contextPath }/updateitemAjax2Temp.do',//必传
		type:'post',//必传,默认提交是get
		dataType:'json',//必传,与springmvc框架的@ResponseBody注解一起使用时必须为json,否则后台接收不到数据
		data:$("#itemForm").serialize(),//必传
		//contentType:'application/json;charset=utf-8',//默认类型:application/x-www-form-urlencoded;charset=UTF-8
		success:function(data){
			alert(data.name);
			// data :{"success":true|false,"message":"操作成功"|“操作失败”}
			//if(data.success){
				//location.href="${pageContext.request.contextPath }/list.do";
			//}else{
				//alert(data.message); 
			//}
		},
		error:function(err){
			alert("error");
		}
	});
}

function updateCustomer() {
	$.post("<%=basePath%>/update.do",$("#edit_customer_form").serialize(),function(data){
// 		data 返回boolean
		if(data){
			alert("客户信息更新成功!");
			window.location.reload();//当前页面重新加载
		}else{
			alert("客户信息更新失败!");
		}
	});
}

function deleteCustomer(id) {
	if(confirm('确实要删除该客户吗?')) {
		$.post("<%=basePath%>/delete.do",{"id":id},function(data){
			if(data){
				alert("客户删除成功!");
				window.location.reload();//当前页面重新加载
			}else{
				alert("客户删除失败!");
			}
		});
	}
}
</script>
<input type="button" onclick="save()" value="提交" />

2、springmvc框架的配置:<mvc:annotation-driven/>即支持

<!--  加载注解驱动 目的:加载新版本的处理器映射器、处理器适配器,同时支持json -->
<mvc:annotation-driven/>
或者显式的这样写:
<!-- 加载注解驱动 目的:加载新版本的处理器映射器、处理器适配器,同时支持json -->
<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
    </mvc:message-converters>
</mvc:annotation-driven>

3、controller的要素

@RequestMapping("/updateitemAjax")
@ResponseBody
public Items updateitemAjax(Items item){
//		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("success", true);
//		map.put("message", "操作成功");
	
	System.out.println("==updateitemAjax=="+item);
	return item;
}

三、ssm框架的异常处理思路

Web工程中一般都是三层结构,dao、service、controller,系统中无论哪一层发送异常都可以直接throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理。

1、自定义异常处理器,继承HandlerExceptionResolver 接口

public class MyHandlerExceptionResolver implements HandlerExceptionResolver {
	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object method,Exception exception) {
//		跳转到错误页面
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("errorMessage", exception.getMessage());
		modelAndView.setViewName("error");
		return modelAndView;
	}
}

2、自定义错误页面

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>error页面</title>
</head>
<body>
 <h1>由于您的操作造成系统异常,错误信息如下,请转告开发工程师:<br/></h1>
 ${errorMessage }
</body>
</html>

3、springmvc.xml异常处理器配置

在springmvc.xml中添加:
<!-- 配置自定义的异常处理器 -->
<bean class="com.ly.ssm.exception.MyHandlerExceptionResolver"/>

4、异常测试:在controller、service、dao层均适用

controller中添加:在service、dao层均适用
//异常测试
if(items == null){
    int i = 1/0;
}
//异常测试 over

5、结果展示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值