Spring MVC 4 java config does not recognize internationalization change - java

this is my project structure:
these are all classes of my sample to use spring i18n internationalization, but spring only use en_US for application localization:
SpringWebInitializer
public class SpringWebInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(SpringWebConfig.class);
rootContext.setServletContext(servletContext);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
servletContext.addListener(new RequestContextListener());
servletContext.addListener(new ContextLoaderListener(rootContext));
}
}
SpringWebConfig
#EnableWebMvc
#Configuration
#ComponentScan("com.rgh.web")
public class SpringWebConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/view/");
viewResolver.setSuffix(".jsp");
viewResolver.setViewClass(JstlView.class);
return viewResolver;
}
#Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
#Bean
public LocaleResolver localeResolver() {
CookieLocaleResolver localeResolver = new CookieLocaleResolver();
localeResolver.setDefaultLocale(new Locale("fa"));
localeResolver.setCookieName("lang");
return localeResolver;
}
#Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("lang");
return localeChangeInterceptor;
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
}
index.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# page contentType="text/html;charset=UTF-8" language="java"%>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<spring:message code="app.name" />
${pageContext.response.locale}
</body>
</html>
messages_fa.properties
app.name=MyAppFarsi
messages.properties
app.name=MyApp

Related

noHandlerFound in Spring for CSS

I am learning Spring MVC and I try to get some experience. I wrote an app and deployed it to Tomcat serve. At run time, the browser gets a 404 code for the CSS and Tomcat "WARNING [http-nio-8080-exec-12] org.springframework.web.servlet.DispatcherServlet.noHandlerFound No mapping for GET /SpringC5BuildingSpringWebApplication/resources/style.css"
Can you please give me some hints of what could be wrong?
Below is my code:
App initializer
public class SpittrWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
#Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] {RootConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] {WebConfig.class};
}
}
WebConfig
#Configuration
#EnableWebMvc
#ComponentScan(basePackageClasses = HomeController.class)
class WebConfig extends WebMvcConfigurationSupport{
#Bean
public ViewResolver viewResolver(){
InternalResourceViewResolver resolver =
new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
#Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}
}
Controller
#Controller
public class HomeController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(){
return "home";
}
}
Webpage
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page session="false" %>
<html>
<head>
<title>Spitter</title>
<link rel="stylesheet"
href="<c:url value="/resources/style.css" />" >
</head>
<body>
<h1>Welcome to Spitter</h1>
Spittles |
Register
</body>
</html>
WebXML
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd"
version="3.0">
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
Folder structure
The CSS file is inserted in many places with the home that the server will read it from somewhere. Any hint could be helpful and appreciated! Thank you and I wish you good health!
The problem was in the WebConfig.class.
I need to change the inherited entity. From class WebConfig extends WebMvcConfigurationSupport to public class WebConfig implements WebMvcConfigurer.

Uncaught Error: Could not load **** at XMLHttpRequest.xhr.onreadystatechange

