webconfig.java_Spring MVC 的 Java Config ( 非 XML ) 配置方式

1 packagelm.solution.web.config.configs;2

3 importcom.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;4 importlm.solution.common.web.messageconverter.CustomMessageConverter;5 importlm.solution.web.config.beans.TimerInterceptor;6 importorg.springframework.context.annotation.Bean;7 importorg.springframework.context.annotation.ComponentScan;8 importorg.springframework.context.annotation.Configuration;9 importorg.springframework.http.MediaType;10 importorg.springframework.http.converter.HttpMessageConverter;11 importorg.springframework.web.multipart.MultipartResolver;12 importorg.springframework.web.multipart.commons.CommonsMultipartResolver;13 import org.springframework.web.servlet.config.annotation.*;14 importorg.springframework.web.servlet.view.InternalResourceViewResolver;15 importorg.springframework.web.servlet.view.JstlView;16

17 importjava.util.ArrayList;18 importjava.util.List;19

20 @Configuration21 /**

22 * @EnableWebMvc 注解会开启一些默认配置,如:ViewResolver MessageConverter 等,23 * 若无此注解,重写 WebMvcConfigurerAdapter 方法无效24 **/

25 @EnableWebMvc26 @ComponentScan(value ={27 "lm.solution.web",28 "lm.solution.service.mysql",29 "lm.solution.service.webtest"

30 })31 /**

32 * 继承 WebMvcConfigurerAdapter 类,重写其方法可对 spring mvc 进行配置33 **/

