慕仔4221270
2016-12-14 11:57
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <a href="servlet/HelloServlet">使用get方式访问servlet</a> <form action="servlet/HelloServlet" method=“post”> <input type="submit" value="使用post方式访问servlet" /> </form> </body> </html>
package servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //继承于HttpServlet public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); System.out.println("使用get()方式访问servlet"); PrintWriter out = response.getWriter(); out.println("<strong>使用get()方式访问servlet<strong/>"); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); System.out.println("使用post()方式访问servlet"); PrintWriter out = response.getWriter(); out.println("<strong>使用post方式访问servlet<strong/>"); } }
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>MyFirstServletDemo</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/servlet/HelloServlet</url-pattern> </servlet-mapping> </web-app>
平时看视频的时候建议也看一下评论,评论里一些常见错误处理。
这个问题在doget和dopost方法中写入:response.setContentType("text/html;charset=utf-8");
需要注意的是此行代码一定要在PrintWriter out=response.getWriter();之前;如果像视频中得,在获取PrintWriter之后才打此行代码,text/html设置是有效的,但是charset=utf-8无效,因为在获取PrintWriter时就获取了默认的ISO-8859-1编码格式。希望是最佳答案
浏览器编码要在哪里改呀??我吧eclipse重启之后打开就好了,我都不明白到底为什么
可能是浏览器编码集问题
JAVA遇见HTML——Servlet篇
160614 学习 · 1029 问题
相似问题