I am working on a springboot project that consumes a weather api and shows the data on the browser using react, Anyway, It seems that I am missing some configurations or I might need to move files around in my project, The error in the browser shows that the js/css files are not reachable :
GET http://localhost:8080/demo/resources/css/neo.css
browser.min.js:4 GET http://localhost:8080/demo/resources/js/WeatherManager.js 404 ()
browser.min.js:4 Uncaught Error: Could not load http://localhost:8080/demo/resources/js/WeatherManager.js
at XMLHttpRequest.xhr.onreadystatechange (browser.min.js:4)
* WebConfig *
#Configuration
#ComponentScan
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
return resolver;
}
/**
* We need to define 3 things to implement
* 1- Define message resource
* 2- Define Local resolver internationalization
* 3- Override interceptor
*/
#Bean
public MessageSource messageSource(){
ResourceBundleMessageSource messageSource=new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
#Bean
public LocaleResolver localeResolver(){
SessionLocaleResolver resolver =new SessionLocaleResolver();
resolver.setDefaultLocale(Locale.ENGLISH);
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry){
//you can add more resources here
registry.addResourceHandler("/css/**").addResourceLocations("/resources/css/");
registry.addResourceHandler("/js/**").addResourceLocations("/resources/js/");
}
#Override
public void addInterceptors(InterceptorRegistry registry)
{
LocaleChangeInterceptor changeInterceptor=new LocaleChangeInterceptor();
changeInterceptor.setParamName("language");
registry.addInterceptor(changeInterceptor);
}
}
* WebAppInitializer *
public class WebAppInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
WebApplicationContext context = getContext();
servletContext.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("*.html");
dispatcher.addMapping("*.pdf");
//Enable JSON response
dispatcher.addMapping("*.json");
dispatcher.addMapping("*.jsx");
}
private WebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context =new AnnotationConfigWebApplicationContext();
context.register(WebConfig.class);
return context;
}
* DemoApplication *
#SpringBootApplication
#EnableAutoConfiguration
#EnableAsync
public class DemoApplication extends AsyncConfigurerSupport {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(2);
executor.setQueueCapacity(500);
executor.setThreadNamePrefix("WeatherService-");
executor.initialize();
return executor;
}
}
JS/CSS files live under /resources/css/ /resources/js/
JSP pages live under WEB-INF/jsp
** weather.jsp page **
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="resources/css/neo.css">
<title>Weather </title>
</head>
<body>
<div id="main" class="container">
</div>
<script type="text/babel" src="resources/js/WeatherManager.js"></script>
</body>
</html>
I have the source code at
github : [https://github.com/saifmasadeh/WeatherBoard][1]
You should add this to your question:
<script type="text/babel" src="resources/js/WeatherManager.js"></script>
<link rel="stylesheet" type="text/css" href="resources/css/neo.css">
This is where the problem is. You're importing via the wrong URL.
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry){
//you can add more resources here
registry.addResourceHandler("/css/**").addResourceLocations("/resources/css/");
registry.addResourceHandler("/js/**").addResourceLocations("/resources/js/");
}
The above method says when a user tries to access a url with the path /js/** look in /resources/js/.
Basically, if the user were to request localhost/context-root/js/script.js
Spring would view this as localhost/context-root/resources/js/script.js
(That is not literally the case, but it explains the idea well enough.)
So when you try to import your script file resources/js/WeatherManager.js the resource handler doesn't know where to look. It doesn't know about anything with the path resources/**
What you want to do is import this way:
<script type="text/babel" src="/js/WeatherManager.js"></script>
This maps to the resource handler's "/js/** and looks up WeatherManager.js in /resources/js/. You need to do the same thing with your CSS file.
For another example of how this works, view my answer here.
(Also, you may need to use classpath:/resources/(js|css) as your resource location if this doesn't work.)

Reading data after adding into table return zero

I have a problem when I add several rows into talbe in transaction
and read that data from table.
I have tested data before I adding, to prevent duplicated data.
My table have no autogenerated index.
Since I enabled hibernate to show sql I saw that insert into table
executed after my reading data, so I have got wrong data.
sessionFactory.getCurrentSession().flush();
I know that I could flush session before reading, but that is not good solution for me, becouse if my program create exception, data were stored
into table, and I will have a problem.
My table was converted into INNODB engine
ALTER TABLE mytable ENGINE=InnoDB;
Here is my project
I removed import from files
AppInitializer.java
package rs.co.master.config.web;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
#ComponentScan(basePackages = { "rs.co" })
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
implements WebApplicationInitializer{
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { ApplicationContextConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
appContext.register(ApplicationContextConfig.class);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
"test", new DispatcherServlet(appContext));
dispatcher.setInitParameter("display-name", "test");
dispatcher.setInitParameter("Version", "dec");
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
ApplicationContextConfig
package rs.co.master.config.web;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
#Configuration
#EnableWebMvc
#MultipartConfig
#EnableAspectJAutoProxy
#ComponentScan(basePackages = { "rs.co" })
public class ApplicationContextConfig extends WebMvcConfigurerAdapter{
#Autowired
ConfigurationForTiles configurationForTiles;
#Override
public void configureViewResolvers(ViewResolverRegistry registry) {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
registry.viewResolver(viewResolver);
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/themes/**").addResourceLocations("/themes/").setCachePeriod(31556926);
registry.addResourceHandler("/ui/**").addResourceLocations("/ui/").setCachePeriod(31556926);
registry.addResourceHandler("*.jpg").addResourceLocations("").setCachePeriod(31556926);
}
#Override
public void configurePathMatch(PathMatchConfigurer matcher) {
matcher.setUseRegisteredSuffixPatternMatch(true);
}
#Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
#Bean
public LiteDeviceResolver liteDeviceResolver() {
List<String> keywords = new ArrayList<String>();
keywords.add("iphone");
keywords.add("android");
return new LiteDeviceResolver(keywords);
}
#Bean
public DeviceResolverHandlerInterceptor deviceResolverHandlerInterceptor() {
return new DeviceResolverHandlerInterceptor(liteDeviceResolver());
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(deviceResolverHandlerInterceptor());
registry.addInterceptor(localeChangeInterceptor());
}
#Bean
public LocaleResolver localeResolver() {
CookieLocaleResolver resolver = new CookieLocaleResolver();
resolver.setDefaultLocale(new Locale("sr_LATN_RS"));
resolver.setCookieName("localeCookie");
resolver.setCookieMaxAge(4800);
return resolver;
}
#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("sr", "sr_LATN_RS"));
return localeResolver;
}
#Bean(name = "supportedMediaTypes")
public ByteArrayHttpMessageConverter supportedMediaTypes() {
ByteArrayHttpMessageConverter supportedMediaTypes = new ByteArrayHttpMessageConverter();
List<MediaType> suppMedType = new ArrayList<MediaType>();
suppMedType.add(MediaType.IMAGE_GIF);
suppMedType.add(MediaType.IMAGE_JPEG);
suppMedType.add(MediaType.IMAGE_PNG);
suppMedType.add(MediaType.ALL);
supportedMediaTypes.setSupportedMediaTypes(suppMedType);
return supportedMediaTypes;
}
ConfigurationForTiles.java
package rs.co.master.config.web;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
public class ConfigurationForTiles {
#Bean
public TilesConfigurer tilesConfigurer() {
final TilesConfigurer configurer = new TilesConfigurer();
configurer.setDefinitions(new String[] {
"/WEB-INF/config/tiles.xml"
});
configurer.setCheckRefresh(true);
return configurer;
}
#Bean
public TilesViewResolver tilesViewResolver() {
final TilesViewResolver resolver = new TilesViewResolver();
resolver.setViewClass(TilesView.class);
return resolver;
}
}
HibernateConfiguration.java
package rs.co.master.config.web;
#Configuration
#EnableTransactionManagement
#ComponentScan({ "rs.co" })
#PropertySource(value = { "classpath:database.properties" })
public class HibernateConfiguration {
#Autowired
private Environment environment;
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "rs.co" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("database.driver"));
dataSource.setUrl(environment.getRequiredProperty("database.url"));
dataSource.setUsername(environment.getRequiredProperty("database.user"));
dataSource.setPassword(environment.getRequiredProperty("database.password"));
return dataSource;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
properties.put("hibernate.connection.useUnicode", environment.getRequiredProperty("hibernate.connection.useUnicode"));
properties.put("hibernate.connection.characterEncoding", environment.getRequiredProperty("hibernate.connection.characterEncoding"));
properties.put("hibernate.connection.charSet", environment.getRequiredProperty("hibernate.connection.charSet"));
return properties;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
}
IndexController.java
package rs.co.webController;
#Controller
#RequestMapping("")
public class IndexController {
private static final Logger logger =
LoggerFactory.getLogger(IndexController.class);
#Autowired
private DataService dataService;
#RequestMapping(value = {"", "/"}, method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
public #ResponseBody
ModelAndView index(
Locale locale,
HttpServletRequest request, HttpServletResponse response){
ModelAndView model = new ModelAndView("index");
model.addObject("welcome", "werew rew");
return model;
}
#RequestMapping(value = "/fillData", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
public #ResponseBody
ModelAndView fillData(
Locale locale,
HttpServletRequest request, HttpServletResponse response){
ModelAndView model = new ModelAndView("index");
Random number = new Random();
Integer x = number.nextInt(100)+1;
if (x < 0) x = x * - 1;
try{
Integer result = dataService.fillData(x);
model.addObject("resultSum", result);
}
catch (Exception e) {
logger.error("Error {}.", e.getMessage());
e.printStackTrace();
}
finally {
}
return model;
}
}
DataModel.java
package rs.co.webModel;
#Entity
#Table(name = "mytable")
public class DataModel implements Serializable {
#Id
// #GeneratedValue(strategy=GenerationType.AUTO)
#NotNull
#Column(name = "idtable")
private Integer idtable;
#NotNull
#Column(name = "number")
private Integer number;
private static final long serialVersionUID = -729870310313L;
public static long getSerialversionuid() {
return serialVersionUID;
}
public DataModel() {
super();
}
public DataModel(Integer idtable, Integer number) {
super();
this.idtable = idtable;
this.number = number;
}
public void updateModel(DataModel inModel) {
this.idtable = inModel.getIdtable();
this.number = inModel.getNumber();
}
}
DataService.java
DataServiceImpl.java
package rs.co.webService;
#Service("DataService")
#Transactional
public class DataServiceImpl implements DataService{
#Autowired
DataDao dataDao;
// #Override
public Integer fillData(Integer number) throws Exception {
return dataDao.fillData(number);
}
}
DataDao.java
DataDaoImp.java
package rs.co.webDao;
import rs.co.webModel.DataModel;
#Repository("DataDao")
#Transactional
public class DataDaoImpl implements DataDao {
#Autowired
private SessionFactory sessionFactory;
#Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public Integer fillData(Integer number) throws Exception{
Session sess = sessionFactory.openSession();
Transaction tx = null;
try{
tx = sess.beginTransaction();
emptyTable();
for(int i = 0; i < number; i++){
Random n = new Random();
Integer x = n.nextInt(100)+1;
DataModel dm = new DataModel(i+1, x);
addData(dm);
}
tx.commit();
}
catch (Exception e) {
if (tx!=null && tx.getLocalStatus() != LocalStatus.ROLLED_BACK)
tx.rollback();
e.printStackTrace();
}
finally {
sess.close();
}
Integer sumNumbers = getSumNumber();
return sumNumbers;
}
#Transactional(readOnly = true, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public DataModel getData(Integer idtable) {
DataModel tmp = null;
Query query;
String sql =
" from DataModel t"
+ " where idtable = :idtable "
;
query = sessionFactory
.getCurrentSession().createQuery(sql);
tmp = (DataModel)
query
.setInteger("idtable", idtable)
.uniqueResult();
return tmp;
}
#Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void emptyTable() throws Exception {
sessionFactory
.getCurrentSession()
.createQuery(
"DELETE FROM DataModel t"
)
.executeUpdate();
}
#Transactional(readOnly = true, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
private Integer getSumNumber() {
Long tmp = null;
Query query;
String sql = " select COALESCE(sum(t.number), 0) as number"
+ " from DataModel t";
query = sessionFactory
.getCurrentSession().createQuery(sql);
tmp = (Long) query.uniqueResult();
if (null == tmp) return 0;
return tmp.intValue();
}
#Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public DataModel addData(DataModel inModel) throws Exception {
DataModel model = null;
model = getData( inModel.getIdtable());
if (null == model){
model = inModel;
sessionFactory.getCurrentSession().save(model);
} else {
model.updateModel(inModel);
sessionFactory.getCurrentSession().saveOrUpdate(model);
}
return model;
}
#Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void deleteData(Integer idtable) throws Exception{
sessionFactory.getCurrentSession().createQuery(
"DELETE FROM DataModel "
+ " where idtable = :idtable ")
.setInteger("idtable", idtable).executeUpdate();
}
}
Resource database.properties
database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/test??characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&characterEncoding=UTF-8&characterSetResults=UTF-8
database.user=test
database.password=test
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.format_sql=true
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
hibernate.connection.useUnicode=true
hibernate.connection.characterEncoding=UTF-8
hibernate.connection.charSet=UTF-8
tiles.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN"
"http://tiles.apache.org/dtds/tiles-config_3_0.dtd">
<tiles-definitions>
<definition name="base.definition" template="/WEB-INF/tiles-templates/mainTemplate.jsp">
<put-attribute name="title" value="test"></put-attribute>
<put-attribute name="header" value=""></put-attribute>
<put-attribute name="menu" value=""></put-attribute>
<put-attribute name="body" value=""></put-attribute>
<put-attribute name="footer" value=""></put-attribute>
</definition>
mainTemplate.jsp
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%# taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
<c:import url="/WEB-INF/tiles-templates/homeHead.jsp"></c:import>
<body>
<div id="main">
<div id="header" >
<tiles:insertAttribute name="header"></tiles:insertAttribute>
</div>
<div id="main1">
<div id="menu1">
<tiles:insertAttribute name="menu"></tiles:insertAttribute>
</div>
<div id="middle">
<div id="b1">
<tiles:insertAttribute name="body"></tiles:insertAttribute>
</div>
</div>
</div>
<div id="footer">
<tiles:insertAttribute name="footer"></tiles:insertAttribute>
</div>
</div>
</body>
</html>
homeHead.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html>
<html lang="sr_RS">
<head>
<%# page isELIgnored="false" %>
<meta name="_csrf" content="${_csrf.token}"/>
<meta name="_csrf_header" content="${_csrf.headerName}"/>
<title>
<tiles:insertAttribute name="title" ignore="true"></tiles:insertAttribute>
</title>
</head>
<definition name="index" extends="base.definition">
<put-attribute name="title" value="test"></put-attribute>
<put-attribute name="body" value="/WEB-INF/views/index.jsp"></put-attribute>
</definition>
</tiles-definitions>
index.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="tiles" uri="http://tiles.apache.org/tags-tiles"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%# taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<script type="text/javascript">
<!--
function fillData(){
window.open("/test/fillData"
,
"_self");
;
}
//-->
</script>
<h2>Hello World!</h2>
<input type = "button" value="Click me" onclick="fillData()">Click to fill data and sum
<br>
<c:if test="${resultSum > 0 }">
Result = ${resultSum }
</c:if>
Result = <c:out value="${resultSum }"/>
I resolve problem
In main controller I open new Session and transaction.
In DataImplementation I getCurrent session and open transaction in the same session
#RequestMapping(value = "/fillData", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
public #ResponseBody
ModelAndView fillData(
Locale locale,
HttpServletRequest request, HttpServletResponse response){
ModelAndView model = new ModelAndView("index");
Random number = new Random();
Integer x = number.nextInt(3)+1;
if (x < 0) x = x * - 1;
Session sess = sessionFactory.openSession();
Transaction tx = null;
try{
tx = sess.beginTransaction();
Integer result = dataService.fillData(x);
model.addObject("resultSum", result);
tx.commit();
}
catch (Exception e) {
if (tx!=null && tx.getLocalStatus() != LocalStatus.ROLLED_BACK)
tx.rollback();
logger.error("Error {}.", e.getMessage());
e.printStackTrace();
}
finally {
sess.close();
}
return model;
}
do not close session in dao implementation. It will be closed in controller
#Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public Integer fillData(Integer number) throws Exception{
Session sess = sessionFactory.getCurrentSession();
Integer sumNumbers = -1;
Transaction tx = null;
try{
tx = sess.beginTransaction();
emptyTable();
for(int i = 0; i < number; i++){
Random n = new Random();
Integer x = n.nextInt(100)+1;
DataModel dm = new DataModel(i+1, x);
addData(dm);
}
sumNumbers = getSumNumber();
tx.commit();
}
catch (Exception e) {
if (tx!=null && tx.getLocalStatus() != LocalStatus.ROLLED_BACK)
tx.rollback();
e.printStackTrace();
}
finally {
//will be closed in controller sess.close();
}
return sumNumbers;
}

Problems with loading resources Spring mvc

i collided with some problems when i was writing web app.
When i use URL like this http://localhost:8080/user i have no problems and my app work correctly, but when i use URL such as http://localhost:8080/some-intermediate-node/user i have pages without any style and java-script code.
Belong i show my dispatcher servlet config
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.excbooks.controller")
public class ServletConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**").addResourceLocations("/css");
registry.addResourceHandler("/js/**").addResourceLocations("/js");
}
#Bean
public InternalResourceViewResolver setupViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix("");
resolver.setViewClass(JstlView.class);
return resolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
and my controller
#Controller
public class MainController {
{
BasicConfigurator.configure();
}
#RequestMapping(value = "/d/login", method = RequestMethod.GET)
public String login(Model model){
return "log-in.html";
}
#RequestMapping(value = "/d/user", method = RequestMethod.GET)
public String userProfile(Model model){
User user = new User();
user.setId(new BigInteger("1"));
user.setUsername("Sashko");
model.addAttribute("user",user);
return "index.jsp";
}
}
Link to my JSP index https://drive.google.com/file/d/0B42ezhAKqwZlcUEyVkR5amNIaDg/view?usp=sharing
Within your JSP, I suspect the javacsript/css files are pulled in roughly like...
<link rel="stylesheet" href="css/my.css">
<script src="js/my.js"></script>
The issue is that the href and src attributes specify relative URLs. They correctly point to your files when the URL is http://localhost:8080/user, but when the URL is http://localhost:8080/some-intermediate-node/user the browser will look for...
http://localhost:8080/some-intermediate-node/css/my.css
http://localhost:8080/some-intermediate-node/js/my.js
respectively.
Change the href and src attributes so that they start with a forward slash (/) character.
Change CSS and javascript href to /css/** and /js/**
For example :
<link rel="stylesheet" href="/css/bootstrap.min.css">
<script src="/js/jquery-1.12.3.min.js"></script>

Static resource cannot be served with Spring MVC

I'm trying to serve an static resource (css file).
I already register the location and handler
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/resources/");
}
}
so the Tomcat's Logger displays the correct mapping to resource
Mapped URL path [/resources/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
When the browser renders the view, the inspector displays a 404 error trying to get the static resource.
AppInitializer.java
#Configuration
#ComponentScan("com.learning")
#EnableWebMvc
public class ApplicationInitializer extends WebMvcConfigurerAdapter implements WebApplicationInitializer {
private final Logger LOGGER = Logger.getLogger(ApplicationInitializer.class.getName());
public static final String DISPATCHER_SERVLET_NAME = "dispatcher";
#Autowired
private ApplicationContext applicationContext;
public ApplicationInitializer() {
}
//region Context Initialization Area
public void onStartup(ServletContext servletContext) throws ServletException {
WebApplicationContext springContext = getSpringApplicationContext();
MyDispatcherServlet dispatcherServlet = new MyDispatcherServlet(springContext);
servletContext.addListener(new ContextLoaderListener(springContext));
servletContext.setSessionTrackingModes(EnumSet.of(SessionTrackingMode.COOKIE));
servletContext.getSessionCookieConfig().setHttpOnly(true);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet(DISPATCHER_SERVLET_NAME, dispatcherServlet);
dispatcher.addMapping("/");
dispatcher.setLoadOnStartup(1);
}
private WebApplicationContext getSpringApplicationContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
LOGGER.info(String.format("Registering springApplicationContext: %s", context));
// Loads into container first
context.register(ApplicationInitializer.class);
LOGGER.info(String.format("Registration success of springApplicationContext: %s", context));
return context;
}
//endregion
//region ViewResolver Region
#Bean
public ViewResolver viewResolver() {
//Runs after coontroller ends its execution. It receives the view name to be processed.
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
resolver.setCharacterEncoding("UTF-8");
return resolver;
}
#Bean
public TemplateEngine templateEngine() {
// Processes the template
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setEnableSpringELCompiler(true);
engine.setTemplateResolver(templateResolver());
return engine;
}
private ITemplateResolver templateResolver() {
//Resolves templates with provided prefix and suffix
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setApplicationContext(applicationContext);
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".html");
resolver.setTemplateMode(TemplateMode.HTML);
return resolver;
}
//endregion
//region ResourceHandler Region
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/resources/");
}
//endregion
}
Hello.html
h1 {
color: red;
text-align: center;
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="/resources/css/MyCss.css" th:href="#{/resources/css/MyCss.css}"/>
</head>
<body>
<h1 th:text="'Hello ' + ${name}">Hello World</h1>
</body>
</html>
It supposed to displays as the running snippet... but as I mentioned, the app is not able to find and load the resource.
Log File
Any help?
http://localhost:8080/resources/css/MyCss.css
you are missing the webapp name:
http://localhost:8080/webapp_name/resources/css/MyCss.css
Within your: link rel="stylesheet" ...
Use the Spring URL tag, in order to resolve your URL better.
Here is how i use to import bootstrap.min.css:
<link rel="stylesheet" href='<spring:url value="/resources/bootstrap/bootstrap.min.css"/>' type="text/css" />
Don't forget to add the taglib, like this:
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>

Categories

Resources