前言
在构建现代 web 应用时,处理请求参数、实现请求过滤和拦截是确保应用高效、安全的重要环节。本文将深入探讨 Spring 框架中请求参数的处理方法,以及如何运用过滤器和拦截器来优化应用的性能和用户体验。
请求参数与回显
public String test(String name,ModelAndView model) { System.out.println("name="+name); // 业务代码 String result = "HelloSpringMVC"; model.addObject("msg", result); return "test"; } http://localhost:8080/myMaven_war_exploded/hello?name=youren @RequestMapping("/hello") public String test(@RequestParam("username") String name, ModelAndView model) { System.out.println("name="+name); // 业务代码 String result = "HelloSpringMVC"; model.addObject("msg", result); return "test"; } http://localhost:8080/hello?username=youren
lombok
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.20</version> </dependency> @Data @AllArgsConstructor @NoArgsConstructor public class User { private int id; private String name; private int age; } @RequestMapping("hello2") public String test02(User user) { System.out.println(user); return "test"; } http://localhost:8080/hello2?name=youren&age=8&id=10
过滤器的使用
package com.youren.controller; import javax.servlet.*; import java.io.IOException; public class EncodingFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { servletRequest.setCharacterEncoding("utf-8"); servletResponse.setCharacterEncoding("utf-8"); filterChain.doFilter(servletRequest, servletResponse); } @Override public void destroy() { } }
<filter> <filter-name>encoding</filter-name> <filter-class>com.youren.controller.EncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/</url-pattern> </filter-mapping>
使用注解开发
@RequestMapping 用于把 url 跟具体的 action 方法进行匹配
@ RequestParam 绑定单个 请求 数据,
@ModelAttribute ,绑定 数据到 Model
@value 指定 请求的实际url
@method 请求 类型
@params 设置参数必须包含的内容
@headers 设置请求头 包含的内容
@ResponseBody 通常用来返回 json数据 或则xml 文件
json
@ResponseBody //它就不会走视图解析器,会直接返回一个字符串 @RequestMapping("json1") public String json1(){ User user = new User(1,"youren",8); return user.toString(); }
@Data @AllArgsConstructor @NoArgsConstructor public class User { private int id; private String name; private int age; }
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.20</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.14.2</version> </dependency>
public String json1() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); User user = new User(1,"youren",8); String s = mapper.writeValueAsString(user); return s; }
//乱码解决 @RequestMapping(value="json1",produces="application/json;charset=UTF-8") <!--解决json 乱码配置--> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <constructor-arg value="UTF-8"/> </bean> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper"> <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"> <property name="failOnEmptyBeans" value="false"/> </bean> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
public static void main(String[] args) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); User user = new User(2,"youren",10); String s = mapper.writeValueAsString(user); System.out.println(s);//json System.out.println(user);//对象, }
拦截器
创建 一个 类继承HandlerInterceptor
public class MyInterceptor implements HandlerInterceptor { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{ System.out.println("===========处理前=========="); return false; // 当return false 不会执行之后的 } //日志 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception{ System.out.println("===========处理后=========="); } public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception{ System.out.println("===========清理 =========="); } }
<!--拦截器 的配置 --> <mvc:interceptors> <mvc:interceptor> <!-- 包括这个 请求 下面 的 所有请求 --> <!-- /** 文件下所有--> <!-- /* 文件下一个--> <mvc:mapping path="/**"/> <bean class="com.youren.interceptor.MyInterceptor"/> </mvc:interceptor> </mvc:interceptors>