SpringMVC的ajax操作
查看网络 如果有ajax xhr 说明需要在后台写ajax方法
json
用户查看
通过id查看
controller 接收前台信息id值 和前台是对应的
优化:异步请求 ajax 我希望点击查看的时候在就在下方展示
前台 ajax
后台 但是返回的json中文有问题 生日+时间格式也有问题
/* #######################用户查看以前ajax写法########################## */
@RequestMapping(value="/viewUser",method=RequestMethod.GET)
public void doviewUser(@RequestParam Long uid,Model model,
HttpServletResponse response)throws Exception{
User user = userService.getById(uid);
model.addAttribute("user", user);
String userJson = JSON.toJSONString(user);
response.getWriter().print(userJson);
}
ResponseBody 作用 将返回的结果 写入到响应体中 而不会由视图解析器进行解析 用于异步请求
使用ajax以后 解决json的中文乱码
治标不治本 produces 是string类型数据 用于设置响应格式 text/html;charset=UTF-8
@ResponseBody
@RequestMapping(value="/viewUser",method=RequestMethod.GET,
produces="application/json;charset=UTF-8")
public String doviewUser(@RequestParam Long uid) throws Exception {
User user = userService.getById(uid);
// String userJson = JSON.toJSONString(user);
String userJson = JSON.toJSONStringWithDateFormat(user, "yyyy-mm-dd");
return userJson;
}
时间格式 如果你非要用jsontoString
在实体类中添加注解
@JSONField(format="yyyy-MM-dd")
private Date birthday;
治本: 在核心配置文件springmvc-servlet.xml中进行配置
<!-- 开启注解驱动 更改处理器映射器为DefaultAnnotationHandlerMapping -->
<!--找StringHttpMessageConverter supportedMediaTypes List类型 -->
<mvc:annotation-driven>
<!-- 解决响应格式中文乱码 -->
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter ">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset="UTF-8"</value>
<value>application/json;charset="UTF-8"</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
扩展:
GET/articles/2 表示查看某一个文章
?这种的叫查询字符串
/* ############用户查看现在ajax写法---rest风格#####*/
//value里面的id随便起·· @pathVariable里面的参数名和id一致
//localhost:8080/day71/user/view/7
//PathVariable路径里面的变量
@ResponseBody
@RequestMapping(value="/view/{id}", method=RequestMethod.GET)
public String doviewUser(@PathVariable Long id) throws Exception {
//(@PathVariable(name="id") Long uid)
User user = userService.getById(id);
String userJson = JSON.toJSONString(user);
return userJson;
}
或者
#### 密码修改
dao 参数id
service 修改密码 旧密码检查 参数(id+旧密码)
controller 参数 旧密码
ajax中
出现了data.result 前端controller 说明是一个对象 或者是一个map集合