Spring MVC - 上傳圖片, JSON数据交互 ,RESTful 支持

1.上传图片

       springmvc中对多部件(multipart)类型解析,在页面from中提交enctype="multipart/form-data" 的数据时,需要springmvc对multipart类型的数据进行解析;
     1.1 在springmvc.xml中配置解析器
    org.springframework.web.multipart.commons.CommonsMultipartResolver
 
     1.2 模拟:在tomcat上配置虚拟目录来进行上传图片  
   注意:在图片虚拟目录中,一定将图片目录分级创建(提高i/o性能),一般按照日期创建;
 
  上传思路:
                     1)存储的物理路径
                     2)拿到原始名称 getOriginalFileName()
                     3)新的图片名称 UUID.randomUUID() + 原始
                     4)新图片 new File(物理+新名称)
                     5)tranTofer(file)
     6)存储图片路径与名称


     1.3 tomcat建立虚拟文件目录

           (1)方法1:图形化界面操作

  

  


             图片访问路径就为 示例:

http://localhost:8989/images/3e896d12-ff02-4777-aa6e-90b2b31d3359.png


  

            (2)方法2 :Tomact配置文件配置

                          tomcat / conf /server.xml 中 的 host标签中添加 :

                       

  <Context docBase="D:\yuan\image" path="/images" reloadable="true"/>
  

      即 :docBase为物理路径 , path为虚拟路径 ;

  <Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true">

        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" -->
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" pattern="%h %l %u %t "%r" %s %b" prefix="localhost_access_log." suffix=".txt"/>

         <Context docBase="D:\yuan\image" path="/images" reloadable="true"/>
	  </Host>


    1.3 SpringMvc.xml 中 配置解析器 

         解析器: org.springframework.web.multipart.commons.CommonsMultipartResolver

   <!-- 配置文件上传解析器 -->
	    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	          <!-- 最大的上传尺寸 -->
	         <property name="maxUploadSize" value="5242880"></property>
	    </bean>

   1.4 controller实现示例 

	@RequestMapping("/uploadImage")
	public String uploadImage(FClient fc,MultipartFile mFile) throws Exception{
		if(mFile!=null){
			//物理路径
			String lujin="D:\\yuan\\image\\";
                       //文件名称
			String oldImagename=mFile.getOriginalFilename();
                     //新的文件名称
			String newImagename=UUID.randomUUID()+oldImagename.substring(oldImagename.lastIndexOf('.'));
			File file = new File(lujin+newImagename);
                      //保存文件
			mFile.transferTo(file);
			
			//图片名称
			System.out.println(newImagename);
			
		}
		
		System.out.println(fc.getUsername());
		
		return "/success.jsp";
	}

    1.5 JSp页面实现

 

  <form action="${pageContext.request.contextPath}/clients/uploadImage.action" method="post" enctype="multipart/form-data">
      
           客户姓名: <input type="text" name="username" /> <br> <br>
           上传图片:<input type="file" name="mFile"> <br> <br>
           <input type="submit" value="提交表单">
       
      </form>

2.Json数据交互

   2.1  为什么进行JSON数据交互
json数据在js中,手机客户端中,webservice中使用流行且简单;

   2.2 所需jar 

         http://download.csdn.net/detail/lablenet/9394976

   2.3 两个注解

       @RequestBody:将json串转成java对象 ;

       @ResponseBody:将java对象转成json串;

   2.4 Json配置实现

       (1) 注解驱动的方式不需要配置,即

 <mvc:annotation-driven conversion-service="conversionService" validator="validator"></mvc:annotation-driven>

       (2)  注解适配器的方式,需要配置json配置


              

 //使用注解器的配置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> 

  2.5 请求的是json,输出的是json,要求请求的是json串,所以在前端页面中需要将请求的内容转为json 实现 

       (1)controller实现

	@RequestMapping("/requestJson")
	public @ResponseBody FClient requestJson(@RequestBody FClient client){

		client.setUsername("我去");
		
		return client;
	}


      (2)ajax进行请求

       function requestJson(){

             $.ajax({
           			type: 'post',
           			url:'/SpringMvcMybatis1Demo/requestJson.action',
           			contentType:'application/json;charset=utf-8',
           			data:'{"id":"102","username":"yuan"}',
           			success:function(data){
           			    console.log(data);
           			}
        
               });
        
        }

   2.6 请求key-value ,输出的json, 比较常用 ;

       (1)controller实现

	@RequestMapping("/requestJsonKV")
	public @ResponseBody FClient requestJsonKV( FClient client){

		client.setUsername("我去");
		
		return client;
	}

      (2)ajax实现

        function requestJson(){
             $.ajax({
           			type: 'post',
           			url:'/SpringMvcMybatis1Demo/requestJsonKV.action',
           			data:'id=102&username=yuan',
           			success:function(data){
           			    console.log(data);
           			}
        
               });
        
        }

  2.7 整个json Controller实现

   