34 public class WebConfig extendsWebMvcConfigurerAdapter {35

36 //重写 addViewControllers 简化页面快捷转向,这样就可以不用配置 Controller 了

37 @Override38 public voidaddViewControllers(ViewControllerRegistry registry) {39

40 registry.addViewController("/").setViewName("index");41 registry.addViewController("/error").setViewName("error/error");42 registry.addViewController("/excel").setViewName("excel/excel");43 //文件上传下载

44 registry.addViewController("/upload").setViewName("fileupload/upload");45 registry.addViewController("/ImageValidateCodeLogin").setViewName("login/imageValidateCodeLogin");46 registry.addViewController("/restfulapi").setViewName("restful/user");47 registry.addViewController("/jaxwsri").setViewName("jaxwsri/wsri");48 registry.addViewController("/redis").setViewName("redis/jedis");49 registry.addViewController("/mybatisPage").setViewName("db/mybatis");50 registry.addViewController("/messageconverter").setViewName("httpmessageconverter/customconverter");51 registry.addViewController("/sse").setViewName("serverpushmessage/sse");52

53 }54

55 //配置JSP视图解析器

56 @Bean57 publicInternalResourceViewResolver viewResolver() {58 InternalResourceViewResolver viewResolver = newInternalResourceViewResolver();59 /**

60 * views 在 /resources/ 下61 **/

62 //前缀

63 viewResolver.setPrefix("/WEB-INF/classes/views/");64 //后缀

65 viewResolver.setSuffix(".jsp");66 viewResolver.setViewClass(JstlView.class);67 viewResolver.setContentType("text/html");68 //可以在JSP页面中通过${}访问beans

69 viewResolver.setExposeContextBeansAsAttributes(true);70 returnviewResolver;71 }72

73 //配置springMVC处理上传文件的信息

74 @Bean75 publicMultipartResolver multipartResolver() {76 CommonsMultipartResolver resolver = newCommonsMultipartResolver();77 resolver.setDefaultEncoding("UTF-8");78 resolver.setMaxUploadSize(10485760000L);79 resolver.setMaxInMemorySize(40960);80 returnresolver;81 }82

83 //配置静态文件处理

84 @Override85 public voidaddResourceHandlers(ResourceHandlerRegistry registry){86

87 /**

88 * addResourceHandler 指的是对外暴露的访问路径89 * addResourceLocations 指的是文件放置的目录90 **/

91 registry.addResourceHandler("/assets/**")92 .addResourceLocations("classpath:/assets/");93

94 //href 链接方式 下载文件

95 registry.addResourceHandler("/files/**")96 .addResourceLocations("classpath:/files/");97

98 /**

99 * 解决 No handler found for GET /favicon.ico 异常100 **/

101 registry.addResourceHandler("/favicon.ico")102 .addResourceLocations("classpath:/favicon.ico");103

104 }105

106 //重写 configurePathMatch ,改变路径参数匹配

107 @Override108 public voidconfigurePathMatch(PathMatchConfigurer configurer) {109

110 /**

111 * Spring mvc 默认 如果路径参数后面带点,如 “/mm/nn/xx.yy” 后面的yy值将被忽略112 * 加入下面的配置,就不会忽略“.”后面的参数了113 **/

114 configurer.setUseSuffixPatternMatch(false);115

116 }117

118 //

119 // //负责读取二进制格式的数据和写出二进制格式的数据;120 //@Bean121 //public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() {122 //

123 //return new ByteArrayHttpMessageConverter();124 //

125 //}126 //

127 // //负责读取字符串格式的数据和写出字符串格式的数据;128 //@Bean129 //public StringHttpMessageConverter stringHttpMessageConverter() {130 //

131 //StringHttpMessageConverter messageConverter = new StringHttpMessageConverter();132 //messageConverter.setDefaultCharset(Charset.forName("UTF-8"));133 //return messageConverter;134 //

135 //}136 //

137 // //负责读取资源文件和写出资源文件数据;138 //@Bean139 //public ResourceHttpMessageConverter resourceHttpMessageConverter() {140 //

141 //return new ResourceHttpMessageConverter();142 //

143 //}144 //

145 ///**146 //* 负责读取form提交的数据147 //* 能读取的数据格式为 application/x-www-form-urlencoded,148 //* 不能读取multipart/form-data格式数据;149 //* 负责写入application/x-www-from-urlencoded和multipart/form-data格式的数据;150 //*/151 //@Bean152 //public FormHttpMessageConverter formHttpMessageConverter() {153 //

154 //return new FormHttpMessageConverter();155 //

156 //}157 //

158 // //负责读取和写入json格式的数据;159 ///**160 //* 配置 fastjson 中实现 HttpMessageConverter 接口的转换器161 //* FastJsonHttpMessageConverter 是 fastjson 中实现了 HttpMessageConverter 接口的类162 //*/163 //@Bean(name = "fastJsonHttpMessageConverter")164 //public FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {165 // //

166 //String txtHtml = "text/html;charset=UTF-8";167 //String txtJson = "text/json;charset=UTF-8";168 //String appJson = "application/json;charset=UTF-8";169 //

170 // //这里顺序不能反,一定先写 text/html,不然 IE 下会出现下载提示171 //List mediaTypes = new ArrayList<>();172 //mediaTypes.add(MediaType.parseMediaType(txtHtml));173 //mediaTypes.add(MediaType.parseMediaType(txtJson));174 //mediaTypes.add(MediaType.parseMediaType(appJson));175 //

176 // //加入支持的媒体类型,返回 contentType177 //FastJsonHttpMessageConverter fastjson = new FastJsonHttpMessageConverter();178 //fastjson.setSupportedMediaTypes(mediaTypes);179 //return fastjson;180 //

181 //}182 //

183 // //负责读取和写入 xml 中javax.xml.transform.Source定义的数据;184 //@Bean185 //public SourceHttpMessageConverter sourceHttpMessageConverter() {186 //

187 //return new SourceHttpMessageConverter();188 //

189 //}190 //

191 // //负责读取和写入xml 标签格式的数据;192 //@Bean193 //public Jaxb2RootElementHttpMessageConverter jaxb2RootElementHttpMessageConverter() {194 //

195 //return new Jaxb2RootElementHttpMessageConverter();196 //

197 //}198 //

199 // //注册消息转换器200 ///**201 //* 重写 configureMessageConverters 会覆盖掉 spring mvc 默认注册的多个 HttpMessageConverter202 //* 所以 推荐使用 extendMessageConverter203 //* */204 ///**205 //* Error:206 //* 400:(错误请求) 服务器不理解请求的语法。207 //* 415:(不支持的媒体类型) 请求的格式不受请求页面的支持。208 //*/209 //@Override210 //public void configureMessageConverters(List> converters) {211 //

212 //converters.add(this.byteArrayHttpMessageConverter());213 //converters.add(this.stringHttpMessageConverter());214 //converters.add(this.resourceHttpMessageConverter());215 //converters.add(this.formHttpMessageConverter());216 //converters.add(this.fastJsonHttpMessageConverter());217 //converters.add(this.sourceHttpMessageConverter());218 //converters.add(this.jaxb2RootElementHttpMessageConverter());219 //

220 //}221

222 //自定义 HttpMessageConverter

223 @Bean224 publicCustomMessageConverter customMessageConverter(){225

226 return newCustomMessageConverter();227

228 }229

230 //负责读取和写入json格式的数据;

231 /**

232 * 配置 fastjson 中实现 HttpMessageConverter 接口的转换器233 * FastJsonHttpMessageConverter 是 fastjson 中实现了 HttpMessageConverter 接口的类234 */

235 @Bean(name = "fastJsonHttpMessageConverter")236 publicFastJsonHttpMessageConverter fastJsonHttpMessageConverter() {237 //238 String txtHtml = "text/html;charset=UTF-8";239 String txtJson = "text/json;charset=UTF-8";240 String appJson = "application/json;charset=UTF-8";241

242 //这里顺序不能反,一定先写 text/html,不然 IE 下会出现下载提示

243 List mediaTypes = new ArrayList<>();244 mediaTypes.add(MediaType.parseMediaType(txtHtml));245 mediaTypes.add(MediaType.parseMediaType(txtJson));246 mediaTypes.add(MediaType.parseMediaType(appJson));247

248 //加入支持的媒体类型,返回 contentType

249 FastJsonHttpMessageConverter fastjson = newFastJsonHttpMessageConverter();250 fastjson.setSupportedMediaTypes(mediaTypes);251 returnfastjson;252

253 }254

255 /**

256 * 重写 extendMessageConverters 方法,仅添加自定义 HttpMessageConverter257 * 不覆盖默认注册的 HttpMessageConverter258 **/

259 @Override260 public void extendMessageConverters(List>converters) {261

262 converters.add(customMessageConverter());263 converters.add(fastJsonHttpMessageConverter());264

265 }266

267 //拦截器 bean

268 @Bean269 publicTimerInterceptor timerInterceptor(){270

271 return newTimerInterceptor();272

273 }274

275 //重写 addInterceptors 注册拦截器

276 @Override277 public voidaddInterceptors(InterceptorRegistry registry) {278

279 registry.addInterceptor(timerInterceptor());280

281 }282

283 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java 中,我们可以使用 JavaConfig配置拦截器。JavaConfig 是一种基于 Java 代码的配置方式,可以用来替代传统的 XML 配置文件。 下面是一个基于 JavaConfig 配置的拦截器使用示例: 首先,定义一个拦截器类: ```java public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 在处理请求之前进行拦截处理 return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // 在处理请求之后进行拦截处理 } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // 在请求完成之后进行拦截处理 } } ``` 然后,在配置类中注册拦截器: ```java @Configuration @EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyInterceptor()) .addPathPatterns("/**") // 拦截所有请求 .excludePathPatterns("/login"); // 排除登录请求 } } ``` 在上述代码中,我们通过 `registry.addInterceptor()` 方法来注册拦截器,并通过 `addPathPatterns()` 方法来指定需要拦截的请求路径,通过 `excludePathPatterns()` 方法来指定不需要拦截的请求路径。 最后,我们需要将配置类声明为 Spring 的配置类: ```java @Configuration @EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { // 配置拦截器 // ... } ``` 这样,我们就可以使用 JavaConfig配置拦截器了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值