servlet中文编码问题setCharacterEncoding

请问下setCharacterEncoding()到底是什么含义,注释说是转码,但是由什么码转到什么码,后面参数只有一个
那么 request.setCharacterEncoding("UTF-8");这条语句是什么意思,将请求的编码转为UTF-8,serlvet理解请求原编码又是什么?是gbk转utf-8还是ascII转utf-8,同样response.setCharacterEncoding("UTF-8");又是什么意思,将回应转为utf-8,那servlet原本的编码又默认是什么?当我两条语句同时用的时候,request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");把输入再次输出,结果又是怎样的?

如果不定义setCharacterEncoding,使其值为null,有是什么编码。

3个回答

追问:还是上面说的将页面的输入输出出去的例子

request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("gb2312");

无乱码(浏览器设置了解码方式gbk)

request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");  
无乱码(浏览器设置了解码方式unicode)

request.setCharacterEncoding("gb2312");
response.setCharacterEncoding("gb2312");  
乱码(浏览器怎么设置解码都乱码)

    response.setCharacterEncoding("UTF-8");  
乱码(浏览器怎么设置解码都乱码)


从以上例子我推测,是不是servlet里面的编码是固定的,是那个iso-8190类似的那个,request.setCharacterEncoding("UTF-8");告诉serlvet,请求(浏览器)是utf-8编码的,你给我转成iso-8190。response.setCharacterEncoding("UTF-8");则是说给我把iso-8190转成UTF-8。

因为浏览器的请求都是unicode编码,所以request.setCharacterEncoding("UTF-8");如果参数不是utf-8,就一定是乱码。
而response.setCharacterEncoding("UTF-8");参数则可以随便写,只要浏览解码调整为对应的输出格式就行了。
不知道我的猜测对不对。
另外,为了储存中文cookie(只支持acsII),我得用URLEncoder.encode(data, "utf-8");代码编MIME码,这里的参数utf-8是指什么呢,

QQ1252776430
QQ1252776430 因为URLEncoder.encode(data, "utf-8");肯定是servlet本地代码,就是说给我把iso-8190转成utf-8版的mime,反之亦然,所以mime只要编码和解码参数一样,最后结果一定是iso-8190,反正response.setCharacterEncoding("UTF-8");最后输出还是转成unicode的
大约 4 年之前 回复

servlet是有web容器加载的,举例tomcat来说,默认ISO8859-1,setCharacterEncoding("utf8");就是将ISO8859-1转成utf8