@Controller
public class JsonController {
 
	@Autowired
	private FClientService fs;
	
	@RequestMapping("/requestJson")
	public @ResponseBody FClient requestJson(@RequestBody FClient client){

		client.setUsername("我去");
		
		return client;
	}
	
	@RequestMapping("/requestJsonKV")
	public @ResponseBody FClient requestJsonKV( FClient client){

		client.setUsername("我去");
		
		return client;
	}
	
	@RequestMapping("/requestListJsons")
	public @ResponseBody List<FClient> getClients() throws Exception{
		return fs.findClientList();
	}
	
	@RequestMapping("/findClientsbyid/{id}")
	public @ResponseBody FClient findClientsbyid(@PathVariable("id") Integer id) throws Exception{
		
		return fs.findClientById(id);
	}
	
}

    html实现 :

<!DOCTYPE html>
<html>
  <head>
    <title>json</title>
	
    <meta name="keywords" content="keyword1,keyword2,keyword3">
    <meta name="description" content="this is my page">
    <meta name="content-type" content="text/html; charset=UTF-8">
    
     <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
    
     <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js"></script>
     
     <script type="text/javascript">
      

        function requestJson(){

             $.ajax({
           			type: 'post',
           			url:'/SpringMvcMybatis1Demo/requestJson.action',
           			contentType:'application/json;charset=utf-8',
           			data:'{"id":"102","username":"yuan"}',
           			success:function(data){
           			    console.log(data);
           			}
        
               });
        
        }
        
        function requestJson1(){
             $.ajax({
           			type: 'post',
           			url:'/SpringMvcMybatis1Demo/requestJsonKV.action',
           			data:'id=102&username=yuan',
           			success:function(data){
           			    console.log(data);
           			}
        
               });
        
        }
        
        $(document).ready(function(){
          console.log("我家在了");
         
        });
       
     </script>
   
  </head>
  
  <body>
       <input type="button" οnclick="requestJson()" value="测试"  />
         <input type="button" οnclick="requestJson1()" value="测试1"  />
  </body>
</html>

3.RESTful实现

    3.1 什么是restful?

        restful 是一种开发的理念,是对http的很好的诠释,全称Representational State Transfer :表现层的状态转换;

     3.2 作用1 :对Url进行规范,写成RESTful格式的url

      即:参数后以斜杠传入参数

http://localhost:8989/SpringMvcMybatis1Demo/findClientsbyid/1

     3.3 实现

          (1)配置RESTful的前端控制器 

                  可以和 .action 共存,但servlet-name不可以一样;

  <!-- 配置rest的支持 -->
  <servlet>
    <servlet-name>springmvc_rest</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>classpath:spring/springmvc.xml</param-value>
    </init-param>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>springmvc_rest</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

        (2) URL模板映射 :将URL中的模板变量映射到指定名称中;使用 @PathVariable()

 

@RequestMapping("/findClientsbyid/{id}")
	public @ResponseBody FClient findClientsbyid(@PathVariable("id") Integer id) throws Exception{
		
		return fs.findClientById(id);
	}

      (3)一个问题:RESTful模式需要对静态资源的加载,配置前端控制器的url-partten中指定的 / ,对静态资源文件的访问有问题;

  解决: 静态资源的解析,静态文件有 :js, img,html 等;
  <mvc:resources location="/js/" mapping="/js/**" />

     例如:对html的指定访问

		 <mvc:resources location="/" mapping="/**" />

4.Demo免积分下载

http://download.csdn.net/detail/lablenet/9395542



  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值