Spring MVC 专题

 

Spring静态资源路径是指系统可以直接访问的路径,且路径下的所有文件均可被用户直接读取
在Springboot中默认的静态资源路径有:classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,从这里可以看出这里的静态资源路径都是在classpath中(也就是在项目路径下指定的这几个文件夹)

试想这样一种情况:一个网站有文件上传文件的功能,如果被上传的文件放在上述的那些文件夹中会有怎样的后果?

网站数据与程序代码不能有效分离;
当项目被打包成一个.jar文件部署时,再将上传的文件放到这个.jar文件中是有多么低的效率;
网站数据的备份将会很痛苦。
此时可能最佳的解决办法是将静态资源路径设置到磁盘的某个目录

 

在Springboot中可以直接在配置文件中覆盖默认的静态资源路径的配置信息:
application.properties配置文件如下:
server.port=1122

web.upload-path=D:/file/
spring.mvc.static-path-pattern=/**
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${web.upload-path}
注意:web.upload-path这个属于自定义的属性,指定了一个路径,注意要以/结尾

spring.mvc.static-path-pattern=/**表示所有的访问都经过静态资源路径;
spring.resources.static-locations在这里配置静态资源路径,这里的配置会覆盖默认配置,所以需要将默认的也加上否则static、public等这些路径将不能被当作静态资源路径,
在这个最末尾的file:${web.upload-path}之所有要加file:是因为指定的是一个具体的硬盘路径,其他的使用classpath指的是系统环境变量


自定义资源映射

上面我们介绍了Spring Boot 的默认资源映射,一般够用了,那我们如何自定义目录?
这些资源都是打包在jar包中的,然后实际应用中,我们还有很多资源是在管理系统中动态维护的,并不可能在程序包中,对于这种随意指定目录的资源,如何访问?

自定义目录

以增加 /myres/* 映射到 classpath:/myres/* 为例的代码处理为:
实现类继承 WebMvcConfigurerAdapter 并重写方法 addResourceHandlers (对于 WebMvcConfigurerAdapter 上篇介绍拦截器的文章中已经有提到)

import org.springboot.sample.interceptor.MyInterceptor1;
import org.springboot.sample.interceptor.MyInterceptor2;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/myres/**").addResourceLocations("classpath:/myres/");
        super.addResourceHandlers(registry);
    }

}

访问myres 文件夹中的fengjing.jpg 图片的地址为 http://localhost:8080/myres/fengjing.jpg
这样使用代码的方式自定义目录映射,并不影响Spring Boot的默认映射,可以同时使用。

如果我们将/myres/* 修改为 /* 与默认的相同时,则会覆盖系统的配置,可以多次使用 addResourceLocations 添加目录,优先级先添加的高于后添加的。

// 访问myres根目录下的fengjing.jpg 的URL为 http://localhost:8080/fengjing.jpg (/** 会覆盖系统默认的配置// registry.addResourceHandler("/**").addResourceLocations("classpath:/myres/").addResourceLocations("classpath:/static/");

其中 addResourceLocations 的参数是多参,可以这样写 addResourceLocations(“classpath:/img1/”, “classpath:/img2/”, “classpath:/img3/”);

    /**
     * Add one or more resource locations from which to serve static content. Each location must point to a valid
     * directory. Multiple locations may be specified as a comma-separated list, and the locations will be checked
     * for a given resource in the order specified.
     * <p>For example, {{@code "/"}, {@code "classpath:/META-INF/public-web-resources/"}} allows resources to
     * be served both from the web application root and from any JAR on the classpath that contains a
     * {@code /META-INF/public-web-resources/} directory, with resources in the web application root taking precedence.
     * @return the same {@link ResourceHandlerRegistration} instance, for chained method invocation
     */
    public ResourceHandlerRegistration addResourceLocations(String... resourceLocations) {
        for (String location : resourceLocations) {
            this.locations.add(resourceLoader.getResource(location));
        }
        return this;
    }

使用外部目录

如果我们要指定一个绝对路径的文件夹(如 H:/myimgs/ ),则只需要使用 addResourceLocations 指定即可。

