zoukankan      html  css  js  c++  java
  • 在spring MVC的controller中获取ServletConfig

    在使用SmartUpload进行文件上传时,需要用到srevletConfig:


    如果是在servlet中写当然是很容易实现的:

            private ServletConfig config;
    	//初始化Servlet
    	final public void init(ServletConfig config)
    			throws ServletException{
    		this.config=config;
    	}

    init方法会在servlet初始化时获取到servletConfig.

    但是在Controller中怎么获得呢?经过小编多方请教,可以通过继承ServletConfigAware,ServletContextAware这两个接口来实现:

    package module.system.controller;
    
    import java.io.IOException;
    
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import module.system.common.FileLoad;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.context.ServletConfigAware;
    import org.springframework.web.context.ServletContextAware;
    /**
     * 文件上传下载.
     * 
     */
    @Controller
    @RequestMapping("/fileLoad")
    public class FileLoadController implements ServletConfigAware,ServletContextAware{
    	
    	private ServletContext servletContext;
    	@Override
    	public void setServletContext(ServletContext arg0) {
    		this.servletContext = arg0;
    	}
        private ServletConfig servletConfig;
    	@Override
    	public void setServletConfig(ServletConfig arg0) {
            this.servletConfig = arg0;
    	}
    	
    	@RequestMapping(value = "/upload.do", method = RequestMethod.POST)
    	@ResponseBody  //此注解表明返回值跳过视图处理部分,直接写入 http response body中
    	public String upload(HttpServletRequest request,HttpServletResponse response) {
    		 
    		FileLoad fileLoad = new FileLoad();
    		try {
    			fileLoad.upload(request, response,servletConfig);
    		} catch (ServletException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		return "";
    	}
    
    	
    }
    

    里边这个upload方法是另外写的一个方法,将会在下一篇文章中介绍。通过这样就可以得到servletConfig了



    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    Cannot resolve symbol 'SpringBootApp
    Java读取ZIP文件ZipEntry.getsize()总是返回-1?
    java 读取zip里面的xml文件
    导出:xml zip
    jquery form submit提交方式
    [转][C#]无法创建虚拟目录。ASP.NET 2.0 尚未在 Web服务器上注册。
    [转][C#].Net反编译利器
    [转][echarts]地图轮播
    [转][C#]AutoFac 使用方法总结
    [转]用代码访问 Https
  • 原文地址:https://www.cnblogs.com/dingxiaoyue/p/4931748.html
Copyright © 2011-2022 走看看