Character-encoding Spring MVC - spring-mvc

I am having trouble with Turkish characters...In my JSP pages, there is no problem... but, when an alert come from Java side, Turkish character(ŞşİığĞüÜç...) seems like that (ı,?,ü,ç,Å,...)
In JSP pages, I use this code and ı can solve Turkish character problem
<%# page contentType="text/html;charset=UTF-8" language="java"%>
in Spring MVC config, I tried a lot of way but I didn't succeed... For example In my mvc config class, I set my MessageSource like that;
#Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:messages");
messageSource.setUseCodeAsDefaultMessage(true);
messageSource.setDefaultEncoding("UTF-8");
messageSource.setCacheSeconds(0);
return messageSource;
}
In this program, I try to reset password and I typed unregister email address..Finally I am getting exception and this following is exception code blog.
#Autowired
private MessageSource messages;
...
#ExceptionHandler({ UserNotFoundException.class })
public ResponseEntity<Object> handleUserNotFound(final RuntimeException exception, final WebRequest request) {
logger.error("404 Status Code", exception);
final GenericResponse bodyOfResponse = new GenericResponse(messages.getMessage("message.userNotFound", null, request.getLocale()), "UserNotFound");
return handleExceptionInternal(exception, bodyOfResponse, new HttpHeaders(), HttpStatus.NOT_FOUND, request);
}
In my messages_tr_TR.properties file,
...
message.userNotFound=Kullanıcı Bulunamadı
...
but In JSP pages this alert shows like that;
Kullanıcı Bulunamadı
How can I solve this problem..

Comment follow-up, you can set the encoding in your response header as well. An example if you're returning json would be
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add("Content-Type", "application/json; charset=utf-8");
return handleExceptionInternal(exception, responseHeaders, HttpStatus.NOT_FOUND, request);

In web.xml:
<jsp-config>
<!-- global JSP configuration -->
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<page-encoding>UTF-8</page-encoding>
</jsp-property-group>
</jsp-config>
<filter>
<filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Put the actual text in the handler method (temporarily). Does it now look right? Is your messages file correctly saved as UTF-8? Also, I can't tell if you're using JSON or not...

Related

URL pattern servlet mapping

