2019.7.12 下午
自定义异常(说明)
//Form表单提交 自定义抛出异常
@PostMapping(value = "userLogin")
@ResponseBody
public User userLogin(User user){
User userLogin = userService.queryUserByNameAndPassword(user);
if (userLogin==null){
throw new UserNameAndPasswordException("用名字,密码不存在!");
}
return userLogin;
}
//自定义异常类
public class UserNameAndPasswordException extends RuntimeException{
public UserNameAndPasswordException(String message) {
super(message);
}
}
@Test
public void testUserLogin(){
String url="http://localhost:8088/UserProject/FormUserManager/userLogin";
LinkedMultiValueMap<Object, Object> formDate = new LinkedMultiValueMap<>();
formDate.add("name","zhangsan");
formDate.add("password","1234567");//密码错误时候抛出自定义异常
User user = restTemplate.postForObject(url, formDate, User.class);
System.out.println(user);
}
[外链图片转存失败(img-5At7oefo-1563978161393)(C:\Users\Administrator\Desktop\大数据项目实战\assets\1562933455708.png)]
restful风格测试请求时 直接抛出500null,需要改进
自定义异常(Form表单提交的解决方法)
在url上 重写ResponseErrorHandler中的两个方法
restTemplate.setErrorHandler(new ResponseErrorHandler() {
@Override
//是否抛出异常 返回false
public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException {
System.out.println(clientHttpResponse.getStatusCode());
return false;
}
@Override
public void handleError(ClientHttpResponse clientHttpResponse) throws IOException {
System.out.println("出错了"+clientHttpResponse.getStatusCode());
}
});
此时报错信息为500,但是并不表示服务器错误,只是自定义错误异常
500 INTERNAL_SERVER_ERROR
User{id=null, name=‘null’, sex=null, password=‘null’, birthday=null, photo=‘null’}
改进方法:
- 自定义类 extends HandlerExceptionResolver
此方法返回值为ModelAndView数据加视图 不适合restful风格测试 错误!!!
- 自定义ErrorMessage实体类并实现序列化
public class ErrorMessage implements Serializable {
private Integer errorCode;
private String message;
}
//在controller中加入以下方法
@ExceptionHandler(value = UserNameAndPasswordException.class)
public ErrorMessage handlerError(UserNameAndPasswordException ex){
return new ErrorMessage(1000,ex.getMessage());
}
{"errorCode":1000,"message":"用户名或者密码不正确"} //用idea 发送post测试 返回错误信息 但是此方法缺点在于上述方法必须放置在需要绑定的controller(userLogin)一起,否则检测不到
idea发送请求不能改变编码格式 测试中文会报错
自定义异常(改进)
在controller中定义以下内容 则全局可用 适用于视图 + Restful风格通用
@RestControllerAdvice//等价于ControllerAdvice + ResponseBody
public class CustomExceptionHandler {
@ExceptionHandler(value = UserNameAndPasswordException.class)
public ErrorMessage handlerError(UserNameAndPasswordException ex){
return new ErrorMessage(1001,ex.getMessage());
}
}
{"errorCode":1000,"message":"用户名或者密码不正确"}
如果ajax发送请求 此时为200 正确运行,此时会产生回掉函数,应该自定义错误码
在上述内容中加入此标签即可
@ResponseStatus(code = HttpStatus.BAD_REQUEST)//默认400
[外链图片转存失败(img-EcKVjlqv-1563978161398)(C:\Users\Administrator\Desktop\大数据项目实战\assets\1562936494308.png)]
springboot,ajax提交user对象+文件上传,restful风格
引入jquery 自闭和标签会无效
//User数据写死 测试文件上传
<script>
$(function(){
$("#rest_register_btn").click(function(){
var formData = new FormData();
//获取form表单中的input标签,[0]把jquery对象变成dom对象,files[0]获取第一个文件
var file=$("#rest_register_form input[type='file']")[0].files[0]
formData.append("multipartFile",file);
var user = JSON.stringify({
"name":"zhangsan",
"password":"1234567"
});
//这里包装 可以直接转换成对象
formData.append("user",new Blob([user],{type:"application/json"}));
$.ajax({
url:"${pageContext.request.contextPath}/RestUserManager/user",
type:"post",
contentType:false,//忽略contentType
processData:false,//取消序列化,formData本来就是序列化好的
dataType:"json",
data:formData,
success:function(data){
alert(data);//弹出数据 Object object 需要转换成json对象
},
error:function(){
alert("出错了")
}
})
})
})
</script>
jquery 表单 对象转换为 json对象
自定义 jquery.extend.js
var json = $("#rest_register_form").serializeForm2JSON();//通过id选择器调用自定义方法
$.fn.extend({
serializeForm2JSON:function () {
if(this.length > 1){
alert("你只能用ID选择器,选择唯一一个表单元素")
return
}
var inputs = $(this[0]).serializeArray();
var map = {};
inputs.forEach(function (item,index) {
if (map[item.name]) { //返回json中有该属性
if (!map[item.name].push) { //将已存在的属性值改成数组
map[item.name] = [map[item.name]];
}
map[item.name].push(item.value || ''); //将值存放到数组中
}else { //返回json中没有有该属性
map[item.name] = item.value || ''; //直接将属性和值放入返回json中
}
});
return JSON.stringify(map);
}
})
- 调整jps中代码
<script>
$(function(){
$("#rest_register_btn").click(function(){
var formData = new FormData();
//获取form表单中的input标签,[0]把jquery对象变成dom对象,files[0]获取第一个文件
var file=$("#rest_register_form input[type='file']")[0].files[0]
var user = $("#rest_register_form").serializeForm2JSON();
formData.append("multipartFile",file);
/*var user = JSON.stringify({
"name":"zhangsan",
"password":"1234567"
});*/
//这里包装 可以直接转换成对象
formData.append("user",new Blob([user],{type:"application/json"}));
$.ajax({
url:"${pageContext.request.contextPath}/RestUserManager/user",
type:"post",
contentType:false,//忽略contentType
processData:false,//取消序列化,formData本来就是序列化好的
dataType:"json",
data:formData,
success:function(data){
alert("提交成功"+data);
},
error:function(){
alert("出错了")
}
})
})
})
</script>
实现头像上传时 旁边位置图片通过本地位置回显
<img id="photoImg" width="50px" alt="用户图"/>
- 自定义jquery
imgShow:function (options) {
$(this).change(function () {
for (var i = 0; i < event.target.files.length; i++) {
var file = event.target.files.item(i);
if (!(/^image\/.*$/i.test(file.type))) {
continue; //不是图片 就跳出这一次循环
}
//实例化FileReader API
var freader = new FileReader();
freader.readAsDataURL(file);
freader.onload = function (e) {
console.log(e.target.result);
$("#"+options.imageId).attr("src", e.target.result);
}
}
})
}
- 前端jsp调用方法
$("#rest_register_form input[type='file']").imgShow({
imageId:"photoImg"
})