I have a demo web application that creates users. When I try to insert data in other languages (like french) the characters are not encoded correctly. The code on the controller is:
#SuppressWarnings("unchecked")
#RequestMapping(value = "/user/create.htm", params={"id"}, method = RequestMethod.GET)
public String edit(#RequestParam("id") Long id, ModelMap model) {
System.out.println("id is " + id);
User user = userService.get(id);
model.put("user", user);
return "user/create";
}
#RequestMapping(value = "/user/create.htm", method = RequestMethod.POST)
public String save(#ModelAttribute("user") User user, BindingResult result) {
System.out.println(user.getFirstName());
System.out.println(user.getLastName());
validator.validate(user, result);
if(result.hasErrors()) {
return "user/create";
}
userService.save(user);
return "redirect:list.htm";
}
my web.xml is:
...
<filter>
<filter-name>encoding-filter</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>encoding-filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
...
and the page is:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<!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">
...
<form:form method="post" commandName="user">
...
<form:input path="firstName" cssErrorClass="form-error-field"/>
...
when I enter some french characters in the first name then the output from the system.out.println is ????+????? or something similar.
I saw other people fixing this with the CharacterEncodingFilter but this doesn't seem to work.
Thanks a lot.
Edited the filter value.
Try making CharacterEncodingFilter the first filter in web.xml.
I realize this question is a little old, but I just ran into the same problem, and moving CharacterEncodingFilter fixed it for me.
If this still does not work and you're using Tomcat as your application server try to set the following option on every <Connector> element in the server.xml:
<Connector URIEncoding="UTF-8" ...>
...
</Connector>
This did the trick for me. There might be similar options for other application servers, so you might want to check the server documentation.
Perhaps I'm missing something, but if the page-encoding in your JSP is "UTF-8", shouldn't the encoding in your CharacterEncodingFilter be UTF-8 rather than ISO-8859-7?
You need to add accept-charset="UTF-8" to your form.
Output of System.out.println() depends on console encoding, so it's not a good way to debug encoding problems.
To check that your values are decoded properly, you should show it at another page. Actually, it's already done in the case of form validation failure, so your system works fine if values in the fields remains the same after validation error.
There are two things to help:
In your setenv.sh file add JAVA_OPTS="$JAVA_OPTS -Dfile.encoding=utf-8"
In the script that starts your tomcat process, set the LANG environment: export LANG='utf-8'
This can then be tested by examining the default character set: Charset.defaultCharset().
Related
I'm a beginner in spring programming. (i'm not good in english)
I have a problem that I can not get value from the controller.
My previous jsp worked fine, but I did not work with this project about a week then back to work, and i founded all jsp that I created after can not get value from the controller. But my previous jsp page worked fine.
I have seen on the same question and they said the error focus on version in web.xml but I dont have this error because the previous page jsp is still work fine.
Web.xml
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"
JSP file
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<%# page isELIgnored="false" %>
</head>
<body> <h1>${check}</h1> </body> </html>
Controller
#Controller
public class SingleController {
#RequestMapping(value="/single", method=RequestMethod.GET)
public ModelAndView single() {
ModelAndView mav = new ModelAndView();
mav.setViewName("single");
mav.addObject("check", "123");
return mav;
}
}
i have a spring application and while i am deploying it in weblogic server it is giving 404 Error.
in web.xml i given index.jsp as welcome file and from that i am redirecting to controller class but it is not working
here is my web.xml
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
<url-pattern>*.do</url-pattern>
<url-pattern>/*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
here is my index.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<c:redirect url="/result"/>
</body>
</html>
here is my controller class method
#RequestMapping(value="/result" , method=RequestMethod.GET)
public String getResults(ModelMap map){
map.put("userList","null");
System.out.println("result page ...");
return "result";
}
the above logic is woking in tomcat but it is not working in weblogic server
please any body help me.
here i created as a war and i am deploying in weblogic server.
Can you change
<url-pattern>/*.html</url-pattern>
to
<url-pattern>/*.jsp</url-pattern>
Edit
Try doing the following
#RequestMapping(value="/result" , method=RequestMethod.GET)
public String getResults(ModelMap map){
map.put("userList","null");
System.out.println("result page ...");
return "redirect:"+ Your_Url;
}
I'm following a tutorial about spring and I'm supposed to set a variable in a controller in order to be printed within the jsp rendering the request. The code is as follows:
#Controller
public class HelloController {
#RequestMapping(value="/hello.htm")
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String now = (new Date()).toString();
return new ModelAndView("WEB-INF/views/hello.jsp", "now", now);
}
}
Then, the hello.jsp code is as follows:
<%# page session="true"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<body>
<p>Greetings, it is now <c:out value="${now}" /></p>
</body>
</html>
I am expected to get an html showing this:
Greetings, it is now Mon Fri Dec 06 00:39:35 CET 2013
But all I get is:
Greetings, it is now ${now}
I've checked everything twice (or even more!) but everything seems to be as the tutorial says but there must be something missing, I hope...
What's wrong with my code?
This is an E xpression L anguage issue. Your ${} is not being resolved. This can happen for a number of reasons. One, and the most likely, is that your web.xml is declaring Servlet 2.3 and under. You'll have to specify 2.4+. Now, obviously, your Servlet container must also support that higher version.
Change this - the pad a library is bad:
<!-- %# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>-->
<%# taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
I'm using Sping MVC with freemarker views. I set up a FreeMarkerViewResolver to resolve the views and it works so far but now I have encoding problems. All my views are HTML 5 pages in UTF-8 encoding and I also added a <meta charset="UTF-8" /> to the HTML page but characters are still printed in the wrong encoding. I checked the HTTP headers with curl and found this:
k#jules:~$ curl -I http://localhost:8080/testweb/test.view
HTTP/1.1 200 OK
Content-Type: */*;charset=ISO-8859-1
But when I request some non-existing resource (Which generates a Tomcat error) then I get this:
k#jules:~$ curl -I http://localhost:8080/testweb/nothere.html
HTTP/1.1 200 OK
Content-Type: text/html;charset=utf-8
So Tomcat itself returns the correct content-type but a Spring MVC Freemarker views don't.
For a JSP I can set the Content-Type in the JSP header but where can I set it for a freemarker template? I guess I have to do this somewhere in the Spring bean configuration but I can't find the right place.
The view resolver (should be in your dispatcher-servlet.xml) has a contentType property for that:
<bean id="viewResolver"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="prefix" value=""/>
<property name="suffix" value=".ftl"/>
<property name="contentType" value="text/html;charset=UTF-8"/>
</bean>
I have also experienced a problem with showing UTF-8 characters (special characters like æ. ø and å etc.), when using spring framework and freemarker template.
What i did was.
1. Ensure that your .ftl page is encoded with utf-8
This is an important thing to ensure, that a page not encoded with UTF-8 charset, could show the wrong numbers even though you have all the other requirements set. Check your IDE settings, to find out which default encoding it sets your files to. I think however today that both Eclipse and NetBeans set all files with UTF-8 encoding as standard. You must ensure that it is encoding UTF-8 with no BOM.
2. Include the Meta tag in your template file to set the charset
In your template (.ftl) file, which holds your <head> tag, set a <meta>, with the attribute charset="UTF-8". This is if you use HTML 5. If you use xhtml or HTML 4, your meta tag needs to look like this
HTML 5 <meta charset="UTF-8" />
HTML 4/XHTML <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
3. Make sure you set a Character Encoding Filter in your Deployment Descriptor File
You have to filter all incoming/outgoing requests through a character encoding filter. This filter is set in your deployment descriptor (web.xml / or the java equivalent WebApplicationInitializer).
WebApplicationInitializer (Java File)
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
registerCharacterEncodingFilter(servletContext);
}
/**
* Filter all incoming requests with character encoding UTF-8
* #param servletContext
*/
private void registerCharacterEncodingFilter(ServletContext servletContext) {
CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
encodingFilter.setEncoding("UTF-8");
encodingFilter.setForceEncoding(true);
FilterRegistration.Dynamic characterEncodingFilter = servletContext.addFilter("characterEncodingFilter", encodingFilter);
characterEncodingFilter.addMappingForUrlPatterns(null, false, "/*");
}
web.xml
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
4. Set the FreeMarker Character Encoding in configurer and view resolver
You also need to make all your FreeMarker files be standard encoded with UTF-8, this is done by setting their properties to UTF-8 in the FreeMarkerConfigurer and the FreeMarkerViewResolver. This is set in your spring application context file (I will only show the Java equivalent as it is the same in the XML file).
/**
* FreeMarker Configurer will help configure different settings of
* the FreeMarker template engine.
*
* #return an object of the FreeMarkerConfigurer class.
*/
#Bean
public FreeMarkerConfigurer freemarkerConfig() {
FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
freeMarkerConfigurer.setTemplateLoaderPath("/templates/");
freeMarkerConfigurer.setDefaultEncoding("UTF-8");
return freeMarkerConfigurer;
}
/**
* The View resolver to use when resolving FreeMarker views.
*
* #return the View Resolver Object used to resolve FreeMarker views.
*/
#Bean
public FreeMarkerViewResolver viewResolver() {
FreeMarkerViewResolver viewResolver = new FreeMarkerViewResolver();
viewResolver.setPrefix("");
viewResolver.setSuffix(".ftl");
viewResolver.setCache(false); //Set to true during production
viewResolver.setContentType("text/html;charset=UTF-8");
return viewResolver;
}
Hope this helps you out :)
I tried to run the following lines.
<%=application.getInitParameter("tagline")%>
<br />
<%=config.getInitParameter("admincontact")%>
${initParam.tagline}
<br />
${pageContext.servletConfig.initParameter("admincontact")}
And my web.xml is
<servlet>
<jsp-file>/index.jsp</jsp-file>
<init-param>
<param-name>admincontact</param-name>
<param-value>8939302763</param-value>
</init-param>
</servlet>
<context-param>
<param-name>tagline</param-name>
<param-value>Each one Plant one</param-value>
I get a exception at
${pageContext.servletConfig.initParameter("admincontact")}
and null value for
<%=config.getInitParameter("admincontact")%>.
Regards,
John
There is an FAQ on JavaRanch about this.
It states the following;
How to access servlet init parameters using EL?
You cannot use the following syntax to access servlet init parameters:
${pageContext.servletConfig.initParameter.name}
You cannot get Servlet init parameters using this technique. The
getInitParameter(java.lang.String name) does not fit in this case,
because it requires some arguments.
According to the JavaBean spec, the property has getter & setter
methods in the form
public type1 getXXX() -- WITH NO ARGUMENTS.
public void setXXX(type1)
Now consider the pageContext as bean Object. The
PageContext class has methods like getServletConfig(), getRequest(),
getSession() etc. You can access these like pageContext.page,
pageContext.request etc in EL.
ServletContext object has a couple of methods like getMajorVersion(),
getMinorVersion() with no args. so we can access these methods
treating it as properties to sevletContext bean as
pageContext.servletContext.majorVersion and
pageContext.servletContext.minorVersion.
If you want to access Servlet init parameters using EL, then it is
better to create a Map of the init parameters for the servlet and
place it in the request as a scoped variable -- let's say
initParameters. You would then be able to obtain any param by name
with ${requestScope.initParameters.name}.
NOTE:
We can access context init parameters with ${initParam.name}
In addition to Mr Moose's answer, I have found this solution that uses EL defining a custom tag.
It worked in my case.
Here the link
Basically you have to create a Java class like this:
package example.customTags;
import javax.servlet.jsp.JspPage;
public class MyFunctions {
public static String getJspInitParameter(JspPage page, String param){
return page.getServletConfig().getInitParameter(param);
}
}
Create a tld file like this (my filepath is WEB-INF/myTags/customTags.tld):
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>Functions</short-name>
<function>
<name>getJspInitParameter</name>
<function-class>example.customTags.MyFunctions</function-class>
<function-signature>
java.lang.String getJspInitParameter(javax.servlet.jsp.JspPage, java.lang.String)
</function-signature>
</function>
</taglib>
And use it in your JSP like this:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="my" uri="../WEB-INF/myTags/customTags.tld"%>
<!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=ISO-8859-1">
<title>Example</title>
</head>
<body>
<c:out value="${my:getJspInitParameter(pageContext.page, 'admincontact')}"/>
</body>
</html>