I created hello world example using Spring MVC, but there is one thing I didn't understand in servlet URL mapping, I did the following in web.xml:
<servlet>
<servlet-name>HelloWeb</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HelloWeb</servlet-name>
<url-pattern>/test/*</url-pattern>
</servlet-mapping>
now if I want to call the following controller:
#Controller
#RequestMapping("/hello")
public class HelloWorld {
#RequestMapping(method = RequestMethod.GET)
public String printWelcome(ModelMap model){
model.addAttribute("message","hello world");
return "index";
}
}
it will work using the following link:
http://localhost:8080/test/hello
but when I change the servlet url-pattern to "/*" and try:
http://localhost:8080/hello
it doesn't work, shouldn't it match my servlet ? as * matches everything
When you register a servlet with "/*" then it will override all the servlet mappings if there are any. Hence it should be avoided. This overrides default servlet mapping as well hence all default url handling also overridden and hence any specific url matching fails. In your case it is /hello.
With your case, initially you registered with /test/* this registered all your URL's with /test and hence they got identified.
It doesn't work for /* because, you have not registered/created a controller for that pattern.
It worked for http://localhost:8080/hello because, you have controller #RequestMapping("/hello")
Just change the RequestMapping to #RequestMapping("/") for url-pattern /*

Spring LazyInitializationException when using "redirect" in controller

I started creating an application with Spring-Roo 1.3.1 and Spring-Security 3.1.7
I'm using Spring OpenEntityManagerInViewFilter to be able to do lazy loading of my domain objects.
<filter>
<filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
This is working fine so far. However, I encountered the following issue when doing a redirect from a controller:
#RequestMapping(method = RequestMethod.PUT, produces = "text/html")
public String update(#Valid Service service, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
if (bindingResult.hasErrors()) {
populateEditForm(uiModel, service);
return "services/update";
}
uiModel.asMap().clear();
serviceRepository.save(service);
return "redirect:/services/" + encodeUrlPathSegment(service.getId().toString(), httpServletRequest);
}
This redirect return "redirect:/services/" + encodeUrlPathSegment(service.getId().toString(), httpServletRequest); is failing with an LazyInitializationException. It fails during execution of the filter chain after the commit is done and redirect took place. The URL redirected to is working when access directly.
When using return "forward:/services/" + encodeUrlPathSegment(service.getId().toString(), httpServletRequest); the page loaded just fine.
I really do not know why the hibernate session is not available when using "redirect". Another strange thing is, when activating DEBUG logging for org.springframework.security.web is is also working fine.
e.g. log4j.logger.org.springframework.security.web=DEBUG
I already searched the internet for some hints but generally lazy loading is working fine in my app, it's just in that circumstance and currently I do not fully understand why.
Any comments/hints are welcome.
Thanks
Stefan
Try to change controller like this:
#RequestMapping(method = RequestMethod.PUT, produces = "text/html")
public String update(#Valid Service service, BindingResult bindingResult,
Model uiModel, HttpServletRequest httpServletRequest) {
if (bindingResult.hasErrors()) {
populateEditForm(uiModel, service);
return "services/update";
}
uiModel.asMap().clear();
Service attached = serviceRepository.save(service);
return "redirect:/services/" +
encodeUrlPathSegment(attached.getId().toString(),
httpServletRequest);
}
The instance service is create by Spring binder to map request values to the object but it is not attached to entityManager (no db session). When you call save you get an attached (instance managed by entityManager) instance so, if you try to get any lazy property from this instance it knows how do it.
You can found more information about JPA objects live cycle here.
Good luck!

URL mapping problems using Spring MVC

I have a very basic setup which I am trying to get working.
web.xml
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/site/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
mvc-dispatcher-servlet.xml
<context:component-scan base-package="com.blabla.controller" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/pages/" p:suffix=".jsp"
p:viewClass="org.springframework.web.servlet.view.JstlView" />
In the controller
#Controller
#RequestMapping(value = "/site")
public class SearchController {
#RequestMapping(value = "welcome", method = RequestMethod.GET)
public String test() {
return "test";
}
This is the problem that I have:
I would like to write /site/* as url-pattern in my web.xml, but when I do that I get
WARNING: No mapping found for HTTP request with URI [/site/welcome] in DispatcherServlet with name 'mvc-dispatcher'
When I write /site/welcome in full, everything works, but I dont want this because I dont want to add every page manually to the web.xml
And when I write "/*" as url-pattern i get the error message:
WARNING: No mapping found for HTTP request with URI [/WEB-INF/pages/test.jsp] in DispatcherServlet with name 'mvc-dispatcher'
which I guess makes sense because the the location of the jsp is included in the pattern.
So how do you do it: how can you be sufficiently vague in your url pattern without the problems I just had?

How do I integrate Sitemesh 3 with Spring MVC 3?

I am trying to use Sitemesh 3 to control the decoration of JSP output from a Spring MVC application.
When I hit the application it seems that Sitemesh is making a request to the Spring servlet to try and retreive its decorator file. This may, or may not be correct behaviour but it is causing me all many of headaches.
My understanding of Sitemesh 3 is that it does its work after Spring, ie on the Response object.
The error I'm getting in the browser is a 404 and in the logs (config/code follows):
INFO: Server startup in 1367 ms
DEBUG: org.springframework.web.servlet.DispatcherServlet - DispatcherServlet with name
'springiness' processing GET request for [/clientmanager/]^M
DEBUG:
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping -
Looking up handler method for path /^M
DEBUG: org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping -
Returning handler method [public java.lang.String
uk.co.hermes.HomeController.home(java.util.Locale,org.springframework.ui.Model)]^M
DEBUG: org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning
cached instance of singleton bean 'homeController'^M
DEBUG: org.springframework.web.servlet.DispatcherServlet - Last-Modified value for
[/clientmanager/] is: -1^M
INFO : uk.co.hermes.HomeController - Welcome home! The client locale is en_GB.^M
DEBUG: org.springframework.beans.factory.support.DefaultListableBeanFactory - Invoking
afterPropertiesSet() on bean with name 'home'^M
DEBUG: org.springframework.web.servlet.DispatcherServlet - Rendering view
[org.springframework.web.servlet.view.JstlView: name 'home'; URL [/WEB-
INF/jsp/home.jsp]] in DispatcherServlet with name 'springiness'^M
DEBUG: org.springframework.web.servlet.view.JstlView - Added model object 'serverTime'
of type [java.lang.String] to request in view with name 'home'^M
DEBUG: org.springframework.web.servlet.view.JstlView - Forwarding to resource [/WEB-
INF/jsp/home.jsp] in InternalResourceView 'home'^M
DEBUG: org.springframework.web.servlet.DispatcherServlet - Successfully completed
request^M
DEBUG: org.springframework.web.servlet.DispatcherServlet - DispatcherServlet with name
'springiness' processing GET request for [/clientmanager/WEB-
INF/decorators/mainDecorator.html]^M
DEBUG:
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping -
Looking up handler method for path /WEB-INF/decorators/mainDecorator.html^M
DEBUG:
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping -
Did not find handler method for [/WEB-INF/decorators/mainDecorator.html]^M
WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request
with URI [/clientmanager/WEB-INF/decorators/mainDecorator.html] in DispatcherServlet
with name 'springiness'^M
DEBUG: org.springframework.web.servlet.DispatcherServlet - Successfully completed request^M
I suspect it's a problem in my web.xml and how I've defined the mappings(URLs):
<servlet>
<servlet-name>springiness</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springiness</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>sitemeshfilter</filter-name>
<filter-class>uk.co.hermes.filters.SitemeshFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>sitemeshfilter</filter-name>
<!-- leaving SitemeshFilter class to decide which responses it should decorate -->
<url-pattern>/*</url-pattern>
</filter-mapping>
My custom filter:
public class SitemeshFilter extends ConfigurableSiteMeshFilter {
private Logger log = LoggerFactory.getLogger(SitemeshFilter.class);
/**
* See http://wiki.sitemesh.org/display/sitemesh3/Configuring+SiteMesh+3
*/
#Override
protected void applyCustomConfiguration(SiteMeshFilterBuilder builder) {
log.debug("** hit the sitemesh filter");
// apply this decorator (template) to the path defined...
builder.addDecoratorPath("/*", "/WEB-INF/decorators/mainDecorator.html");
// ... when the response type matches one of these
builder.setMimeTypes("text/html", "application/xhtml+xml", "application/vnd.wap.xhtml+xml");
}
}
WEB-INF/
|-jsp
|-home.jsp
|-decorators
|-mainDecorator.html
And my super simple Controller:
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
return "home";
}
Since no one has posted actual content, here you go:
in pom.xml add:
<dependency>
<groupId>org.sitemesh</groupId>
<artifactId>sitemesh</artifactId>
<version>3.0.0</version>
</dependency>
in WEB-INF/web.xml † add:
<filter>
<filter-name>sitemesh</filter-name>
<filter-class>org.sitemesh.config.ConfigurableSiteMeshFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>sitemesh</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
in WEB-INF/sitemesh3.xml add:
<sitemesh>
<mapping path="/*" decorator="/WEB-INF/decorator1.jsp"/>
</sitemesh>
in WEB-INF/decorator1.jsp add:
<html>
<head>
...
</head>
<body>
<sitemesh:write property='body'/>
</body>
</html>
† put this below your Spring Security Filter Chain if using Spring Security.
Here is another blog that shows the integration between Sitemesh 3 and Spring MVC
In my case, I used this little tutorial to make it works.