// 可以直接使用addResourceLocations 指定磁盘绝对路径,同样可以配置多个位置,注意路径写法需要加上file:
registry.addResourceHandler("/myimgs/**").addResourceLocations("file:C:/myimgs/");

通过配置文件配置【会覆盖默认配置,操作时,要明白操作的业务含义】

上面是使用代码来定义静态资源的映射,其实Spring Boot也为我们提供了可以直接在 application.properties(或.yml)中配置的方法。
配置方法如下:

# 默认值为 /**
spring.mvc.static-path-pattern=
# 默认值为 classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/ 
spring.resources.static-locations=这里设置要指向的路径,多个使用英文逗号隔开,

使用 spring.mvc.static-path-pattern 可以重新定义pattern,如修改为 /myres/** ,则访问static 等目录下的fengjing.jpg文件应该为 http://localhost:8080/myres/fengjing.jpg ,修改之前为 http://localhost:8080/fengjing.jpg
使用 spring.resources.static-locations 可以重新定义 pattern 所指向的路径,支持 classpath: 和 file: (上面已经做过说明)
注意 spring.mvc.static-path-pattern 只可以定义一个,目前不支持多个逗号分割的方式。

参考了

https://www.cnblogs.com/ceshi2016/p/6704693.html
http://blog.csdn.net/catoop/article/details/50501706

 

最近需要做些接口服务,服务协议定为JSON,为了整合在Spring中,一开始确实费了很大的劲,经朋友提醒才发现,SpringMVC已经强悍到如此地步,佩服!

相关参考:
Spring 注解学习手札(一) 构建简单Web应用
Spring 注解学习手札(二) 控制层梳理
Spring 注解学习手札(三) 表单页面处理
Spring 注解学习手札(四) 持久层浅析
Spring 注解学习手札(五) 业务层事务处理
Spring 注解学习手札(六) 测试
Spring 注解学习手札(七) 补遗——@ResponseBody,@RequestBody,@PathVariable
Spring 注解学习手札(八) 补遗——@ExceptionHandler


SpringMVC层跟JSon结合,几乎不需要做什么配置,代码实现也相当简洁。再也不用为了组装协议而劳烦辛苦了!

一、Spring注解@ResponseBody,@RequestBody和HttpMessageConverter

Spring 3.X系列增加了新注解@ResponseBody@RequestBody

  • @RequestBody 将HTTP请求正文转换为适合的HttpMessageConverter对象。
  • @ResponseBody 将内容或对象作为 HTTP 响应正文返回,并调用适合HttpMessageConverter的Adapter转换对象,写入输出流。

HttpMessageConverter接口,需要开启<mvc:annotation-driven  />
AnnotationMethodHandlerAdapter将会初始化7个转换器,可以通过调用AnnotationMethodHandlerAdaptergetMessageConverts()方法来获取转换器的一个集合 List<HttpMessageConverter>
引用
ByteArrayHttpMessageConverter
StringHttpMessageConverter
ResourceHttpMessageConverter
SourceHttpMessageConverter
XmlAwareFormHttpMessageConverter
Jaxb2RootElementHttpMessageConverter
MappingJacksonHttpMessageConverter


可以理解为,只要有对应协议的解析器,你就可以通过几行配置,几个注解完成协议——对象的转换工作!

PS:Spring默认的json协议解析由Jackson完成。

二、servlet.xml配置

Spring的配置文件,简洁到了极致,对于当前这个需求只需要三行核心配置:
<context:component-scan base-package="org.zlex.json.controller" />  
<context:annotation-config />  
<mvc:annotation-driven />  

mvc:annotation-driven是一种简写的配置方式,那么mvc:annotation-driven到底做了哪些工作呢?如何替换掉mvc:annotation-driven呢?

<mvc:annotation- driven/>在初始化的时候会自动创建两个对 象,
org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping

org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter,
我们如果想不使用<mvc:annotation-driven/>这种简写方式,将其替换掉的话,就必须自己手动去配置这两个bean对 象。下面是这两个对象的配置方法,和详细的注视说明。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">

    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
        <property name="useDefaultSuffixPattern" value="false" />
        <property name="interceptors">
            <list>
                <bean class="org.mspring.mlog.web.interceptor.RememberMeInterceptor" />
                <bean class="org.mspring.mlog.web.interceptor.SettingInterceptor" />
                <bean class="org.mspring.platform.web.query.interceptor.QueryParameterInterceptor" />
            </list>
        </property>
    </bean>

    <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <-- 这个converter是我自己定义的,是为了解决spring自带的StringHttpMessageConverter中文乱码问题的 -->
                <bean class="org.mspring.platform.web.converter.StringHttpMessageConverter">
                    <constructor-arg value="UTF-8" />
                </bean>
                <!-- 这里可以根据自己的需要添加converter -->
                <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
                <bean class="org.springframework.http.converter.StringHttpMessageConverter" />
                <bean class="org.springframework.http.converter.ResourceHttpMessageConverter" />
                <bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter" />
                <bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter" />
                <bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter" />
                <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
                <!-- -->
            </list>
        </property>
        <property name="customArgumentResolvers">
            <list>
                <bean class="org.mspring.platform.web.resolver.UrlVariableMethodArgumentResolver" />
            </list>
        </property>

        <property name="webBindingInitializer">
            <bean id="webBindingInitializer"
                class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
                <property name="conversionService" ref="conversionService" />
            </bean>
        </property>
    </bean>

    <!-- 1, 注册ConversionService -->
    <bean id="conversionService"
        class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <list>
                <bean class="org.mspring.platform.web.converter.DateConverter">
                    <property name="pattern" value="yyyy-MM-dd HH:mm:ss" />
                </bean>
            </list>
        </property>
        <property name="formatters">
            <list>
                <bean class="org.mspring.mlog.web.formatter.factory.TagFormatAnnotationFormatterFactory"></bean>
                <bean class="org.mspring.mlog.web.formatter.factory.EncodingFormatAnnotationFormatterFactory"></bean>
            </list>
        </property>
    </bean>

</beans>

这样,我们就可以就成功的替换掉<mvc:annotation-driven />了。

http://www.cnblogs.com/shines77/p/3315445.html

三、pom.xml配置

闲言少叙,先说依赖配置,这里以Json+Spring为参考:
<dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-webmvc</artifactId>  
        <version>3.1.2.RELEASE</version>  
        <type>jar</type>  
        <scope>compile</scope>  
    </dependency>  
    <dependency>  
        <groupId>org.codehaus.jackson</groupId>  
        <artifactId>jackson-mapper-asl</artifactId>  
        <version>1.9.8</version>  
        <type>jar</type>  
        <scope>compile</scope>  
    </dependency>  
    <dependency>  
        <groupId>log4j</groupId>  
        <artifactId>log4j</artifactId>  
        <version>1.2.17</version>  
        <scope>compile</scope>  
    </dependency>  

主要需要spring-webmvcjackson-mapper-asl两个包,其余依赖包Maven会帮你完成。至于log4j,我还是需要看日志嘛。 

包依赖图:

至于版本,看项目需要吧!

四、代码实现

域对象:
public class Person implements Serializable {   
  
    private int id;   
    private String name;   
    private boolean status;   
  
    public Person() {   
        // do nothing   
    }   
}  

这里需要一个空构造,由Spring转换对象时,进行初始化。


@ResponseBody,@RequestBody,@PathVariable
控制器:
@Controller  
public class PersonController {   
  
    /**  
     * 查询个人信息  
     *   
     * @param id  
     * @return  
     */  
    @RequestMapping(value = "/person/profile/{id}/{name}/{status}", method = RequestMethod.GET)   
    public @ResponseBody  
    Person porfile(@PathVariable int id, @PathVariable String name,   
            @PathVariable boolean status) {   
        return new Person(id, name, status);   
    }   
  
    /**  
     * 登录  
     *   
     * @param person  
     * @return  
     */  
    @RequestMapping(value = "/person/login", method = RequestMethod.POST)   
    public @ResponseBody  
    Person login(@RequestBody Person person) {   
        return person;   
    }   
}  