那具体看情况了,不过那句话发的意思就是转码成utf-8

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
Servlet、html的编码问题
编写了一个html文件,直接使用浏览器打开之后是我期望的显示“欢迎光临” 而在一个Servlet中使用请求转发,forward(request,response),跳转的页面却是乱码。 这是为什么呢? index.html ``` <!DOCTYPE html> <!-- To change this license header, choose License Headers in Project Properties. To change this template file, choose Tools | Templates and open the template in the editor. --> <html> <head> <title>TODO supply a title</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <h1>欢迎光临!</h1> </body> </html> ``` HandleLoginServlet.java ``` /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author OKAXINA */ @WebServlet(urlPatterns = {"/HandleLoginServlet"}) public class HandleLoginServlet extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try{ /* TODO output your page here. You may use following sample code. */ String username = request.getParameter("username"); String userpass = request.getParameter("userpass"); if("admin".equalsIgnoreCase(username) && "1234".equals(userpass)){ RequestDispatcher rd = request.getRequestDispatcher("index.html"); rd.forward(request, response); }else{ out.print("用户名或密码错误,请重新输入!"); RequestDispatcher rd = request.getRequestDispatcher("login.jsp"); rd.include(request, response); } }finally{ out.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> } ```
servlet中文乱码的问题,百度所有的解决方案后还是不行
这个是doget方法 request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setHeader("Content-Type", "text/html;charset=UTF-8") ; String username = new String(request.getParameter("username").getBytes("ISO-8859-1"),"UTF-8"); PrintWriter pw=response.getWriter(); System.out.println(username);//当为固定的中文字符串时没问题 所以是request.getParameter的问题 这里就是乱码了 userDao use=new userDao();//自己定义的数据库连接 String result=use.cheakName(username); System.out.println(result); pw.print(result); //返回处理的结果 然后jsp页面我也用了 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 在tomcat下面也改了 <Connector port="8081" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="UTF-8"/> 点击属性查看编码方式也是UTF-8
jsp页面通过href向servlet类页面传递中文参数时出现乱码了怎么办?
jsp页面通过href向servlet类页面传递中文参数时出现乱码了怎么办?我在doGet方法中设置了response.setContentType("text/html"); response.setCharacterEncoding("utf-8"); request.setCharacterEncoding("utf-8");所有的编码方式都是utf-8,其他地方都没出现乱码,可是就这里传递的参数是中文时会出乱码,请问是什么原因,怎么解决?
!!!servlet 传数据给数据库出现中文乱码
网上的各种方法我都试过了 什么my.ini, 还有 request.setCharacterEncoding("UTF-8");//处理编码 response.setCharacterEncoding("UTF-8");//处理编码 以及public String handleString(String s) { try{ byte bb[] =s.getBytes("UTF-8"); s=new String(bb); } catch(Exception ee){ } return s; } 最后的String uri="jdbc:mysql://127.0.0.1/zbsjk?"+"user=root&password=123456&characterEncoding=utf8"; 都解决不了,难道我要重装mysql吗!!!!QUQ
setContentType设置编码时设置为utf-8就出现乱码,其他编码则正常显示
设置编码的代码: response.setCharacterEncoding("utf-8"); response.setContentType("text/html,charset=utf-8"); 运行之后只有不是UTF-8编码就可以正常显示中文,比如gb2313和GBK
servlet 下载文件时文件名中文乱码问题一直解决不了
jsp页面通过超链标签下载文件,文件名包含中文时,下载乱码,英文和数字可以正常下载,根据网上的方法试了很多次还是解决不了,困扰一天了,现在是凌晨1点这个问题搞得我睡不着,各位老哥帮小弟看看是 哪里错了![图片说明](https://img-ask.csdn.net/upload/201907/10/1562692200_241773.png)页面编码设置utf_8 ![图片说明](https://img-ask.csdn.net/upload/201907/10/1562692300_50200.png)下载链接 ``` protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); EbizCompany company = (EbizCompany) request.getSession().getAttribute("currentCompany"); //String file = new String(request.getParameter("file").getBytes("ISO-8859-1"),"UTF-8"); String fileName = request.getParameter("file"); //客户端传递的需要下载的文件名 fileName = new String(fileName.getBytes("ISO8859-1"),"UTF-8"); System.out.println("filename "+fileName); //获得请求头中的User-Agent String agent = request.getHeader("User-Agent"); //根据不同浏览器进行不同的编码 String fileNameEncoder = ""; if (agent.contains("MSIE")) { // IE浏览器 fileNameEncoder = URLEncoder.encode(fileName, "utf-8"); fileNameEncoder = fileNameEncoder.replace("+", " "); } else if (agent.contains("Firefox")) { // 火狐浏览器 BASE64Encoder base64Encoder = new BASE64Encoder(); fileNameEncoder = "=?utf-8?B?" + base64Encoder.encode(fileName.getBytes("utf-8")) + "?="; } else { // 其它浏览器 fileNameEncoder = URLEncoder.encode(fileName, "utf-8"); } //客户端通过文件的MIME区分下载的文件的类型 response.setContentType(this.getServletContext().getMimeType(fileName)); //告诉客户端不要直接解析该文件,而是以附件的形式打开(下载) 客户端默认对名字进行解码 response.setHeader("Content-Disposition", "attachment;filename=" + fileNameEncoder); String time=Integer.toString(GeneralMethod.getYear(System.currentTimeMillis()))+"\\"+Integer.toString(GeneralMethod.getMonth(System.currentTimeMillis())); String path = Constant.FilePath + "\\" + company.companyName+"\\"+time+"\\"+fileName; FileInputStream fis = new FileInputStream(path); response.setContentType("multipart/form-data"); ServletOutputStream out = response.getOutputStream(); byte[] bt = new byte[1024]; int length = 0; while((length=fis.read(bt))!=-1){ out.write(bt,0,length); } out.close(); } ``` ![图片说明](https://img-ask.csdn.net/upload/201907/10/1562692854_226734.png)
Servlet接收表单传过来的中文值,再转发时,出现乱码的问题
<p> </p> <pre name="code" class="html">&lt;%@ page language="java" import="java.util.*" pageEncoding="GBK"%&gt;</pre> <pre name="code" class="html">&lt;% String message = "Hello World!"; String msg = (String)request.getAttribute("msg"); if(msg != null &amp;&amp; !msg.equals("")) { message = msg; } %&gt; &lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;My JSP 'helloworld.jsp' starting page&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;%=message %&gt; &lt;form action="servlet/HelloServlet" method="post"&gt; &lt;input type="text" name="name"/&gt; &lt;input type="submit" value="提交"/&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </pre> <p> </p> <p> </p> <pre name="code" class="java">package lee; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class HelloServlet extends HttpServlet {</pre> <pre name="code" class="java"> public void service(HttpServletRequest request, HttpServletResponse response) throws IOException{ String msg = null; String name = request.getParameter("name"); request.setCharacterEncoding("GBK"); if(name != null &amp;&amp; !name.equals("")) { msg = "Hello " + name; } request.setAttribute("msg", msg); RequestDispatcher rd = request.getRequestDispatcher("/Hello/helloworld.jsp"); rd.forward(request, response); } } </pre> <p> 小弟是Java web的初学者,今天学习时,写了一个简单的应用来测试servlet的页面转发功能,问题是: 当输入中文时,会出现乱码,不是编码的问题,这个我试过了,请问各位高手这是什么原因呢,怎么改呢?请指点指点,让大家见笑了。</p>
配置web.xml后显示HTTP Status 404 – 未找到
实现通过表单向servlet中传送数据,配置webxml后一直显示HHTP404,但我把添加的配置内容删掉后反而可以运行了 web.xml配置: ``` <servlet> <servlet-name>ComputeBill</servlet-name> <servlet-class>myservlet.ComputeBill</servlet-class> </servlet> <servlet-mapping> <servlet-name>ComputeBill</servlet-name> <url-pattern>/ComputeBill</url-pattern> </servlet-mapping> ``` ![图片说明](https://img-ask.csdn.net/upload/201911/20/1574242666_587077.jpg) ![图片说明](https://img-ask.csdn.net/upload/201911/20/1574242696_947922.jpg) jsp代码: ``` <%@ 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>利用表单给servlet传送数据</title> </head> <body> <form action="ComputeBill" method="post"> 输入账单:<br> <textarea name='billMess' rows="5" cols="30"> </textarea> <br> <input type=submit value="提交"> </form> </body> </html> ``` servlet代码(省略导包): ``` public class ComputeBill extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ComputeBill() { super(); // TODO Auto-generated constructor stub } /** * @see Servlet#init(ServletConfig) */ public void init(ServletConfig config) throws ServletException { // TODO Auto-generated method stub super.init(config); } /** * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response) */ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //1、设置编码格式 request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); //2、利用printwriter类输出流声明out对象,利用response对象调用getwriter方法获取一个输出流,利用out对象调用print方法 PrintWriter out=response.getWriter(); out.print("<html><body bgcolor=yellow>"); //3、通过request对象获取表单中文本区的内容送给str String str=request.getParameter("billMess"); if(str==null||str.length()==0) return; String [] price=str.split("[^0123456789.]+"); double sum=0; try { for(int i=0;i<price.length;i++) { if(price[i].length()>=1) sum+=Double.parseDouble(price[i]); } } catch(NumberFormatException e){out.print(e);} out.print(str+"<br>的消费额:"+sum+"元"); out.print("</body></html>"); } ```
servlet 里面用PrintWriter创建的html 怎么设置编码?
public void doGet(HttpServletRequest request,HttpServletResponse response)throws IOException,ServletException{ PrintWriter out = response.getWriter(); response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); String base = request.getContextPath(); out.print("<html>"); out.print("<head>"); out.print("<meta charset=\"UTF-8\"/>"); out.print("<title>DemoOne</title>"); out.print("</head>"); out.print("<body>"); out.print("<p1>欢迎登陆这个界面</p1>"); out.print("</br></br>"); out.print("<form action=\"cityServlet\" method=\"get\"/>"); out.print("<input type=\"submit\" value=\"选择城市\"/>"); out.print("</br>"); out.print("</br>"); out.print("<form action=\"climateServlet\" method=\"get\"/>"); out.print("<input type=\"submit\" value=\"选择天气\"/>"); out.print("</br>"); out.print("</br>"); out.print("<a href=\"climateServlet\"/>选择天气</a>"); out.print("</body>"); out.print("</html>"); } 这样子出来的编码都是??怎么显示中文?
jsp里面的foreach如何正确获取从 servlet里list里的值
jsp页面 <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'addowner.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body style="background-color:pink;"> <form action="AddOwnerServlet" method="post"> <center> <table style="background-color:pink; color:#2c92fb; text-align:center; margin:0 auto;"> <tr> <td><img src="image/1.png"/></td> <td> <div style="background-color:pink; color:#0ee3db"> <h1 style="color:write;">宠物医院管理系统</h1> </div> </td> <td><img src="image/3.png"/></td> </tr> <tr> <td><a href="index.jsp">系统首页</a></td> <td><a href="login.jsp">登录</a></td> <td><a href="register.jsp">注册</a></td> </tr> <tr> <table width="600" border="1" bordercolor="red" bgcolor="#FFFFEE"> <tr> <td>用户ID:</td> <td><input type="text" name="ownerID"></td> </tr> <tr> <td>用户登录名:</td> <td><input type="text" name="oname"></td> </tr> <tr> <td>用户密码:</td> <td><input type="password" name="opassword"></td> </tr> <tr> <td>性别:</td> <td><input type="text" name="osex"></td> </tr> <tr> <td>联系方式:</td> <td><input type="text" name="phone"></td> </tr> <tr> <td>地址:</td> <td><input type="text" name="address"></td> </tr> <tr> <td>宠物ID:</td> <td> <select id="list" name="petID"> <option value="">请选择宠物ID..</option> <c:forEach items="${requestScope.list}" var="listpets"> <option value="${listpets}">${listpets}</option> </c:forEach> </select> </td> </tr> <tr> <td><input type="submit" value="添加"></td> <td><input type="reset" value="重置"></td> </tr> </table> </tr> </table> </center> </form> </body> </html> servlet页面 package www.bttc.manager.ownerservlet; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import www.bttc.manager.model.Pets; import www.bttc.manager.model.Powner; import www.bttc.manager.service.OwnerService; import www.bttc.manager.service.PetsService; import www.bttc.manager.service.impl.OwnerServiceImpl; import www.bttc.manager.service.impl.PetsServiceImpl; import www.bttc.manager.utils.ServiceException; public class AddOwnerServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8");// 设置请求的编码方式 response.setCharacterEncoding("UTF-8");// 设置响应的编码方式 response.setContentType("text/html;charset=utf-8"); OwnerService ownerService=new OwnerServiceImpl(); PetsService petsService=new PetsServiceImpl(); HttpSession session=request.getSession(); int ownerID=Integer.parseInt(request.getParameter("ownerID")); String osex=request.getParameter("osex"); String oname=request.getParameter("oname"); String opassword=request.getParameter("opassword"); int phone=Integer.parseInt(request.getParameter("phone")); String address=request.getParameter("address"); int petID=Integer.parseInt(request.getParameter("petID")); /*try { List<Pets> list=(List<Pets>) petsService.findAllPetID(); //request.setAttribute("ownerID", ownerID); request.setAttribute("list", list); } catch (ServiceException e1) { e1.printStackTrace(); }*/ try { //Pets pets=new Pets(); Pets pets=petsService.findPetsByPetsID(petID); if(ownerService.findOwnerByOwnerID(ownerID)!=null){ session.setAttribute("message", "添加的普通用户记录已存在!"); request.getRequestDispatcher("addowner.jsp").forward(request, response); }else{ Powner owner=new Powner(ownerID,osex,oname,opassword,phone,address,pets); ownerService.addOwner(owner); //Powner owner=ownerService.addOwner(owner); session.setAttribute("message", "添加普通用户已成功!"); request.getRequestDispatcher("/admin.jsp").forward(request, response); } } catch (ServiceException e) { e.printStackTrace(); } } } 另一个servlet package www.bttc.manager.ownerservlet; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import www.bttc.manager.model.Pets; import www.bttc.manager.service.PetsService; import www.bttc.manager.service.impl.PetsServiceImpl; import www.bttc.manager.utils.ServiceException; public class SelectPetID extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8");// 设置请求的编码方式 response.setCharacterEncoding("UTF-8");// 设置响应的编码方式 response.setContentType("text/html;charset=utf-8"); //int petID=Integer.parseInt(request.getParameter("petID")); PetsService petsService=new PetsServiceImpl(); try { List<Pets> pets = petsService.findAllPetID(); request.setAttribute("listpets", pets); request.getRequestDispatcher("/addowner.jsp").forward(request, response); } catch (ServiceException e) { e.printStackTrace(); } } }
Servlet
我通过servlet的forward的方法从一个一面跳向另一个页面,现在跳转后的页面对应得控制层获取原来页面的参数。 [color=red]跳转前[/color] protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String name=request.getParameter("name"); String password=request.getParameter("password"); if(name!=null&&password!=null){ try { if(ChatService.instance().addUser(name,password)){ request.getSession(true).setAttribute(name,name); System.out.println("測試保存到Session里的用戶名"+request.getSession(true).getAttribute(name)); //String url="/chat.jsp?name="+name; request.getRequestDispatcher(/chat.jsp).forward(request,response); // response.sendRedirect("/chat.jsp"); } else{ request.setAttribute("tip",name+",注册失败,请重新注册"); request.getRequestDispatcher("/error.html").forward(request,response); } } catch (Exception e) { request.setAttribute("tip",e.getMessage()); request.getRequestDispatcher("/error.html").forward(request,response); } } [color=red] 跳转后[/color] protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //ajax是以utf8的方式设置编码的 request.setCharacterEncoding("UTF-8"); String context = request.getParameter("context"); if(context!=null&&!context.equals("")){ try { String user=request.getParameter("name"); //String user= (String) request.getSession(true).getAttribute("name"); System.out.println("测试获取的用户名:"+user); if(user==null){ user="晓利"; } ChatService.instance().addMsg(user,context); } catch (Exception e) { e.printStackTrace(); } } response.setContentType("text/html;charset=GBK"); PrintWriter out = response.getWriter(); System.out.println("测试聊天记录"+ChatService.instance().getMsg()); out.print(ChatService.instance().getMsg()); } 跳转后页面显示的url:[color=green]http://localhost:8080/welcome?name=join&password=789[/color]从url上看参数明明已经带过来了啊,可是我通过 String user=request.getParameter("name");或者 String user= (String) request.getSession(true).getAttribute("name"); 均获取不到name参数,请各位帮忙找找原因吧,谢谢!
Servlet遇到java.lang.NullPointerException问题无法解决,恳求帮助
各位大佬,最近用Jsp+servlet写教务管理系统,其中servlet端有一个问题始终无法解决 ``` 严重: Servlet.service() for servlet [com.jwglxt.data.searchStudent] in context with path [/jwglxt] threw exception java.lang.NullPointerException ``` 目的是根据从前台传来的查询类型和查询关键词在数据库中进行检索,目前前后端数据传递正常,NullPointerException这个问题始终得不到解决,尝试了很多办法都不行,恳请各位大佬施以援手! 代码如下: ```java package com.jwglxt.data; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; 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 org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; //思路:绑定一个弹出框在“搜索”按钮上,弹出框里放置一个datagrid,url为searchStudent @WebServlet("/searchStudent") public class searchStudent extends HttpServlet { @SuppressWarnings({ "null", "null", "null" }) protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置编码格式 request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/json; charset=utf-8"); //获取学生信息主码-学号(sno) String name=request.getParameter("name"); System.out.println("搜索类型:"+name); String value=request.getParameter("value"); System.out.println("搜索值:"+value); //姑且赋值 /*String name="sno"; String value="990101";*/ //连接数据库 Connection connection=null; String driverName="com.microsoft.sqlserver.jdbc.SQLServerDriver";//SQL数据库引擎 String dbURL="jdbc:sqlserver://localhost:1433;DatabaseName=tjl";//数据源 !!!注意若出现加载或者连接数据库失败一般是这里出现问题 String Name="sa"; String Pwd="19990713"; ResultSet rs=null; String sql="sql"; //定义JSON数组,用于保存从数据库查出来的数据 JSONArray array = new JSONArray(); try { Class.forName(driverName); connection=DriverManager.getConnection(dbURL,Name,Pwd); System.out.println("搜索学生:连接数据库成功"); } catch (ClassNotFoundException e2) { e2.printStackTrace(); }catch (SQLException e) { e.printStackTrace(); } //处理搜索类型 尝试switch语句 /*switch(name) { case "sno":{ try { sql="select * from student where sno=?"; connection.prepareStatement(sql); pstmt.setString(1,value); //rs=pstmt.executeQuery(sql); } catch (SQLException e) { e.printStackTrace(); };break; }//case }//switch */ //处理搜索类型 尝试If语句 if(name!=null) { if("sno".equals(name)){ try { //仅构造SQL语句,暂不运行 sql="select * from student where sno=?"; PreparedStatement pstmt=connection.prepareStatement(sql); pstmt.setString(1,value); rs = pstmt.executeQuery(sql); } catch (SQLException e) { e.printStackTrace(); } } else if("sname".equals(name)){ try { //仅构造SQL语句,暂不运行 sql="select * from student where sname=?"; PreparedStatement pstmt=connection.prepareStatement(sql); pstmt.setString(1,value); rs = pstmt.executeQuery(sql); } catch (SQLException e) { e.printStackTrace(); } } else if("sex".equals(name)){ try { //仅构造SQL语句,暂不运行 sql="select * from student where sex=?"; PreparedStatement pstmt=connection.prepareStatement(sql); pstmt.setString(1,value); rs = pstmt.executeQuery(sql); } catch (SQLException e) { e.printStackTrace(); } } else if("dno".equals(name)){ try { //仅构造SQL语句,暂不运行 sql="select * from student where dno=?"; PreparedStatement pstmt=connection.prepareStatement(sql); pstmt.setString(1,value); rs = pstmt.executeQuery(sql); } catch (SQLException e) { e.printStackTrace(); } } else { try { //仅构造SQL语句,暂不运行 sql="select * from student where dormno=?"; PreparedStatement pstmt=connection.prepareStatement(sql); pstmt.setString(1,value); rs = pstmt.executeQuery(sql); } catch (SQLException e) { e.printStackTrace(); } } System.out.println(sql); } try { // 获取列数 ResultSetMetaData metaData = rs.getMetaData(); int columnCount = metaData.getColumnCount(); while (rs.next()) { JSONObject jsonObj = new JSONObject(); // 遍历每一列 for (int i = 1; i <= columnCount; i++) { String columnName =metaData.getColumnLabel(i); String value2 = rs.getString(columnName); try { jsonObj.put(columnName, value2); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } array.put(jsonObj); } } catch (SQLException e1) { e1.printStackTrace(); } //关闭 try { if(rs!=null) rs.close(); //pstmt.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } //PrintWriter out = response.getWriter(); System.out.println(array); }//总类 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } public static void main(String args[]) { searchStudent ss=new searchStudent(); try { ss.doGet(null, null); } catch (ServletException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ```
servlet 过滤(filter)
======================== EncodingFilter.java ======================== package filter; import javax.servlet.FilterChain; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletException; import javax.servlet.FilterConfig; public class EncodingFilter implements Filter{ private String targetEncoding = "gb2312"; protected FilterConfig filterConfig; public void init(FilterConfig config) throws ServletException { this.filterConfig = config; this.targetEncoding = config.getInitParameter("encoding"); } public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)throws IOException, ServletException { request.setCharacterEncoding(targetEncoding);//把请求用指定的方式编码 // 把处理发送到下一个过滤器 chain.doFilter(request,response); } public void destroy() { this.filterConfig=null; } public void setFilterConfig(final FilterConfig filterConfig) { this.filterConfig=filterConfig; } } ===================== web.xml ===================== <filter> <filter-name>encoding</filter-name> <filter-class>filter.EncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>gb2312</param-value> </init-param> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>*</url-pattern> </filter-mapping> 我觉得这样写应该可以实现过滤,但没能,请大家看一下,问题的症结在哪儿.谢谢了
java web使用filter更改字符编码
filterName.jsp ``` <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title></title> </head> <body> <form action="servlet/DealWithForm" method="post"> 学生姓名: <input type="text" name="stuname"><br> <input type="submit" value="显示"> </form> </body> </html> ``` filter.java ``` package filter; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.Filter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.sun.net.httpserver.Filter.Chain; public class filter implements Filter { public filter() { super(); } private FilterConfig filterConfig; public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; } public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) { try { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; HttpSession session = request.getSession(); request.setCharacterEncoding("utf-8"); // response.setCharacterEncoding("GBK"); // response.setCharacterEncoding("gbk"); // response.setContentType("text/html;charset=gbk"); //code when login filterChain.doFilter(req, res); //code when logout } catch (IOException e) { e.printStackTrace(); } catch (ServletException e) { e.printStackTrace(); } } public void destroy() { //put destroy string in log //put your code } } ``` DealWithForm.java ``` 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; public class DealWithForm extends HttpServlet { /** * Constructor of the object. */ public DealWithForm() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // response.setContentType("text/html"); try { // PrintWriter out = response.getWriter(); String name=request.getParameter("stuname"); System.out.print("学生姓名:"+name); // System.out.print("学生姓名:"+name); } catch(Exception e) { e.printStackTrace(); } /* out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the GET method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); */ } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // response.setContentType("text/html"); try { // PrintWriter out = response.getWriter(); String name=request.getParameter("stuname"); System.out.println("学生姓名:"+name); } catch(Exception e) { e.printStackTrace(); } /* out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the POST method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); */ } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } } ``` web.xml ``` <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name></display-name> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>DealWithForm</servlet-name> <servlet-class>servlet.DealWithForm</servlet-class> </servlet> <servlet-mapping> <servlet-name>DealWithForm</servlet-name> <url-pattern>/servlet/DealWithForm</url-pattern> </servlet-mapping> <filter> <filter-name>filter</filter-name> <filter-class>filter.filter</filter-class> </filter> <filter-mapping> <filter-name>filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app> ``` * 想将filter.java中的 ``` request.setCharacterEncoding("utf-8"); ``` 改成 ``` request.setCharacterEncoding("GBK"); ``` 以更改编码方式,但是输出乱码(utf-8正常)
跪求高手帮忙看下程序为什么android连接不到servlet上,谢谢大家了
android客户端 package com.android.helloworld; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class ButtonDemo extends Activity{ private Button button; private String username; private String psw; private EditText editText; private EditText editText2; public void onCreate(Bundle queding){ super.onCreate(queding); /** * 设置界面 */ setContentView(R.layout.activity_main); /** * 根据ID找到界面上的按钮对象 */ button=(Button) findViewById(R.id.button1); /** * 为按钮绑定点击时间 */ button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { /** * 根据ID找到界面中的输入框 */ editText=(EditText) findViewById(R.id.editText1); /** * 根据ID找到界面中的输入框 */ editText2=(EditText) findViewById(R.id.editText2); /** * 把输入框中的内容去除空格后获得并且交给变量 */ username=editText.getText().toString().trim(); /** * 把输入框中的内容去除空格后获得并且交给变量 */ psw=editText2.getText().toString().trim(); /** * 构建需要传输的XML */ /** * 将构建的XML转化成字符串 */ String xml="username"+username+"psw"+psw; // /** // * 打印日志 // */ // Log.i("得到数据", "用户名"+username+"密码"+psw); /** * 打印看获得的数据和用户输入的数据是否一样 */ System.out.println("用户名"+username+"密码"+psw); try { /** * 服务器位置 */ URL url=new URL("http://127.0.0.1:8080/TestAndroid/1.do"); /** * 打开一个服务器的连接 */ HttpURLConnection connection=(HttpURLConnection) url.openConnection(); /** * 设置超时时间 单位毫秒 */ connection.setConnectTimeout(5000); /** * 允许输入 */ connection.setDoInput(true); /** * 允许输出 */ connection.setDoOutput(true); /** * 设置不允许用缓存 */ connection.setUseCaches(false); /** * 设置请求方法 */ connection.setRequestMethod("POST"); /** * 设置发送字符串的编码格式 */ connection.setRequestProperty("Conten-Type", "text/xml;charset=UTF-8"); /** * 通过IO流的方式发送数据给服务器 */ OutputStream outputStream=connection.getOutputStream(); /** * 设置将XML转化为字节的形式进行传输,编码方式是UTF-8 */ outputStream.write(xml.getBytes("UTF-8")); /** * 将输出流交给数据流发送 */ DataOutputStream dataOutputStream=new DataOutputStream(outputStream); /** * 将数据发送出去并且清空数据输出流 */ dataOutputStream.flush(); /** * 关闭输出流并且释放占用的资源空间 */ dataOutputStream.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }); } } servlet端 package testservlet; import java.io.BufferedInputStream; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class TestServlet extends HttpServlet { public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); // response.setContentType("text/xml;charset=utf-8"); // BufferedInputStream bufferedInputStream=new BufferedInputStream(request.getInputStream()); // byte[] bytes=new byte[1024*1024]; // int len=0; // while((len=bufferedInputStream.read(bytes))!=-1){ // System.out.println(bytes); // System.out.println(bytes.toString()); // } // System.out.println(len); System.out.println(111111); } } 有知道的告诉下怎么才可以解决 谢谢了 QQ704532683
Servlet验证出现405错误,HTTP method POST is not supported by this URL
我找了很久确实没有找出错误!!看看错在哪儿行吗? 谢谢!! 我用Form表单提交: [code="html"] <form action="user_dao_servlet" method="post"> 用户名: <input type="text" name="userName"/><br> 密码: <input type="password" name="userPassword"/><br> 确认密码: <input type="password" name="confirmPassword"/><br> 邮箱: <input type="text" name="userEmail"/><br> 安全问题: <input type="text" name="userQuestion"/><br> 答案: <input type="text" name="userAnswer"/><br> <input type="submit" value="提交"/> <input type="reset" value="重置"/> </form>[/code] 以下是我的Servlet代码: [code="java"]public class UserDAOServlet extends HttpServlet { public class UserLoginServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); //统一设置编码 String page = "user_register.jsp"; String code = request.getParameter("code"); List<String> errors = new ArrayList<String>(); // 验证码验证 if (code == null || "".equals(code)) { errors.add("验证码为空!"); } else { String rand = (String) request.getSession().getAttribute("rand"); if (!code.equalsIgnoreCase(rand)) { errors.add("验证码错误!!") ; } } //取出接受参数进行验证 String userName = request.getParameter("userName"); String userPassword = request.getParameter("userPassword"); String confirmPassword = request.getParameter("confirmPassword"); String userEmail = request.getParameter("userEmail"); String userQuestion = request.getParameter("userQuestion"); String userAnswer = request.getParameter("userAnswer"); String userRealName = request.getParameter("userRealName"); String tele = request.getParameter("tele"); String address = request.getParameter("address"); String sex = request.getParameter("sex"); if(!(userPassword.equals(confirmPassword))){ errors.add("两次输入密码不一样!"); } if (userName == null || "".equals(userName)) { errors.add("用户名不能为空!"); } if (userPassword == null || "".equals(userPassword)) { errors.add("密码不能为空!"); } if(errors.size()==0){ // 现在没有任何的错误信息 User vo=new User(); vo.setUserName(userName); vo.setUserPassword(new MD5Code().getMD5ofStr(userPassword)) ; vo.setAddress(address); vo.setSex(sex); vo.setTele(tele); vo.setUserQuestion(userQuestion); vo.setUserAnswer(userAnswer); vo.setUserEmail(userEmail); vo.setUserRealName(userRealName); try { if(DAOFactory.getIUserDAOInstance().doCreate(vo)){ request.getSession().setAttribute("user", vo) ; // 现在保存对象 request.setAttribute("userName", userName); page = "register_success.jsp" ; } else { errors.add("用户名或密码错误!"); } } catch (Exception e) { e.printStackTrace(); } } request.setAttribute("errors", errors) ; request.getRequestDispatcher(page).forward(request, response); } } }[/code] 以下是在WEB.XML里面的配置: [code="xml"]<servlet> <servlet-name>userDAO</servlet-name> <servlet-class>org.mm.servlet.UserDAOServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>userDAO</servlet-name> <url-pattern>/user_dao_servlet</url-pattern> </servlet-mapping> [/code]
Servlet中doget()方法写文件发生中文乱码,如何解决?
作业需求:登陆注册系统中,注册时会调用一个方法来创建一个文件写入用户的密码、科目等信息,在doget()中调用该方法。随后在浏览器地址栏上写参数信息,科目的参数中有中文,结果看创建的文件该参数乱码了,显示一串问号。故登陆时也不能确认信息从而无法登陆。 PS:dopost()能较好实现,但作业任务要求doget()也实现,故提出此疑问。 调试时地址栏的输入: ``` http://localhost:8080/test3_1/register.do?email=1223@123.com&username=123&password=123123123&confirmedPasswd=123123123&subject=计算机 ``` doget()相关代码 ``` protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("utf-8"); String subject = request.getParameter("subject"); byte b[]=subject.getBytes("UTF-8"); subject=new String(b,"UTF-8"); String email = request.getParameter("email"); String username = request.getParameter("username"); String password = request.getParameter("password"); String confirmedPasswd = request.getParameter("confirmedPasswd"); System.out.println(subject); List<String> errors = new ArrayList<String>(); if (isInvalidEmail(email)) { errors.add("未填写邮件或邮件格式不正确"); } if (isInvalidUsername(username)) { errors.add("用户名称为空或已存在"); } if (isInvalidPassword(password, confirmedPasswd)) { errors.add("请确认密码符合格式并再次确认密码"); } String resultPage = ERROR_VIEW; if (!errors.isEmpty()) { request.setAttribute("errors", errors); } else { resultPage = SUCCESS_VIEW; createUserData(email, username, password, subject); } request.getRequestDispatcher(resultPage).forward(request, response); } ``` 写文件方法 ``` private void createUserData(String email, String username, String password, String subject) throws IOException { File userhome = new File(USERS + "/" + username); userhome.mkdir(); BufferedWriter writer = new BufferedWriter(new FileWriter(userhome + "/profile.txt")); writer.write(email + "\t" + password + "\t" + subject); writer.close(); } ``` 显示页面html ``` <!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>注册会员</title> </head> <body> <h1>会员注册</h1> <form method='post' action='register.do'> <table bgcolor=#cccccc> <tr> <td>邮件地址:</td> <td><input type='text' name='email' size='25' maxlength='100'> </td> </tr> <tr> <td>用户名(最大16字符):</td> <td><input type='text' name='username' size='25' maxlength='16'> </td> </tr> <tr> <td>密码(6到16字符):</td> <td><input type='password' name='password' size='25' maxlength='16'> </td> </tr> <tr> <td>确认密码:</td> <td><input type='password' name='confirmedPasswd' size='25' maxlength='16'> </td> </tr> <tr> <td>专业:</td> <td><select name="subject" size="1" > <option value="计算机">计算机</option> <option value="软件工程">软件工程</option> <option value="网络工程">网络工程</option> </select></td> </tr> <tr> <td colspan='2' align='center'><input type='submit' value='注册'> </td> </tr> </table> </form> </body> </html> ``` 写后直接记事本打开,发现输入的subject参数一串问号。 已经查阅百度,写的编码或字符编码转换也应该加上了的,但还是不能解决。 希望有前辈补坑
为什么我的我用AJAX提交数据到Servlet最后数据始终是乱码??
这是jsp的页面,数据提交到doPost,然后响应到div里面显示,但是 AJAX中的中文数据提交到Servlet 始终是乱码;怎么改啊,大神们。。。 ``` <%@ 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"> <!-- 引入写了AJAX的js文件 --> <script type="text/javascript" src="${pageContext.request.contextPath }/AJAXDemo02POST/ajax_posttext.js"></script> <title>Insert title here</title> </head> <body> <h1>AJAX POST获取数据的练习</h1> <div style="width:300px;height:200px;border:1px solid red;" id="divajax"></div> <input type="button" value="点我获取数据" onclick="ajaxPostText()"/> </body> </html> ``` 这是 写了AJAX的js的文件 function ajaxPostText(){ // 创建异步对象: var xhr = createXMLHttp(); // 设置监听: xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 200){ document.getElementById("divajax").innerHTML = xhr.responseText; } } } // 打开路径: xhr.open("POST","/AJAXDemo01/AJAXDemo01Servlet",true); //这一句没能将提交到post的中文数据编码改掉 xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); // 发送请求: xhr.send("name=张三&pass=密码"); } function createXMLHttp() { var xmlHttp; try { // Firefox, Opera 8.0+, Safari xmlHttp = new XMLHttpRequest(); } catch (e) { try {// Internet Explorer xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { } } } return xmlHttp; } 这是Servlet代码 public class AJAXDemo01Servlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//未完成 request.setCharacterEncoding("UTF-8"); String pass =request.getParameter("pass"); String name = request.getParameter("name"); response.setContentType("text/html;charset=UTF-8"); response.getWriter().println( "名称是:" + name + "密码是:" + pass); System.out.println("名称是:" + name + "密码是:" + pass); } } ![图片说明](https://img-ask.csdn.net/upload/201709/17/1505634495_151318.png)
关于Red5整合自己写好的web项目
写了一个Red5的Demo可以成功运行 现在想整合进我的项目里面 也可以实现在线看视频 但是整合web.xml报错 万千搞不懂为啥 下面贴下web.xml的代码 希望大神指教 自己弄了好久了 报错:java.lang.IllegalStateException: Cannot initialize context because there is already a root application context present - check whether you have multiple ContextLoader* definitions in your web.xml! ``` <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <jsp-config> <taglib> <taglib-uri>http://www.keji09.com/jstl/11erp</taglib-uri> <taglib-location>/WEB-INF/classes/com/keji09/erp/jstl/tag/11erp.tld</taglib-location> </taglib> </jsp-config> <!-- red5 --> <context-param> <param-name>globalScope</param-name> <param-value>default</param-value> </context-param> <context-param> <param-name>parentContextKey</param-name> <param-value>default.context</param-value> </context-param> <context-param> <param-name>webAppRootKey</param-name> <param-value>/micro_film</param-value> </context-param> <!-- red5 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml, WEB-INF/classes/*-web.xml </param-value> </context-param> <!-- red5 --> <listener> <listener-class>org.red5.server.war.WarLoaderServlet</listener-class> </listener> <listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener> <!-- red5 --> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <filter> <filter-name>SetCharacterEncoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>SetCharacterEncoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>HiddenHttpMethodFilter</filter-name> <filter-class> org.springframework.web.filter.HiddenHttpMethodFilter </filter-class> </filter> <filter-mapping> <filter-name>HiddenHttpMethodFilter</filter-name> <servlet-name>SpringDispatcherServlet</servlet-name> </filter-mapping> <servlet> <servlet-name>SpringDispatcherServlet</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext_controller.xml</param-value> </init-param> <load-on-startup>0</load-on-startup> </servlet> <!-- red5 --> <servlet> <servlet-name>gateway</servlet-name> <servlet-class>org.red5.server.net.servlet.AMFGatewayServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet> <servlet-name>rtmpt</servlet-name> <servlet-class>org.red5.server.net.rtmpt.RTMPTServlet</servlet-class> <load-on-startup>2</load-on-startup> </servlet> <!-- red5 --> <servlet-mapping> <servlet-name>SpringDispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> <url-pattern>*.css</url-pattern> <url-pattern>*.gif</url-pattern> <url-pattern>*.jpeg</url-pattern> <url-pattern>*.png</url-pattern> <url-pattern>*.jpg</url-pattern> <url-pattern>*.woff</url-pattern> <url-pattern>*.woff2</url-pattern> <url-pattern>*.tff</url-pattern> <url-pattern>*.ico</url-pattern> <url-pattern>*.doc</url-pattern> <url-pattern>*.docx</url-pattern> <url-pattern>*.xls</url-pattern> <url-pattern>*.xlsx</url-pattern> <url-pattern>*.txt</url-pattern> <url-pattern>*.mp4</url-pattern> <url-pattern>*.ogg</url-pattern> <url-pattern>*.DOCX</url-pattern> <url-pattern>*.XLS</url-pattern> <url-pattern>*.XLSX</url-pattern> <url-pattern>*.TXT</url-pattern> <url-pattern>*.DOC</url-pattern> <url-pattern>*.JS</url-pattern> <url-pattern>*.ICO</url-pattern> <url-pattern>*.CSS</url-pattern> <url-pattern>*.GIF</url-pattern> <url-pattern>*.JPEG</url-pattern> <url-pattern>*.PNG</url-pattern> <url-pattern>*.JPG</url-pattern> <url-pattern>*.WOFF</url-pattern> <url-pattern>*.TFF</url-pattern> <url-pattern>*.html</url-pattern> </servlet-mapping> <!-- red5 --> <servlet-mapping> <servlet-name>gateway</servlet-name> <url-pattern>/gateway</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>rtmpt</servlet-name> <url-pattern>/fcs/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>rtmpt</servlet-name> <url-pattern>/open/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>rtmpt</servlet-name> <url-pattern>/idle/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>rtmpt</servlet-name> <url-pattern>/send/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>rtmpt</servlet-name> <url-pattern>/close/*</url-pattern> </servlet-mapping> <security-constraint> <web-resource-collection> <web-resource-name>Forbidden</web-resource-name> <url-pattern>/WEB-INF/*</url-pattern> </web-resource-collection> <auth-constraint /> </security-constraint> <security-constraint> <web-resource-collection> <web-resource-name>Forbidden</web-resource-name> <url-pattern>/persistence/*</url-pattern> </web-resource-collection> <auth-constraint /> </security-constraint> <security-constraint> <web-resource-collection> <web-resource-name>Forbidden</web-resource-name> <url-pattern>/streams/*</url-pattern> </web-resource-collection> <auth-constraint /> </security-constraint> <!-- red5 --> </web-app> ```
《MySQL 性能优化》之理解 MySQL 体系结构
本文介绍 MySQL 的体系结构,包括物理结构、逻辑结构以及插件式存储引擎。
程序员请照顾好自己,周末病魔差点一套带走我。
程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。
卸载 x 雷某度!GitHub 标星 1.5w+,从此我只用这款全能高速下载工具!
作者 | Rocky0429 来源 | Python空间 大家好,我是 Rocky0429,一个喜欢在网上收集各种资源的蒟蒻… 网上资源眼花缭乱,下载的方式也同样千奇百怪,比如 BT 下载,磁力链接,网盘资源等等等等,下个资源可真不容易,不一样的方式要用不同的下载软件,因此某比较有名的 x 雷和某度网盘成了我经常使用的工具。 作为一个没有钱的穷鬼,某度网盘几十 kb 的下载速度让我...
讲真,这两个IDE插件,可以让你写出质量杠杠的代码
周末躺在床上看《拯救大兵瑞恩》 周末在闲逛的时候,发现了两个优秀的 IDE 插件,据说可以提高代码的质量,我就安装了一下,试了试以后发现,确实很不错,就推荐给大家。 01、Alibaba Java 代码规范插件 《阿里巴巴 Java 开发手册》,相信大家都不会感到陌生,其 IDEA 插件的下载次数据说达到了 80 万次,我今天又贡献了一次。嘿嘿。 该项目的插件地址: https://github....
为什么猝死的都是程序员,基本上不见产品经理猝死呢?
相信大家时不时听到程序员猝死的消息,但是基本上听不到产品经理猝死的消息,这是为什么呢? 我们先百度搜一下:程序员猝死,出现将近700多万条搜索结果: 搜索一下:产品经理猝死,只有400万条的搜索结果,从搜索结果数量上来看,程序员猝死的搜索结果就比产品经理猝死的搜索结果高了一倍,而且从下图可以看到,首页里面的五条搜索结果,其实只有两条才是符合条件。 所以程序员猝死的概率真的比产品经理大,并不是错...
害怕面试被问HashMap?这一篇就搞定了!
声明:本文以jdk1.8为主! 搞定HashMap 作为一个Java从业者,面试的时候肯定会被问到过HashMap,因为对于HashMap来说,可以说是Java集合中的精髓了,如果你觉得自己对它掌握的还不够好,我想今天这篇文章会非常适合你,至少,看了今天这篇文章,以后不怕面试被问HashMap了 其实在我学习HashMap的过程中,我个人觉得HashMap还是挺复杂的,如果真的想把它搞得明明白...
毕业5年,我问遍了身边的大佬,总结了他们的学习方法
我问了身边10个大佬,总结了他们的学习方法,原来成功都是有迹可循的。
python爬取百部电影数据,我分析出了一个残酷的真相
2019年就这么匆匆过去了,就在前几天国家电影局发布了2019年中国电影市场数据,数据显示去年总票房为642.66亿元,同比增长5.4%;国产电影总票房411.75亿元,同比增长8.65%,市场占比 64.07%;城市院线观影人次17.27亿,同比增长0.64%。 看上去似乎是一片大好对不对?不过作为一名严谨求实的数据分析师,我从官方数据中看出了一点端倪:国产票房增幅都已经高达8.65%了,为什...
推荐10个堪称神器的学习网站
每天都会收到很多读者的私信,问我:“二哥,有什么推荐的学习网站吗?最近很浮躁,手头的一些网站都看烦了,想看看二哥这里有什么新鲜货。” 今天一早做了个恶梦,梦到被老板辞退了。虽然说在我们公司,只有我辞退老板的份,没有老板辞退我这一说,但是还是被吓得 4 点多都起来了。(主要是因为我掌握着公司所有的核心源码,哈哈哈) 既然 4 点多起来,就得好好利用起来。于是我就挑选了 10 个堪称神器的学习网站,推...
这些软件太强了,Windows必装!尤其程序员!
Windows可谓是大多数人的生产力工具,集娱乐办公于一体,虽然在程序员这个群体中都说苹果是信仰,但是大部分不都是从Windows过来的,而且现在依然有很多的程序员用Windows。 所以,今天我就把我私藏的Windows必装的软件分享给大家,如果有一个你没有用过甚至没有听过,那你就赚了????,这可都是提升你幸福感的高效率生产力工具哦! 走起!???? NO、1 ScreenToGif 屏幕,摄像头和白板...
阿里面试,面试官没想到一个ArrayList,我都能跟他扯半小时
我是真的没想到,面试官会这样问我ArrayList。
曾经优秀的人,怎么就突然不优秀了。
职场上有很多辛酸事,很多合伙人出局的故事,很多技术骨干被裁员的故事。说来模板都类似,曾经是名校毕业,曾经是优秀员工,曾经被领导表扬,曾经业绩突出,然而突然有一天,因为种种原因,被裁员了,...
C语言荣获2019年度最佳编程语言
关注、星标公众号,不错过精彩内容作者:黄工公众号:strongerHuang近日,TIOBE官方发布了2020年1月编程语言排行榜单。我在前面给过一篇文章《2019年11月C语言接近Ja...
大学四年因为知道了这32个网站,我成了别人眼中的大神!
依稀记得,毕业那天,我们导员发给我毕业证的时候对我说“你可是咱们系的风云人物啊”,哎呀,别提当时多开心啦????,嗯,我们导员是所有导员中最帅的一个,真的???? 不过,导员说的是实话,很多人都叫我大神的,为啥,因为我知道这32个网站啊,你说强不强????,这次是绝对的干货,看好啦,走起来! PS:每个网站都是学计算机混互联网必须知道的,真的牛杯,我就不过多介绍了,大家自行探索,觉得没用的,尽管留言吐槽吧???? 社...
良心推荐,我珍藏的一些Chrome插件
上次搬家的时候,发了一个朋友圈,附带的照片中不小心暴露了自己的 Chrome 浏览器插件之多,于是就有小伙伴评论说分享一下我觉得还不错的浏览器插件。 我下面就把我日常工作和学习中经常用到的一些 Chrome 浏览器插件分享给大家,随便一个都能提高你的“生活品质”和工作效率。 Markdown Here Markdown Here 可以让你更愉快的写邮件,由于支持 Markdown 直接转电子邮...
看完这篇HTTP,跟面试官扯皮就没问题了
我是一名程序员,我的主要编程语言是 Java,我更是一名 Web 开发人员,所以我必须要了解 HTTP,所以本篇文章就来带你从 HTTP 入门到进阶,看完让你有一种恍然大悟、醍醐灌顶的感觉。 最初在有网络之前,我们的电脑都是单机的,单机系统是孤立的,我还记得 05 年前那会儿家里有个电脑,想打电脑游戏还得两个人在一个电脑上玩儿,及其不方便。我就想为什么家里人不让上网,我的同学 xxx 家里有网,每...
应届生/社招面试最爱问的几道Java基础问题
本文已经收录自笔者开源的 JavaGuide: https://github.com/Snailclimb (【Java学习 面试指南】 一份涵盖大部分Java程序员所需要掌握的核心知识)如果觉得不错的还,不妨去点个Star,鼓励一下! 一 为什么 Java 中只有值传递? 首先回顾一下在程序设计语言中有关将参数传递给方法(或函数)的一些专业术语。按值调用(call by value)表...
史上最全的IDEA快捷键总结
现在Idea成了主流开发工具,这篇博客对其使用的快捷键做了总结,希望对大家的开发工作有所帮助。
阿里程序员写了一个新手都写不出的低级bug,被骂惨了。
这种新手都不会范的错,居然被一个工作好几年的小伙子写出来,差点被当场开除了。
谁是华为扫地僧?
是的,华为也有扫地僧!2020年2月11-12日,“养在深闺人不知”的华为2012实验室扫地僧们,将在华为开发者大会2020(Cloud)上,和大家见面。到时,你可以和扫地僧们,吃一个洋...
Idea 中最常用的10款插件(提高开发效率),一定要学会使用!
学习使用一些插件,可以提高开发效率。对于我们开发人员很有帮助。这篇博客介绍了开发中使用的插件。
AI 没让人类失业,搞 AI 的人先失业了
最近和几个 AI 领域的大佬闲聊 根据他们讲的消息和段子 改编出下面这个故事 如有雷同 都是巧合 1. 老王创业失败,被限制高消费 “这里写我跑路的消息实在太夸张了。” 王葱葱哼笑一下,把消息分享给群里。 阿杰也看了消息,笑了笑。在座几位也都笑了。 王葱葱是个有名的人物,21岁那年以全额奖学金进入 KMU 攻读人工智能博士,累计发表论文 40 余篇,个人技术博客更是成为深度学习领域内风向标。 ...
2020年,冯唐49岁:我给20、30岁IT职场年轻人的建议
点击“技术领导力”关注∆每天早上8:30推送 作者|Mr.K 编辑| Emma 来源|技术领导力(ID:jishulingdaoli) 前天的推文《冯唐:职场人35岁以后,方法论比经验重要》,收到了不少读者的反馈,觉得挺受启发。其实,冯唐写了不少关于职场方面的文章,都挺不错的。可惜大家只记住了“春风十里不如你”、“如何避免成为油腻腻的中年人”等不那么正经的文章。 本文整理了冯...
最全最强!世界大学计算机专业排名总结!
我正在参与CSDN200进20,希望得到您的支持,扫码续投票5次。感谢您! (为表示感谢,您投票后私信我,我把我总结的人工智能手推笔记和思维导图发送给您,感谢!) 目录 泰晤士高等教育世界大学排名 QS 世界大学排名 US News 世界大学排名 世界大学学术排名(Academic Ranking of World Universities) 泰晤士高等教育世界大学排名 中国共...
一份王者荣耀的英雄数据报告
咪哥杂谈本篇阅读时间约为 6 分钟。1前言前一阵写了关于王者的一些系列文章,从数据的获取到数据清洗,数据落地,都是为了本篇的铺垫。今天来实现一下,看看不同维度得到的结论。2环境准备本次实...
作为一名大学生,如何在B站上快乐的学习?
B站是个宝,谁用谁知道???? 作为一名大学生,你必须掌握的一项能力就是自学能力,很多看起来很牛X的人,你可以了解下,人家私底下一定是花大量的时间自学的,你可能会说,我也想学习啊,可是嘞,该学习啥嘞,不怕告诉你,互联网时代,最不缺的就是学习资源,最宝贵的是啥? 你可能会说是时间,不,不是时间,而是你的注意力,懂了吧! 那么,你说学习资源多,我咋不知道,那今天我就告诉你一个你必须知道的学习的地方,人称...
那些年,我们信了课本里的那些鬼话
教材永远都是有错误的,从小学到大学,我们不断的学习了很多错误知识。 斑羚飞渡 在我们学习的很多小学课文里,有很多是错误文章,或者说是假课文。像《斑羚飞渡》: 随着镰刀头羊的那声吼叫,整个斑羚群迅速分成两拨,老年斑羚为一拨,年轻斑羚为一拨。 就在这时,我看见,从那拨老斑羚里走出一只公斑羚来。公斑羚朝那拨年轻斑羚示意性地咩了一声,一只半大的斑羚应声走了出来。一老一少走到伤心崖,后退了几步,突...
一个程序在计算机中是如何运行的?超级干货!!!
强烈声明:本文很干,请自备茶水!???? 开门见山,咱不说废话! 你有没有想过,你写的程序,是如何在计算机中运行的吗?比如我们搞Java的,肯定写过这段代码 public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } ...
【蘑菇街技术部年会】程序员与女神共舞,鼻血再次没止住。(文末内推)
蘑菇街技术部的年会,别开生面,一样全是美女。
那个在阿里养猪的工程师,5年了……
简介: 在阿里,走过1825天,没有趴下,依旧斗志满满,被称为“五年陈”。他们会被授予一枚戒指,过程就叫做“授戒仪式”。今天,咱们听听阿里的那些“五年陈”们的故事。 下一个五年,猪圈见! 我就是那个在养猪场里敲代码的工程师,一年多前我和20位工程师去了四川的猪场,出发前总架构师慷慨激昂的说:同学们,中国的养猪产业将因为我们而改变。但到了猪场,发现根本不是那么回事:要个WIFI,没有;...
立即提问