您的位置:首页 > 编程语言 > Java开发

springMVC教程中级(四)Controller中级篇2(传图、json)

2015-09-28 15:08 465 查看

一、前言

紧接上一章Controller中级篇1,这篇主要讲图片上传、requestBody和responseBody

二、图片上传

2.1 虚拟目录配置

我们图片等文件上传,在现实项目中,肯定是需要配置图片服务器专业存放的,以前那种存放在本机就out了。我就例举一样tomcat、jetty的springMVC图片上传。之前页眉配置过,一起来学习学习吧。关于服务器设置我会单独将几章节,大家一起学习吧,我也是边学习变分享吧。

2.1.1 配置jetty虚拟目录

在网上找了很久的哦,还是自己摸索来的,我用的jetty9,直接在webapp文件里面,加入一个任意名字的xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN"
"http://www.eclipse.org/jetty/configure_9_0.dtd">
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
<Set name="contextPath">/pic</Set>
<Set name="war">E:/java/ycypic</Set>
</Configure>

contextpath:为真实路径
war:真实路径(暂时这么用)

2.1.2 配置tomcat虚拟目录

在tomcat的conf/server.xml 里面修改虚拟目录,在host标签里面加一句:

<Context path="/pic" docBase="E:/java/ycypic" reloadable="true" debug="0">
</Context>
doBase:为真实路径
parh:真实路径

2.2 图片上传解析器配置

2.2.1 导入jar包

<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.4</version>
</dependency>


2.2.2 配置上传文件springmvc.xml

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

2.2.3 编写上传页面

要点1: form添加enctype="multipart/form-data",
要点2:file的name与controller形参一致:
<tr>
<span style="white-space:pre">	</span><td>商品图片</td>
<td><c:if test="${itemsCustom.pic !=null}">
<img src="/pic/${itemsCustom.pic}" width=100 height=100 />
<br />
</c:if> <input type="file" name="pictureFile" /></td>
</tr>


全部编辑商品editItem.jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" isELIgnored="false">
<title>修改商品信息</title>

</head>
<body>
<form id="itemForm" action="${pageContext.request.contextPath }/items/editItemSubmit" method="post">
<input type="hidden" name="id" value="${itemsCustom.id}"/>
<input type="hidden" name="pic" value="${itemsCustom.pic}"/>
修改商品信息:
<table width="100%" border=1>
<tr>
<td>商品名称</td>
<td><input type="text" name="name" value="${itemsCustom.name}"/></td>
</tr>
<tr>
<td>商品价格</td>
<td><input type="text" name="price" value="${itemsCustom.price}"/></td>
</tr>
<tr>
<td>商品生产日期</td>
<td><input type="text" name="createtime"
value="<fmt:formatDate value="${itemsCustom.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/>"/></td>
</tr>
<tr>
<td>商品图片</td>
<td>
<c:if test="${itemsCustom.pic!=null}">
<img src="/pic/${itemsCustom.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">${itemsCustom.detail}</textarea>
</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="提交"/>
</td>
</tr>
</table>

</form>
</body>

</html>

2.2.3 编写上传controller

要点1:pictureFile与我们jsp页面参数名称保证一直
要点2:我们的上传路径地址与我们的虚拟目录保持一致(一般通过propertity文件读取或者数据库读取)
/**
* 修改商品属性
* @return
*/
@RequestMapping("/editItemSubmit")
public String editItemSubmit(Integer id,@ModelAttribute(value="itemsCustom") ItemsCustom itemsCustom, MultipartFile pictureFile
) throws Exception {
//
if(pictureFile!=null){
//原始文件名称
String pictureFile_name =  pictureFile.getOriginalFilename();
//新文件名称
String newFileName = UUID.randomUUID().toString()+pictureFile_name.substring(pictureFile_name.lastIndexOf("."));

//上传图片
File uploadPic = new java.io.File("E:/java/ycypic"+newFileName);

if(!uploadPic.exists()){
uploadPic.mkdirs();
}
//向磁盘写文件
pictureFile.transferTo(uploadPic);
itemsCustom.setPic(newFileName);
}

itemsService.updateItem(id, itemsCustom);
//返回修改页面
// return "order/editItem";
//重定向  request数据无法共享,url地址栏会发生变化的 页面地址:editItemSubmit
return  "redirect:queryItems";
//转发   request数据可以共享,url地址栏不会变化 页面地址:queryItems
//return  "forward:queryItems";
}

2.2.3 乱码问题

注意:我在这里遇到乱码,因为url-pattern 是斜杠+星号,我都差点搞错,忘记加星号。整了好久
<!-- 设置servlet编码开始 -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 设置servlet编码结束 -->


三、Json格式转

我们日常用的都是json数据,特别是喜欢用空间的小伙伴,这就是json数据的转换。但是不知道你注意没有,我们的url拦截没有.action或者.do等,我们属于restful格式(后面讲)所以我们引入静态资源需要配置
3.0引入静态资源web.xml,引入js结尾的资源
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>


3.1引入jar包

<!--================json转换3人组文件上传(MappingJackson2HttpMessageConverter)==========-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.6.1</version>
</dependency>

3.2 配置springmvc.xml

依然是修改适配器
<!--3、=============================处理器适配器HandlerAdapter====================================-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<!-- 3.1 在webBindingInitializer中注入自定义属性编辑器、自定义转换器 -->
<property name="webBindingInitializer" ref="customBinder"></property>
<!--3.2  加入 json数据的消息转换器 MappingJacksonHttpMessageConverter依赖Jackson的包 -->
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
</list>
</property>
</bean>

3.3编写jsp页面



<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head><base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>json测试</title>
<script type="text/javascript" src="<%=basePath%>pages/jsp/js/jquery-1.9.1.min.js"></script>
<script type="text/javascript">

//请求json响应json
function requestJson(){
$.ajax({
url:"${pageContext.request.contextPath }/json/requestJson",
type:"post",
contentType:"application/json;charset=utf-8",
//请求json数据,使用json表示商品信息
data:'{"name":"手机","price":1999}',
success:function(data){
alert(data.name);
}
});

}
//请求key/value响应json
function responseJson(){

$.ajax({
url:"${pageContext.request.contextPath }/json/responseJson",
type:"post",
//contentType:"application/json;charset=utf-8",
//请求key/value数据
data:"name=手机&price=1999",
success:function(data){

alert(data.name);
}

});

}
</script>
</head>
<body>

<input type="button" value="请求json响应json" onclick="requestJson()"/>
<input type="button" value="请求key/value响应json" onclick="responseJson()"/>
</body>
</html>



3.4编写controller

package com.ycy.controller;

import com.ycy.dto.ItemsCustom;
import com.ycy.model.Items;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
* Created by Administrator on 2015/9/30 0030.
*/
@Controller
@RequestMapping("/json")
public class ItemJson {

@RequestMapping("/requestPage")
public String requestPage() throws Exception {
return "jsontest";

}

// 商品修改提交json信息,响应json信息
@RequestMapping("/requestJson")
@ResponseBody
public Items editItemSubmit_RequestJson(@RequestBody Items items) throws Exception {
System.out.println(items);
//itemService.saveItem(items);
return items;

}

// 商品修改提交json信息,响应json信息
@RequestMapping("/responseJson")
@ResponseBody
public Items responseJson( Items items) throws Exception {
System.out.println(items);
//itemService.saveItem(items);
return items;

}
}

3.5 总结json

我们用到json特别注意就是我们需要用js,注意静态资源引入。还有就是我们json配置到springmvc里面,我们已经用了MappingJackson2HttpMessageConverter
,很多教程都不是2代的,我们当然用最新的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: