2-6自由编程
为什么在返回答案的时候会出现乱码?
这是答案返回Servlet类:daanfanhui.java
package com.winking.ServletProj.change; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class daanfanhui */ @WebServlet("/mun") public class daanfanhui extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public daanfanhui() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int mun=(int)request.getAttribute("reqn"); response.getWriter().println("这是累加的和:"+mun); response.setContentType("text/html;charset=utf-8"); } }
这是请求获取Servlet:getnum.java
package com.winking.ServletProj.change; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class getnum */ @WebServlet("/get") public class getnum extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public getnum() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String n =request.getParameter("n"); int a=Integer.parseInt(n); int i=0; int umn=0; while(i<=a) { umn=umn+i; i++; } request.setAttribute("reqn", umn); request.getRequestDispatcher("/mun").forward(request, response); } }
这是html的代码:computer.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <form action="http://localhost:8080/FirstServlet/get"> <input type="text" name="n" "/> <input type="submit" value="求累加和"/> </form> </body> </html>
1
收起
正在回答
1回答
同学你好,这是因为在使用request和response进行请求响应的数据传递的时候,没有注意编码格式,我们可以添加如下两条语句:
request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8");
这样就可以限定web服务器输入的请求流、输出的响应流的编码都为UTF-8了,这些内容在后面的课程中都会讲解的哦,添加如上代码后,运行效果如下:
如果我的回答解决了你的疑惑,请采纳,祝学习愉快~
2. 从网页搭建入门JavaWeb
- 参与学习 人
- 提交作业 676 份
- 解答问题 9666 个
本阶段将从前端网页搭建入手,到Java Web基础,前后端结合助你完成Java Web小白的蜕变!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星