UTF-8 encoding in JSP page [duplicate]
I have a JSP
page whose page encoding is ISO-8859-1
. This JSP page there is in a question answer blog. I want to include special characters during Q/A posting.
The problem is JSP is not supporting UTF-8
encoding even I have changed it from ISO-8859-1
to UTF-8
. These characters (~
,%
,&
,+
) are making problem. When I am posting these character either individually or with the combination of any character it is storinh null
in the database and when I remove these characters while posting application it is working fine.
Can any one suggest some solution?
Solution 1:
You should use the same encoding on all layers of your application to avoid this problem. It is useful to add a filter to set the encoding:
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain) throws ServletException {
request.setCharacterEncoding("UTF-8");
chain.doFilter(request, response);
}
To only set the encoding on your JSP pages, add this line to them:
<%@ page contentType="text/html; charset=UTF-8" %>
Configure your database to use the same char encoding as well.
If you need to convert the encoding of a string see:
- Encoding conversion in java
I would not recommend to store HTML encoded text in your database. For example, if you need to generate a PDF (or anything other than HTML) you need to convert the HTML encoding first.
Solution 2:
The full JSP tag should be something like this, mind the pageEncoding too:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
Some old browsers mess up with the encoding too. you can use the HTML tag
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
Also the file should be recorded in UTF-8 format, if you are using Eclipse left-click on the file->Properties->Check out ->Text file encoding.
Solution 3:
I also had an issue displaying charectors like "Ṁ Ů".I added the following to my web.xml.
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<page-encoding>UTF-8</page-encoding>
</jsp-property-group>
</jsp-config>
This solved the issue in the pages except header. Tried many ways to solve this and nothing worked in my case. The issue with header was header jsp page is included from another jsp. So gave the encoding to the import and that solved my problem.
<c:import url="/Header1.jsp" charEncoding="UTF-8"/>
Thanks