Spring MVC框架学习笔记1

Spring MVC环境搭建
        今天刚接触Spring MVC,费了半天劲大框架,下面是自己一个个找出来的,不对的请指正!

我用的服务器是tomcat 7,jdk 1.7

往后台传入json对象(jquery实现):

            1, 在spring-servlet.xml中加入如下配置,将加载静态资源。

                       <!-- 加载静态文件 mapping /jsp/** 对应的是webcontent下,js文件夹与WEB-INF同级 -->
                          <mvc:resources location="/js/" mapping="/js/**"/>
                          <mvc:resources location="/img/" mapping="/img/**"/>

          2,前台ajax:

<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(function(){
 alert("hello!");
 $("#btn1").on(
   "click",
   function(){
    $.ajax({
        url:"testJson",  
        dataType:"json",
        data:{"username":"xsd","password":"xsdpaw"},
        type:"POST",
        success:function(){
               alert("ok");
           }
    });
   });
});
</script>

    3,后台controller

@RequestMapping("/testJson")
 @ResponseBody
 public String hello(User user){
  System.out.println(user.getUsername());
  System.out.println(user.getPassword());
  String jsonObj="{\"username\":\"xsd\",\"\":\"xsd_pas\"}";
  return jsonObj;
 }

加上 @ResponseBody表示,该方法返回的内容,不经过视图映射(自己想的),直接写入到响应包的体部. 所以要是放返的是xml文件,也是要加上的。

            不需要导入任何的额外jar包,前台要将json写对。eg:{"username":"xsd","password":"xsdpaw"}。

             后台的controller的方法上,参数既可以是基本类型,也可以是对象,框架会自动封装的。在方法上加上@RequestResponse

spring-servlet.xml中配置首页(我自己瞎弄的)

     <bean name="/" class="org.springframework.web.servlet.mvc.ParameterizableViewController">    
          <property name="viewName" value="test"/>    
      </bean>  

String MVC文件上传于下载,需要jar包,common-io和common-fileupload

      上传:1,在spring-servlet.xml中加入下面的配置

              <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 --> 
             <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 
        <property name="defaultEncoding" value="UTF-8"/> 
        <!-- 指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 --> 
        <property name="maxUploadSize" value="200000"/> 
    </bean>  
    <!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException --> 
    <!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 --> 
    <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> 
        <property name="exceptionMappings"> 
            <props> 
                <!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到/WEB-INF/jsp/error_fileupload.jsp页面 --> 
                <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">uploaderror</prop> 
            </props> 
        </property> 
    </bean>  

        2,再写如下controller

             //参数file1要与前台的file控件的name属性同名,

            //若想传入多个文件,前台控件要用多个file控件,且name属性要相同,MultipartFile file1要改成

            //MultipartFile[]数组。在程序中进行遍历

               @RequestMapping(value="/upload",method=RequestMethod.POST)
 public String testUpload(MultipartFile file1,HttpServletRequest request) {
         String realPath = request.getRealPath("/");;
         try {
              FileUtils.copyInputStreamToFile(file1.getInputStream(), new File(realPath, file1.getOriginalFilename()));
         } catch (IOException e) {
                e.printStackTrace();
          }
        System.out.println("上传成功");
        return null;
 }

      下载:

           @RequestMapping(value="/download")
 public ResponseEntity<byte[]> testDownload(HttpServletRequest request,HttpServletResponse response){
         String path = request.getRealPath("/")+"/"+"类图中的6中关系.txt";
         File file = new File(path);
         HttpHeaders headers = new HttpHeaders(); 
         String fileName = null;
        try {
              fileName = new String("类图中的6中关系.txt".getBytes("UTF-8"),"iso-8859-1");
          } catch (UnsupportedEncodingException e) {
                 // TODO Auto-generated catch block
                  e.printStackTrace();
           }//为了解决中文名称乱码问题
         headers.setContentDispositionFormData("attachment", fileName); 
         headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); 
      try {
          return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStatus.CREATED);
     } catch (IOException e) {
         e.printStackTrace();
      }
      return null;
 }

猜你喜欢

转载自yk1129013140.iteye.com/blog/2182758