备注:@RequestMapping(value = "/person/profile/{id}/{name}/{status}", method = RequestMethod.GET)中的{id}/{name}/{status}@PathVariable int id, @PathVariable String name,@PathVariable boolean status一一对应,按名匹配。 这是restful式风格。 

如果映射名称有所不一,可以参考如下方式:
@RequestMapping(value = "/person/profile/{id}", method = RequestMethod.GET)   
public @ResponseBody  
Person porfile(@PathVariable("id") int uid) {   
    return new Person(uid, name, status);   
}  
  • GET模式下,这里使用了@PathVariable绑定输入参数,非常适合Restful风格。因为隐藏了参数与路径的关系,可以提升网站的安全性,静态化页面,降低恶意攻击风险。
  • POST模式下,使用@RequestBody绑定请求对象,Spring会帮你进行协议转换,将Json、Xml协议转换成你需要的对象。
  • @ResponseBody可以标注任何对象,由Srping完成对象——协议的转换。

做个页面测试下:
$(document).ready(function() {   
    $("#profile").click(function() {   
        profile();   
    });   
    $("#login").click(function() {   
        login();   
    });   
});   
function profile() {   
    var url = 'http://localhost:8080/spring-json/json/person/profile/';   
    var query = $('#id').val() + '/' + $('#name').val() + '/'  
            + $('#status').val();   
    url += query;   
    alert(url);   
    $.get(url, function(data) {   
        alert("id: " + data.id + "\nname: " + data.name + "\nstatus: "  
                + data.status);   
    });   
}   
function login() {   
    var mydata = '{"name":"' + $('#name').val() + '","id":"'  
            + $('#id').val() + '","status":"' + $('#status').val() + '"}';   
    alert(mydata);   
    $.ajax({   
        type : 'POST',   
        contentType : 'application/json',   
        url : 'http://localhost:8080/spring-json/json/person/login',   
        processData : false,   
        dataType : 'json',   
        data : mydata,   
        success : function(data) {   
            alert("id: " + data.id + "\nname: " + data.name + "\nstatus: "  
                    + data.status);   
        },   
        error : function() {   
            alert('Err...');   
        }   
    });  

 


Table
<table>  
    <tr>  
        <td>id</td>  
        <td><input id="id" value="100" /></td>  
    </tr>  
    <tr>  
        <td>name</td>  
        <td><input id="name" value="snowolf" /></td>  
    </tr>  
    <tr>  
        <td>status</td>  
        <td><input id="status" value="true" /></td>  
    </tr>  
    <tr>  
        <td><input type="button" id="profile" value="Profile——GET" /></td>  
        <td><input type="button" id="login" value="Login——POST" /></td>  
    </tr>  
</table>  

 

四、简单测试

Get方式测试:




Post方式测试:




五、常见错误
POST操作时,我用$.post()方式,屡次失败,一直报各种异常:


引用
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported

直接用$.post()直接请求会有点小问题,尽管我标识为json协议,但实际上提交的ContentType还是application/x-www-form-urlencoded。需要使用$.ajaxSetup()标示下ContentType
Js代码  
function login() {   
    var mydata = '{"name":"' + $('#name').val() + '","id":"'  
            + $('#id').val() + '","status":"' + $('#status').val() + '"}';   
    alert(mydata);   
    $.ajaxSetup({   
        contentType : 'application/json'  
    });   
    $.post('http://localhost:8080/spring-json/json/person/login', mydata,   
            function(data) {   
                alert("id: " + data.id + "\nname: " + data.name   
                        + "\nstatus: " + data.status);   
            }, 'json');   
};  

 

效果是一样!
详见附件!

相关参考:
Spring 注解学习手札(一) 构建简单Web应用
Spring 注解学习手札(二) 控制层梳理
Spring 注解学习手札(三) 表单页面处理
Spring 注解学习手札(四) 持久层浅析
Spring 注解学习手札(五) 业务层事务处理
Spring 注解学习手札(六) 测试
Spring 注解学习手札(七) 补遗——@ResponseBody,@RequestBody,@PathVariable
Spring 注解学习手札(八) 补遗——@ExceptionHandler

 

 

http://snowolf.iteye.com/blog/1628861/

posted @ 2015-07-07 13:55  沧海一滴  阅读(348)  评论(0编辑  收藏  举报