spring 3 uploadify giving 404 Error

I am using Spring 3 and implementing Uploadify. The problem is, the files are updating properly but it is giving HTTP Error 404, on completion of file upload. I tried every possible solution, but none of them works.
The files are uploaded. Values are storing in DB properly, only that i am getting HTTP Error 404. Any help is appreciated and Thanks in advance.
The Solution is :
Finally i found the solution but it is lame.
I removed the return "" and changed the method as void. Thats it.
But still i don't understand why the same code is working in Spring 2.5.6 and not in 3.
The URL of the screenshot : http://imgur.com/bf3qo
The JSP Page
$(function() {
$('#file_upload').uploadify({
'swf' : 'scripts/uploadify.swf',
'fileObjName' : 'the_file',
'fileTypeExts' : '*.gif; *.jpg; *.jpeg; *.png',
'multi' : true,
'uploader' : '/photo/savePhoto',
'fileSizeLimit' : '10MB',
'uploadLimit' : 50,
'onUploadStart' : function(file) {
$('#file_upload').uploadify('settings', 'formData', {'trip_id' :'1', 'trip_name' :'Sample Trip', 'destination_trip' :'Mumbai','user_id' :'1','email' :'s#s.com','city_id' :'12'});
},
'onQueueComplete' : function(queueData) {
console.log('queueData : '+queueData);
window.location.href = "trip/details/1";
}
});
});
The Controller
#RequestMapping(value="photo/{action}", method=RequestMethod.POST)
public String postHandler(#PathVariable("action") String action, HttpServletRequest request) {
if(action.equals("savePhoto"))
{
try{
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
MultipartFile file = multipartRequest.getFile("the_file");
String trip_id = request.getParameter("trip_id");
String trip_name = request.getParameter("trip_name");
String destination_trip = request.getParameter("destination_trip");
String user_id = request.getParameter("user_id");
String email = request.getParameter("email");
String city_id = request.getParameter("city_id");
photo.savePhoto(file,trip_id,trip_name,destination_trip,user_id,email,city_id);
photo.updatetrip(photo_id,trip_id);
}catch(Exception e ){e.printStackTrace();}
}
return "";
} **Solution** : Change the method return type as void and remove the return
spring config
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
<property name="maxUploadSize" value="10000000"/>
</bean>
Web.xml is
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>project_name</display-name>
<distributable/>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:log4j.properties</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/project_name-servlet.xml,/WEB-INF/applicationContext-jdbc.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>project_name</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>project_name</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<session-config>
<session-timeout>60</session-timeout>
</session-config>
</web-app>
maybe you simply haven't page trip/details/1 in your application?
EDIT:
Change window.location.href = "trip/details/1"; to
window.location.href = "<%= request.getContextPath() %>/trip/details/1";
The files are uploaded. Values are storing in DB properly, only that i
am getting HTTP Error 404.
What this tells me is that your request is properly being submitted to the URL at '/photo/*'
and is properly handled by the postHandler() method.
You're getting a 404 because your web application doesn't know what to do with the url of "" that the postHandler() method is trying to direct you to.
There is most likely (and I'm making some assumptions here, it'd be helpful if you included the web.xml) a request mapper not set up to handle the " " that your controller is returning; make your controller return some sort of meaningful view name that has a valid servlet mapping and you will not get a 404.
I had this problem too. I added "#ResponseBody" and got the right result.
I think the problem is that without the annotation "#ResponseBody", the returned string is handled by some strange resolver and javascript code gets response of unexpected form.
#RequestMapping(value="/uploadFile",method=RequestMethod.POST)
public #ResponseBody String upload(HttpServletResponse response,
HttpServletRequest request) throws IOException{

Resources