ywlcn / SpringStudy

TempSampleSource
0 stars 0 forks source link

SpringMVC #10

Open ywlcn opened 5 years ago

ywlcn commented 5 years ago

Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
    <display-name>springMVC</display-name>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextClass</param-name>
            <param-value>org.springframework.web.context.support.AnnotationCofingWebApplicationContext</param-value>
        </init-param>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/mvc-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported> <!-- 非同期设置 -->
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/app.xml</param-value>
    </context-param>

    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <async-supported>true</async-supported> <!-- 非同期设置 -->
        <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>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>ASYNC</dispatcher> <!-- 非同期设置 -->
    </filter-mapping>

    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources
        in the /WEB-INF/views directory -->
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <!--  非同期设置 -->
    <mvc:annotation-driven>
        <mvc:async-support default=“5000” />
    </mvc:annotation-driven>

    <!-- 静态资源请求的设定 -->
    <!-- 方法1     -->
    <!-- Handles HTTP GET requests for /resources/** by efficiently serving
        up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/"  cache-period="604800"/>
    <mvc:cachecontrol>
    <!-- 方法2  -->
    <!--  会在Spring MVC上下文中定义一个org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler,它会像一个检查员,对进入DispatcherServlet的URL进行筛查,如果发现是静态资源的请求,就将该请求转由Web应用服务器默认的Servlet处理,如果不是静态资源的请求,才由DispatcherServlet继续处理。 -->
<mvc:default-servlet-handler>

    <!--  函数参数转换 -->
<mvc:annotation-driven>
    <mvc:argument-resolvers>
        <bean class="・・・・.CustomerHandlerMethodArgumentResolver "/>
    </mvc:argument-resolvers>
</mvc:annotation-driven>

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">   
   <!--线程安全的访问session-->  
    <property name="synchronizeOnSession" value="true"/>   
    <property name="customArgumentResolvers">  
       <list>  
          <bean class="・・・・.RequestJsonParamMethodArgumentResolver"/>  
          <bean class="・・・・.FormModelMethodArgumentResolver"/>  
       </list>  
    </property>  
</bean>    

    <!-- -->
    <context:component-scan base-package="com.example.XXXXXX" />

    <jsp-config>
        <jsp-property-group>
            <url-pattern>*.jsp</url-pattern>
            <page-encoding>UTF-8</page-encoding>
            <!-- 所有的JSP裏面都會加上這個文件裏面的東西  -->
            <include-prelude>/WEB-INF/include.jsp</include-prelude>
        </jsp-property-group>
    </jsp-config>

</web-app>

缓存控制:

response.setHeader("Cache-Control", "no-cache");

return ResponseEntity.ok() .cacheControl(CacheControl.maxAge(20, TimeUnit.SECONDS)) .body(body);

ywlcn commented 5 years ago

DispatcherServlet

HandlerExceptionResolver

LocaleResolver

LocaleContextResolver

ThemeResolver

FlashMapManager

RequestToViewNameTranslator

HandlerInterceptor

MultipartResolver

ywlcn commented 5 years ago

HandlerMapping

HandlerAdapter

public class CustomerHandlerMethodArgumentResolver implement HandlerMethodArgumentResolver{

    // 支持的类型判断用
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return UserData.class.isAssignableFrom(parameter.getParameterType());
    }

    // Request参数绑定
    @Override
    public Object resolveArgument(MethodParameter parameter
                                , ModelAndViewContainer container
                                , NativeWebRequest request
                                , WebDataBinderFactory factory) throws Exception {

        ///////
        return userData;
    }
}

使用例子

ViewResolver

View

public class RequestHeaderModelAttributeMethodProcessor extends ModelAttributeMethodProcessor {

    // 构造函数
    public RequestHeaderModelAttributeMethodProcessor() {
        super(true);
    }

    // 支持的类型判断用
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return RequestHeader.class.isAssignableFrom(parameter.getParameterType());
    }

    // Request参数绑定
    @Override
    protected void bindRequestParameters(WebDataBinder binder, NativeWebRequest request) {

        MutablePropertyValues pvs = new MutablePropertyValues();
        pvs.addPropertyValue("userAgent", request.getHeader("user-agent"));
        pvs.addPropertyValue("accept", request.getHeader("accept"));
        pvs.addPropertyValue("acceptLanguage", request.getHeader("accept-language"));
        pvs.addPropertyValue("acceptEncoding", request.getHeader("accept-encoding"));
        binder.bind(pvs);
    }
}
ywlcn commented 5 years ago

Controller 可以使用的注释参数

ywlcn commented 5 years ago

JSP EL式 可以使用的 默认 结构体

ywlcn commented 5 years ago

SpringMVC Exception Handler

ExceptionHandlerExceptionResolver

ResponseStatusExceptionResolver

DefaultHanlderExceptionHandler

编号 例外 HTTP Status Code
(1) org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException 404
(2) org.springframework.web.HttpRequestMethodNotSupportedException 405
(3) org.springframework.web.HttpMediaTypeNotSupportedException 415
(4) org.springframework.web.HttpMediaTypeNotAcceptableException 406
(5) org.springframework.web.bind.MissingPathVariableException 500
(6) org.springframework.web.bind.MissingServletRequestParameterException 400
(7) org.springframework.web.bind.ServletRequestBindingException 400
(8) org.springframework.beans.ConversionNotSupportedException 500
(9) org.springframework.beans.TypeMismatchException 400
(10) org.springframework.http.converter.HttpMessageNotReadableException 400
(11) org.springframework.http.converter.HttpMessageNotWritableException 500
(12) org.springframework.web.bind.MethodArgumentNotValidException 400
(13) org.springframework.web.multipart.support.MissingServletRequestPartException 400
(14) org.springframework.validation.BindException 400
(15) org.springframework.web.servlet.NoHandlerFoundException 404

@ControllerAdvice
public class ExceptionHandler {

    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @org.springframework.web.bind.annotation.ExceptionHandler({ HttpRequestMethodNotSupportedException.class })
    @ResponseBody
    public Map<String, Object> handleError() {
        Map<String, Object> errorMap = new HashMap<String, Object>();
        errorMap.put("message", "Error");
        errorMap.put("status", HttpStatus.METHOD_NOT_ALLOWED);
        return errorMap;
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public String handlerException() {

         ....... 

        return “error/systemError”;
    }

}
ywlcn commented 5 years ago

REST API 数据类型转换

默认可以可使用的Converter(不需要其他Library)

項番 类名 变换 支持的MediaType 支持的JavaType
(1) org.springframework.http.converter. ByteArrayHttpMessageConverter HTTPBody(Text文本 or 2进制数据)⇔Byte数组 / byte[]
(2) org.springframework.http.converter. StringHttpMessageConverter HTTPBody(Text文本)⇔文字列 text / * String
(3) org.springframework.http.converter. ResourceHttpMessageConverter HTTPBody(2进制数据)⇔Spring的ResourceObject / Resource
(4) org.springframework.http.converter.xml. SourceHttpMessageConverter HTTPBody(XML)⇔XMLObject ・text/xml
・application/xml
・application/*-xml
Source
(5) org.springframework.http.converter.support. AllEncompassingFormHttpMessageConverter HTTPBody⇔MultiValueMap ・application/multipart/form-data :MultiValueMap<String, Object>
・application/x-www-form-urlencoded :MultiValueMap<String, String>
Map<K, List<?>>

其他可以可使用的Converter(需要其他Library)

項番 クラス名 变换 MediType 需要的库(存在于ClassPath) サポート型
(6) org.springframework.http.converter.feed. AtomFeedHttpMessageConverter HTTPBody(Atom)⇔AtomObject application/atom+xml ROME Feed
(7) org.springframework.http.converter.feed. RssChannelHttpMessageConverter HTTPBody(RSS)⇔RssObject application/rss+xml ROME Channel
(8) org.springframework.http.converter.json. MappingJackson2HttpMessageConverter HTTPBody(JSON)⇔JavaBean application/json,application/*+json Jackson2 Object (JavaBean) Map
(9) org.springframework.http.converter.xml. MappingJackson2XmlHttpMessageConverter HTTPBody(XML)⇔JavaBean text/xml,application/xml,application/*-xml Jackson-dataformat-xml Object (JavaBean) Map
(10) org.springframework.http.converter.xml. Jaxb2RootElementHttpMessageConverter HTTPBody(XML)⇔JavaBean text/xml,application/xml,application/*-xml JAXB Object (JavaBean)
(11) org.springframework.http.converter.json. GsonHttpMessageConverter HTTPBody(JSON)⇔JavaBean application/json,application/*+json Gson Object (JavaBean) Map

protected final void addDefaultHttpMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
        StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
        stringConverter.setWriteAcceptCharset(false);

        messageConverters.add(new ByteArrayHttpMessageConverter());
        messageConverters.add(stringConverter);
        messageConverters.add(new ResourceHttpMessageConverter());
        messageConverters.add(new SourceHttpMessageConverter<Source>());
        messageConverters.add(new AllEncompassingFormHttpMessageConverter());

        if (romePresent) {
            messageConverters.add(new AtomFeedHttpMessageConverter());
            messageConverters.add(new RssChannelHttpMessageConverter());
        }

        if (jackson2XmlPresent) {
            ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.xml().applicationContext(this.applicationContext).build();
            messageConverters.add(new MappingJackson2XmlHttpMessageConverter(objectMapper));
        }
        else if (jaxb2Present) {
            messageConverters.add(new Jaxb2RootElementHttpMessageConverter());
        }

        if (jackson2Present) {
            ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().applicationContext(this.applicationContext).build();
            messageConverters.add(new MappingJackson2HttpMessageConverter(objectMapper));
        }
        else if (gsonPresent) {
            messageConverters.add(new GsonHttpMessageConverter());
        }
    }
ywlcn commented 5 years ago

HttpSession情报利用

1. @SessionAttributes (类注释 类型指定或者属性名称指定)

2. 定义SessionScope的Bean

3.直接调用HttpSessionAPI

ywlcn commented 5 years ago

ResourceResolver 下面的类实现了ResourceResolver

ResourceTransformer 下面的类实现了ResourceTransformer

LocaleResoler 下面的类实现了LocaleResolver