##servlet传输数据到jsp中出现中文乱码的解决方法
- index.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html><head><meta charset="UTF-8">
<title>Insert title here</title></head>
<body><form action="bmiServlet" method="get">
姓名:<input type="text" name="name"><br/>
体重(公斤):<input type="text" name="w"><br/>
身高(米):<input type="text" name="h"><br/>
<input type="submit" value="提交">
</form>
</body>
</html>
2.result.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html><head><meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>bmi的计算结果</h1>
<h3>${msg}</h3>
</body>
</html>
3.Bmiservlet.java
package com.org.Controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;/** * Servlet implementation class BmiServlet */
public class BmiServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public BmiServlet() {
super();
// TODO Auto-generated constructor stub
}
/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String name=request.getParameter("name");
String weight=request.getParameter("w");
String height=request.getParameter("h");
//计算bmi bmi=体重/身高的平方
float h =Float.valueOf(height);
float w=Float.valueOf(weight);
float bmi=w/(h*h);
//判断bmi的范围
String msg="";
if(bmi<18.5) {
msg="您比较瘦";
}else if(18.5<bmi&&bmi<=23.9) {
msg="您的bmi是正常的";
}else if(bmi>24&&bmi<27) {
msg="您的身体比较胖";
}else {
msg="您的身体肥胖";
}
System.out.print("msg"+msg+name);
msg="您好:"+name+"先生/女士,您的bmi值是:"+bmi+","+msg; //把数据存入到request
request.setAttribute("msg",msg);
RequestDispatcher rd=request.getRequestDispatcher("result.jsp");
rd.forward(request, response);
}
}
4.把response.getWriter().append("Served at: ").append(request.getContextPath()); request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8");
中的response.getWriter().append("Served at: ").append(request.getContextPath());
删除就行或把`request.setCharacterEncoding(“UTF-8”); response.setCharacterEncoding(“UTF-8”);``放在第一行就行