servlet使用request-获取参数和中文乱码问题
servlet代码:
package com.lbl.servlet;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;@WebServlet("/Demo02Servlet")public class Demo02Servlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); System.out.println(username); System.out.println(password); }}1234567891011121314151617181920212223
JSP代码:
<%@ page contentType="text/html;charset=UTF-8" language="java" %><html> <head> <title>$Title$</title> </head> <body> <form method="post" action="/Day04_war_exploded/Demo02Servlet"> 账号: <input type="text" name="username"><br> 密码: <input type="text" name="password"><br> <input type="submit" value="提交"> </form> </body></html>12345678910111213
效果图:
出现了中文乱码
但当改成get方法提交时,效果如下:
可以得出结论:
当是post方法提交时,会出现中文乱码问题,但get方法支持中文
post方法乱码的解决方法:
request.setCharacterEncoding("utf-8");1
完整代码:
package com.lbl.servlet;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;@WebServlet("/Demo02Servlet")public class Demo02Servlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String username = request.getParameter("username"); String password = request.getParameter("password"); System.out.println(username); System.out.println(password); }}12345678910111213141516171819202122232425
运行效果:
乱码问题解决!
作者:水巷石子
链接:https://blog.csdn.net/qq_37924905/article/details/108513486
来源:CSDN
著作权归作者所有,转载请联系作者获得授权,切勿私自转载。