Java Web技术经验总结(八)

时间:2022-06-05
本文章向大家介绍Java Web技术经验总结(八),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

在闲暇时间开始阅读Spring的官方文档,感觉收获很大,记录了一点笔记。

  1. Web服务启用https之后面临性能问题,如何解决?参考QZone的解决方法:Qzone 高性能 HTTPS 实践
  2. Spring MVC的@RequestMapping注解中,可以使用consumes限制web服务接受处理的请求,只有发来的HTTP请求头部的Content-Type与consumes相符合时才能可以处理;可以使用produces限定HTTP响应的多媒体类型,对应的字段是Accept。consumes和produces两个限定不同于其他属性,应用在method上的条件会覆盖应用在type上的条件,而其他属性则会扩展。
  1. 在Java开发中,或者需要访问别人暴露出的HTTP接口,Java提供的API是HttpUrlConnection,不出意外得难用;这种情况下,我原来经常使用Apache提供的httpclient,也还可以。今天遇到一个不错的开源库——http-request,可以拿来试试。
  2. @RequestMapping注解,除了支持常用的GET、PUT、POST、DELETE,也支持不常见的类似HEAD、OPTIONS。

When no HTTP methods are explicitly declared the "Allow" header is set to "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS". Ideally always declare the HTTP method(s) an @RequestMapping method is intended to handle.

  1. @RequestMapping方法的签名中,ErrorsBindingResult对象一定紧跟在待绑定的模型对象后面(当有多个待绑定对象时,Spring将为每个待绑定对象创建一个BindingResult)。如下代码片段不能工作:
@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("pet") Pet pet, Model model, BindingResult result) { ... }

正确的代码片段是:

@RequestMapping(method = RequestMethod.POST)
 public String processSubmit(@ModelAttribute("pet") Pet pet, BindingResult result, Model model) { ... }
  1. @RequestMapping修饰的方法,参数的类型可以有很多种,无法一一列出,参考官方文档贴个图:

@RequestMapping注解方法支持的参数类型

  1. @RequestMapping修饰的方法,支持很多返回类型,列举如下:

@RequestMapping注解方法支持的返回值类型

  1. 使用@RequestParam将请求参数绑定到控制器的方法参数上;使用这个注解的HTTP参数默认是必填的,可以通过将@RequestParam的required属性设置成false来设置成非必须的;如果方法参数类型不是String类型,则Spring会进行自动类型转换;如果@RequestParam应用在Map<String, String>或者MultiValueMap<String, String>类型的参数上时,Spring会使用http请求参数依次填充map。
@Controller
@RequestMapping("/pets")
@SessionAttributes("pet")
public class EditPetForm {
   // ... 
  @RequestMapping(method = RequestMethod.GET)
   public String setupForm(@RequestParam("petId") int petId, ModelMap model) {
     Pet pet = this.clinic.loadPet(petId);
     model.addAttribute("pet", pet);
     return "petForm";
   }
   // ...
}
  1. <mvc:annotation-driven>,在Spring MVC项目中,可以通过Java Config或者XML文件形式开启MVC支持,使用Java Config的配置代码如下:
@Configuration
 @EnableWebMvc
 public class WebConfig {  }

使用XML文件中的mvc:annoation-driven元素也可以,具体代码如下:

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

所谓开启MVC支持,实际上是注册了RequestMappingHandlerMappingRequestMappingHandlerAdapter,以及ExceptionHandlerExceptionResolver这些bean,使得在控制器中可以使用@RequestMapping、@ExceptionHandler这些注解。开启MVC支持,也提供了如下功能:

  • 除了使用JavaBeans的PropertyEditiors完成数据绑定外,也可以通过ConversionService实例实现Spring 3样式的类型转换;
  • 支持通过ConversionService实例和@NumberFormat注解对Number类型的参数进行格式化;
  • 支持使用@DateTimeFormat注解对Date、Calendar、Long和Joda Time类型的参数进行格式化;
  • 如果classpath中存在JSR-303 Provider,则可以使用@Valid注解验证控制器方法中的参数的合理性;
  • 对于@RequestMapping或者@ExceptionHandler修饰的方法,如果方法参数使用@RequestBody修饰,或者方法的返回值用@ResponseBody修饰,则支持HttpMessageConverter进行HTTP请求、响应和Java对象的互相转换。
  1. <mvc:resources mapping="" location=""/>,这个标签用于Spring MVC的Web应用处理静态资源请求;该标签实际的工作类是ResourceHttpRequestHandler,它包含有几个Resource位置属性,可以将处理静态资源请求——包括web应用根目录或者classpath路径下的静态资源。(1)mapping属性指的是特定的URL模式;(2)location属性指的是静态资源文件的位置;(3)cache-period属性用于设置缓存时间(利用浏览器缓存、减小服务器压力。 如果使用Java Config,则对应的配置代码如下:
@Configuration
@EnableWebMvc
 public class WebConfig extends WebMvcConfigurerAdapter {
      @Override
      public void addResourceHandlers(ResourceHandlerRegistry registry) {
         registry.addResourceHandler("/resources/**").addResourceLocations("/public-resources/");
     }
  }

如果使用XML配置,则对应的配置代码如下:

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

mapping属性必须是Ant模式,由SimpleUrlHandlerMapping解析url解析;location属性必须指定一个或者多个有效的资源目录位置,多个资源位置可以用逗号分割。对于每个服务端接受的请求,Spring会按照location属性指定的顺序进行匹配。例如,如果某个服务提供的资源既来自web应用根目录,又来自classpath中的/META-INF/public-web-resources目录,则对应的Java Config代码如下:

@EnableWebMvc
@Configuration
 public class WebConfig extends WebMvcConfigurerAdapter {
      @Override
     public void addResourceHandlers(ResourceHandlerRegistry registry) {
         registry.addResourceHandler("/resources/**")
                 .addResourceLocations("/", "classpath:/META-INF/public-web-resources/");
     }
  }

同样的功能,XML配置代码如下:

<mvc:resources mapping="/resources/**" location="/, classpath:/META-INF/public-web-resources/"/>