I am using spring 3.1.2 MVC.
I am trying to configure web application by annotations
Here I want to implement internationalization for that I am using LocaleChangeInterceptor , ReloadableResourceBundleMessageSource ,SessionLocaleResolver classes.
here is my config class :
#Configuration
#EnableWebMvc
public class MyAppConfig extends WebMvcConfigurerAdapter{
#Bean
public ReloadableResourceBundleMessageSource resourceBundleMessageSource(){
ReloadableResourceBundleMessageSource messageSource=new ReloadableResourceBundleMessageSource();
String[] resources= {"classpath:labels","classpath:message"};
messageSource.setBasenames(resources);
return messageSource;
}
#Bean
public LocaleChangeInterceptor localeChangeInterceptor(){
LocaleChangeInterceptor localeChangeInterceptor=new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("locale");
return localeChangeInterceptor;
}
#Bean
public SessionLocaleResolver sessionLocaleResolver(){
SessionLocaleResolver localeResolver=new SessionLocaleResolver();
localeResolver.setDefaultLocale(new Locale("da","DK"));
return localeResolver;
}
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
}
But this is not working it shows default text for
<spring:message code="login.user.password" text="Password" />
as "Password".
please help me.
where as when I do following configuration in applicationContext.xml it works fine.
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath:message</value>
<value>classpath:labels</value>
</list>
</property>
<property name="defaultEncoding" value="ISO-8859-1" />
</bean>
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" p:paramName="locale"/>
</mvc:interceptors>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="da_DK" />
</bean>
Please help me to solve this issue.
The bean name for messageSource has to be "messageSource", with #Configuration you have it as resourceBundleMessageSource. Change it to this:
#Bean
public ReloadableResourceBundleMessageSource messageSource(){
ReloadableResourceBundleMessageSource messageSource=new ReloadableResourceBundleMessageSource();
String[] resources= {"classpath:labels","classpath:message"};
messageSource.setBasenames(resources);
return messageSource;
}
i resolved my problem , i was missing init param entry in my web.xml
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
com.config.AppConfig
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
after adding this entry my config with annotation is working fine. :)
Related
I am trying to configure Thymeleaf Html page with Spring MVC. I have controller method from which I am trying to return he thymeleaf template html page. Its existing project which uses spring mvc + tiles.I need to integrate thymeleaf in to existing project. The template Engine is autowired which is coming from different Jar file. I have provided configuration below. I am not getting any exception but getting Page Not found when I try to load the page.
IS it possible to have one flow which resolves view with Tiles + Jps and another flow with Thymeleaf template. how can I achieve it .
#Controller
#RequestMapping("/thymeleafConfiguration")
public class ConfigController {
#Autowired
TemplateEngine templateEngine; // This class is coming from different jar and I have
//autowired. xml configuration is provided for reference
#PostConstruct // Changes needs to apply only to certain class so I am using
//postconstruct method in controller
// where I need to use thymeleaf template.
public void Init() {
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setCacheable(false);
templateResolver.setPrefix("/templates/thymeleafPage/");
templateResolver.setSuffix(".html");
templateEngine.setTemplateResolver(templateResolver);
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setOrder(1);
resolver.setTemplateEngine(templateEngine);
}
#RequestMapping(value = "/view") // controller method where I am redirecting thymeleaf
page
public String viewTemplate(){
return "thymeleaf";
}
}
application-context.xml
<bean id="thymeleafProcessor" class="com.java.ThymeleafTemplateProcessor">
<property name="templateEngine" ref="templateEngine"/>
</bean>
<bean id="htmlStringTemplateResolver" class="org.thymeleaf.templateresolver.StringTemplateResolver">
<property name="templateMode" value="HTML" />
<property name="cacheable" value="true" />
</bean>
<bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="enableSpringELCompiler" value="true" />
<property name="templateResolvers">
<set>
<ref bean="htmlStringTemplateResolver" />
</set>
</property>
</bean>
Project Structure :
myProject
|
|Src
-Java
-templates
-thymeleafPage
- thymeleaf.html
-webContent
web.xml
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>*.*</url-pattern>
</servlet-mapping>
Can you please guide me how can I load the Page. I have referred documentation of thymeleaf
ThymeleafDocumetation
Tutorial
I have followed some examples but couldnt find much difference. I appreciate your help.
Jordan
I have found the solution how to make it work for Jsp , HTML and Thymeleaf template together.
Thank you
web.xml
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring/*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
controller
#Controller
#RequestMapping("/car/*")
public class CarController extends BaseController {
#RequestMapping("baojia.html")
public ModelAndView baojia() {
ModelAndView view = new ModelAndView();
view.setViewName("baojia");
return view;
}
when i visit http://mydomain/car/baojia.html and has this error:
[carloan]2016-04-21 09:01:31,177 WARN [org.springframework.web.servlet.PageNotFound] - <No mapping found for HTTP request with URI [/views/baojia.jsp] in DispatcherServlet with name 'springMVC'>
spring.xml ViewResolver
<bean id="ViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="cache" value="false"/>
<property name="contentType" value="text/html;charset=UTF-8" />
<property name="prefix" value="/views/"/>
<property name="suffix" value=".jsp"/>
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
</bean>
and i have file in /views/boajia.jsp
whether i writer, it don't work
<mvc:resources mapping="/views/" location="/views/**" />
and i have another question, i wan't to matching this url-pattern: /api/*
and the controller is:
#Controller
#RequestMapping("/api/*")
public class CarApiController extends BaseController {
#RequestMapping("get")
#ResponseBody
public JsonResult getCars()
but it can't work
try #RequestMapping("/car") instead of #RequestMapping("/car/*")
And check below two links to understand, how request mapping defined.
can anybody explain me difference between class level controller and method level controller..?
http://duckranger.com/2012/04/advanced-requestmapping-tricks-controller-root-and-uri-templates/
URL mapping declaration is not proper use #RequestMapping("/car") and #RequestMapping("/baojia.html")
I'm working with JSF. Recently we decided to exclude service layer from our project, cause this layer in 80% of cases consist only of recalling the same named dao-methods (definelty, I know, that this way is "not true"). So, now we need to make our managed beans layer transactional, and here is the problem: I can make dao-layer transactional, but when I try to move this duty to managegbeans layer, I get an
org.hibernate.HibernateException: No Session found for current thread
Dao and managedbeans layers are in separated modules, so they have separated context.xml files. When i define tx:annotation-driven tag in dao's context.xml file, #Transactional annotations in classes in dao-module are "visible", but when I try to define this tag in managedbeans context.xml file, none of the #Transactional annotations (neiter the dao, nor the managedbeans) are visible, so i get an exception.
Any ideas, how I can correctly configure transactions?
applicationContext-dao.xml
<jee:jndi-lookup id="dataSource" jndi-name="java:/MSSQLDataSource"/>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan">
<list>
<value>com.company.project.entity</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<context:component-scan base-package="com.company.project.dao"/>
applicationContext-web.xml
<context:annotation-config />
//Just because of the service layer is not fully removed, de facto we are using this import only for imort dao-context
<import resource="classpath:/applicationContext-service.xml"/>
<context:component-scan base-package="com.company.project"/>
<tx:annotation-driven transaction-manager="txManager" proxy-target-class="false"/>
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
Part of web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:/applicationContext-web.xml
classpath:/applicationContext-security.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>com.company.project.util.ServletContextListenerConfig</listener-class>
</listener>
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>
org.apache.cxf.transport.servlet.CXFServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
ServletContextListenerConfig class:
public class ServletContextListenerConfig implements ServletContextListener {
public void contextInitialized(ServletContextEvent event) {
System.setProperty("org.apache.el.parser.COERCE_TO_ZERO", "false");
}
public void contextDestroyed(ServletContextEvent event) {
// NOOP
}
}
Thanks in advance!
UPDATE:
After reading a "couple" of articles, I've spoken, that problem may be in double definition beans because of mapping them by different <context: component-scan>. In most of articles I've read, this contexts were root context by contextConfigLocation and servlet-context by DispatcherServlet , but in my case I haven't got DispatcherServlet, but I have FacesServlet by javax.faces.webapp.FacesServlet. So, does Faces Servlet do the same thing and, if yes, how? I don't see any connection between Faces Servlet and my context.xml files.
UPDATE 2:
My fault, that I didn't show this code at once.
Here's my controller:
#Component
#ViewScoped
public class ProfileBean extends EntityBeanBase<Profile> {
#Autowired
private ProfileDao profileDao;
#Override
#Transactional
protected List<Profile> getInitEntities() {
return profileDao.getAll();
}
public void profileNameValidator(FacesContext context, UIComponent component, Object value) {
if (!selectedEntity.getName().equals(value) && profileDao.exists((String) value)) {
System.out.println("Error validating");
}
}
EntityBenBase consist of many-many methods, but now I'm using only getInitEntities(), which is abstract in EnityBeanBase.
And ProfileDaoImpl:
#Repository
public class ProfileDaoImpl extends BaseDao implements ProfileDao {
#Override
public List<Profile> getAll() {
return sessionFactory.getCurrentSession().createCriteria(Profile.class).list();
}
..........
}
BaseDao is simple:
public abstract class BaseDao {
#Autowired
public SessionFactory sessionFactory;
}
I have an xml configuration of spring as below:
<bean id="processor"
class="org.springframework.security.saml.processor.SAMLProcessorImpl">
<constructor-arg>
<list>
<ref bean="redirectBinding" />
<ref bean="postBinding" />
<ref bean="artifactBinding" />
<ref bean="soapBinding" />
<ref bean="paosBinding" />
</list>
</constructor-arg>
</bean>
I also have another Java Configuration of Spring as below:
#ImportResource({ "classpath:security/samlMetadata.xml" })
#Configuration
public class SecConfig{
#Autowired
private SAMLProcessorImpl processor;
#Bean(name ="webSSOProfileConsumer")
public WebSSOProfileConsumer webSSOProfileConsumer(){
WebSSOProfileConsumerImpl webSSOProfileConsumerImpl = new WebSSOProfileConsumerImpl();
try {
webSSOProfileConsumerImpl.setProcessor(processor);
webSSOProfileConsumerImpl.afterPropertiesSet();
}
catch (Exception e) {
e.printStackTrace();
}
return webSSOProfileConsumerImpl;
}
}
I get the processor bean as null, please help me if I am missing some basic thing while autowiring.
EDIT
Here is the relevant part of web.xml The only thing I am skipping is welcome-file-list
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.config.WebConfig
</param-value>
</context-param>
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>production</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>security</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>security</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>filterChainProxy</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>filterChainProxy</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
EDIT2
#Configuration
#ImportResource({ "classpath:security/samlMetadata.xml" })
#Import({SecureConfig.class})
#Profile("production")
#ComponentScan(basePackages = "com.config")
public class WebConfig extends WebMvcConfigurationSupport {
#Bean(name = "viewResolver")
public InternalResourceViewResolver viewResolver() throws Exception {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/jsp/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
I am sorry I didn't add this class earlier.
When i visit localhost:8080/home - i get:
WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/home] in DispatcherServlet with name 'appServlet'
When i visit localhost:8080/ or localhost:8080/index all look ok.
Why one path works, and another don't?
And thing, that confuse me: localhost:8080/homepage.html - return me my home view.
So my project here: https://github.com/IRus/jMusic
my web.xml
<!-- Base servlet handles all requests to the application. -->
<servlet>
<servlet-name>appServlet</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>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
servlet-context.xml - i using tiles
<annotation-driven/>
<resources mapping="/resources/**" location="/resources/"/>
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/"/>
<beans:property name="suffix" value=".jsp"/>
<beans:property name="order" value="1" />
</beans:bean>
<beans:import resource="controllers.xml"/>
<beans:import resource="tiles.xml" />
<beans:import resource="i18n.xml"/>
<beans:import resource="themes.xml"/>
tiles.xml
<bean id="tilesviewResolver" class="org.springframework.web.servlet.view.tiles2.TilesViewResolver">
<property name="order" value="0"/>
</bean>
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/views/tiles-definitions.xml</value>
</list>
</property>
</bean>
ErrorController
#Controller
public class ErrorController {
#RequestMapping("/403")
public String error403() {
return "403";
}
#RequestMapping("/404")
public String error404() {
return "404";
}
}
UserController
#Controller
public class UserController {
#Autowired
private UserService userService;
#RequestMapping("/")
public String index() {
return "redirect:/index";
}
#RequestMapping("/home")
public String home() {
return "home";
}
#RequestMapping("/login")
public String login() {
return "login";
}
#RequestMapping("/index")
public String listUsers(Map<String, Object> map) {
map.put("user", new User());
map.put("userList", userService.listUser());
return "user";
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String addUser(#ModelAttribute("user") User user,
BindingResult result) {
userService.addUser(user);
return "redirect:/index";
}
#RequestMapping("/delete/{idUser}")
public String deleteUser(#PathVariable("idUser") Long idUser) {
userService.removeUser(idUser);
return "redirect:/index";
}
}
Logs
Here: https://gist.github.com/IRus/2ac97c66070001247011
Interested moment in logs:
Mapped URL path [/homepage.html] into handler 'userController'
I added, and delete thats #RequestMapping in controller, but it still alive
I work in Idea 12.0.4
The problem was in the cache/IDE.
Class file is not updated when I deploy project.
First time i get trouble like this. Just restart IDE and clean tomcat webapps folder(delete my project files from here).
Now everything works as expected.