[javaweb]过滤器处理乱码
2022/7/24 1:22:44
本文主要是介绍[javaweb]过滤器处理乱码,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
过滤器
有一些信息不应该被处理,要被过滤的。
1.导包
<dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>jstl-api</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.2-b01</version> </dependency>
2.继承过滤器的接口
package com.javaweb.controller; import javax.servlet.*; import java.io.IOException; /** * @author panglili * @create 2022-07-20-20:32 */ public class FilterDemo1 implements Filter { public void init(FilterConfig filterConfig) throws ServletException { } public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { servletRequest.setCharacterEncoding("utf-8"); servletResponse.setCharacterEncoding("utf-8"); servletResponse.setContentType("text/html;charset=utf-8"); System.out.println("****before:"); //让请求继续执行,如果不写请求到这里就会停止 filterChain.doFilter(servletRequest,servletResponse); System.out.println("####after:"); } public void destroy() { System.out.println("destory……"); } }
3.写一个没有处理编码的请求
package com.javaweb.servlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author panglili * @create 2022-07-20-8:26 */ public class tets extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context = this.getServletContext(); String username="弄啥嘞~"; context.setAttribute("username",username); resp.getWriter().write(username); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
此时还没有配置过滤器,看看网页效果
意料之中的乱码。
4.将过滤器注册到web配置
<filter> <filter-name>encoding</filter-name> <filter-class>com.javaweb.controller.FilterDemo1</filter-class> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/filter</url-pattern> </filter-mapping>
5.经过过滤器的处理
这篇关于[javaweb]过滤器处理乱码的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-01后台管理开发学习:新手入门指南
- 2024-11-01后台管理系统开发学习:新手入门教程
- 2024-11-01后台开发学习:从入门到实践的简单教程
- 2024-11-01后台综合解决方案学习:从入门到初级实战教程
- 2024-11-01接口模块封装学习入门教程
- 2024-11-01请求动作封装学习:新手入门教程
- 2024-11-01登录鉴权入门:新手必读指南
- 2024-11-01动态面包屑入门:轻松掌握导航设计技巧
- 2024-11-01动态权限入门:新手必读指南
- 2024-11-01动态主题处理入门:新手必读指南