Can't see a message form modelAndView Object in JSP representation page - spring

Good afternoon, sorry if the question has already been asked but ... I did not find the answer in those versions.
I’m studying spring by tuturial (https://www.youtube.com/watch?v=JfeCmn8NT88), trying to write a simple CRUD (I haven’t even reached to logic of the program)and i face the problem: Can't see a message form modelAndView Object in JSP representation page, IDEA tells that cannot resolve variable.
I understand that this may be redundant but here are all my files.
my project hierarchy
WebAppInitializer
package com.customermanager.config;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
public class WebAppInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
applicationContext.register(WebMVCConfig.class);
ServletRegistration.Dynamic dispacher = servletContext.addServlet("SpringDispacher", new DispatcherServlet(applicationContext));
dispacher.setLoadOnStartup(1);
dispacher.addMapping("/");
}
}
WebMVCConfig
package com.customermanager.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan("com.customermanager.*")
public class WebMVCConfig {
#Bean(name = "viewResolver")
public InternalResourceViewResolver getViewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
CustomerController
package com.customermanager.customer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class CustomerController {
#RequestMapping(value = "/")
public ModelAndView home() {
ModelAndView model = new ModelAndView("index");
model.addObject("message", "hello world");
return model;
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
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_3_1.xsd"
version="3.1">
</web-app>
index.jsp
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Customer Manager</title>
</head>
<body>
<H1>${message}</H1>
<p>Message: ${message}</p>
Hello
</body>
</html>
In output i dont see my message: Hello from Spring MVC
thanks in advance for your help

Related

How to solve the error message: "Whitelabel Error Page" for Spring Boot

I'm new with spring boot and I'm trying to make a project with Spring MVC + Spring Boot2 + JSP + Spring Data + DB Oracle.
When I run the simple application, The first message error I was been:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Fri Apr 17 10:20:05 CEST 2020
There was an unexpected error (type=Not Found, status=404).
No message available
I found a lot of documention about this error and I tested different solutions but nothing was fine for my problem. Below the tests I did:
1) I make sure that my main class was in the root package and I put the other packages int the sub level;
2) I used de #ComponentScan in the main class in this way #ComponentScan({"com.dashboard.demo.controller"});
3) in the application.properties I used this command server.servlet.context-path=/oee
This is my code:
Application.properties
spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp
server.servlet.context-path=/oee
## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url= jdbc:oracle:thin:#serverIP:Port:DB11G
spring.datasource.username= Server name
spring.datasource.password= password
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.Oracle10gDialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = create-drop
spring.jpa.show-sql= true
server.port = 8091
Main
package com.dashboard.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
public class OeeApplication extends SpringBootServletInitializer{
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(OeeApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(OeeApplication.class, args);
}
}
OEEController
package com.dashboard.demo.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.dashboard.demo.entities.OEE;
import com.dashboard.demo.service.OEEService;
#Controller
public class OEEController {
#Autowired
private OEEService oeeService;
#RequestMapping(value = "/oee}", method = RequestMethod.GET)
public String listAll(Model model)
{
List<OEE> oee = oeeService.SelDevice();
model.addAttribute("OEE",oee);
return "oee";
}
}
OEEServiceImpl
package com.dashboard.demo.service;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dashboard.demo.entities.OEE;
import com.dashboard.demo.repository.OEERepository;
#Service
#Transactional
public class OEEServiceImpl implements OEEService{
#Autowired
private OEERepository oeeRepository;
#Override
public List<OEE> SelDevice()
{
return oeeRepository.findAll();
}
}
OEERepository
package com.dashboard.demo.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.dashboard.demo.entities.OEE;
import com.dashboard.demo.entities.OEEid;
#Repository
public interface OEERepository extends JpaRepository<OEE, OEEid>
{
}
I'm managing a composite key and I've create a class for the composite key and another to manage the entity. I'm catching the error int this package.
package com.dashboard.demo.entities;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import org.springframework.format.annotation.DateTimeFormat;
import lombok.Data;
#Data
#Embeddable
public class OEEid implements Serializable{
/**
*
*/
private static final long serialVersionUID = 4512114330774744082L;
#DateTimeFormat(pattern = "dd-MM-yy HH:mm:ss")
#Column(name = "MSO_GIORNO_LAV")
private Date date;
#Column(name = "MSO_MACCHINA")
private String device;
public OEEid(Date date, String device) {
super();
this.date = date;
this.device = device;
}
}
package com.dashboard.demo.entities;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.IdClass;
import javax.persistence.Table;
import lombok.Data;
#Entity
#Table(name = "MES_OEE")
#Data
public class OEE implements Serializable
{
/**
*
*/
private static final long serialVersionUID = -7738922358421962399L;
#EmbeddedId
private OEEid oeeID;
#Basic(optional = false)
#Column(name = "MSO_QUANTITA")
private int amount;
#Basic(optional = false)
#Column(name = "MSO_OEE")
private float oee;
}
oee.jsp
<!DOCTYPE html>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css"
href="webjars/bootstrap/3.3.7/css/bootstrap.min.css" />
<c:url value="/css/main.css" var="jstlCss" />
<link href="${jstlCss}" rel="stylesheet" />
</head>
<body>
<div class="container">
<header>
<h1>Spring MVC + JSP + JPA + Spring Boot 2</h1>
</header>
<div class="starter-template">
<h1>Users List</h1>
<table
class="table table-striped table-hover table-condensed table-bordered">
<tr>
<th>Date</th>
<th>Device</th>
<th>Amount</th>
<th>OEE</th>
</tr>
<c:forEach items="${OEE}" var="oee">
<tr>
<td>${oee.oeeID.date}</td>
<td>${oee.oeeID.device}</td>
<td>${oee.amount}</td>
<td>${oee.oee}</td>
</tr>
</c:forEach>
</table>
</div>
</div>
<script type="text/javascript"
src="webjars/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
Can anyone give me any suggestions to solve this error message?
Thanks
This is my project directory
Can you please try by removing this server.servlet.context-path=/oee from properties file and try with localhost:8080/oeee

Can't access the get method from expression language in jsf

I can't access getCpuUsage() method from my xhtml code via
<h:outputText id="cpu_usage"
value="#{cpuUsageBean.cpuUsage} %" />
When i add #bean annotation to my getCpuUsage() method this method works when component initialized.But after that when i try to access via xhtml file seen on the page nothing happened at all. I hope you understand me well . Thanks in advance
my xhtml :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head></h:head>
<h:body style="margin-left:50px">
<h2>PrimeFaces Polling Example</h2>
<h:form>
CPU usage:
<b> <h:outputText id="cpu_usage"
value="#{cpuUsageBean.cpuUsage} %" />
</b>
<p:poll interval="1" update="cpu_usage" />
</h:form>
</h:body>
</html>
MY MANAGED BEAN SO COMPONENT:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import javax.inject.Inject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.InitBinder;
import lombok.extern.slf4j.Slf4j;
#Component
#Scope("VIEW")
//#ViewScoped
//#Named
#Slf4j
public class CpuUsageBean {
private AtomicInteger cpuUsage;
#PostConstruct
public void init() {
cpuUsage = new AtomicInteger(50);
ExecutorService es = Executors.newFixedThreadPool(1);
es.execute(() -> {
while (true) {
// simulating cpu usage
int i = ThreadLocalRandom.current().nextInt(-10, 11);
int usage = cpuUsage.get();
usage += i;
if (usage < 0) {
usage = 0;
} else if (usage > 100) {
usage = 100;
}
cpuUsage.set(usage);
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
}
}
});
}
public int getCpuUsage() {
System.out.println("-----getCpuUsage : " + cpuUsage);
log.error("---------- getCpuUsage calisti");
return cpuUsage.get();
}
}
MY SPRİNGBOOT APP CLASS :
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#ComponentScan(basePackages = "com.tutorial.PrimeFacesTutorial.controller,com.tutorial.PrimeFacesTutorial")
public class PrimeFacesTutorialApplication {
public static void main(String[] args) {
SpringApplication.run(PrimeFacesTutorialApplication.class, args);
}
}

Error creating Bean with name 'xmlViewResolver'

i am building a small web application with spring boot and theirfore i do not have an xml files as all configurations are handled by spring boot capabilities , however i decided to add an xmlViewResolver and gave the first priority. With that said i keep getting the following error:
Please Assist me in anyway possible , thank you
Configuration file is as follows:
package com.aubrey.demo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.XmlViewResolver;
#Configuration
#ComponentScan
#EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean
public InternalResourceViewResolver jspViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsps/");
resolver.setSuffix(".jsp");
return resolver;
}
#Bean(name = "messageSource")
public ReloadableResourceBundleMessageSource getMessageSource() {
ReloadableResourceBundleMessageSource resource = new ReloadableResourceBundleMessageSource();
resource.setBasename("classpath:messages");
resource.setDefaultEncoding("UTF-8");
return resource;
}
#Bean
public XmlViewResolver xmlViewResolver(){
XmlViewResolver resolver = new XmlViewResolver();
Resource resource = new ClassPathResource("/WEB-INF/Spring/views.xml");
resolver.setLocation(resource);
//xmlViewResolver().setOrder(1);
return resolver;
}
}
views.xml is as follows :
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="welcome" class="org.springframework.web.servlet.view.JstlView">
<property name="url" value="/WEB-INF/views/xml_welcome.jsp" />
</bean>
</beans>
</beans>
Home controller is as follows:
package com.aubrey.demo.controllers;
import com.aubrey.demo.data.entities.Project;
import com.aubrey.demo.data.entities.Sponsor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class HomeController {
#RequestMapping("/home")
public String goHome(Model model){
Project project = new Project();
project.setName("First Project");
project.setSponsor(new Sponsor("NASA", "555-555-5555", "nasa#nasa.com"));
project.setDescription("This is a simple project sponsored by NASA");
model.addAttribute("currentProject", project);
return "welcome";
}
}

Spring Boot - unable to resolve JSP page

application.yml
spring:
mvc.view:
prefix: /
suffix: .jsp
SampleController.java
package springboot_demo;
import javax.annotation.Resource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import springboot_demo.service.StudentService;
#Controller
#SpringBootApplication
public class SampleController extends SpringBootServletInitializer{
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SampleController.class);
}
#Resource
private StudentService studentService;
#RequestMapping("/")
public String home(Model model) {
model.addAttribute("data", studentService.list());
return "index";
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleController.class, args);
}
}
The 'data' is correctly fetched from database, but the JSP page seems not compiled. I visit http://localhost:8080 and the browser shows me like this:
<%#page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<h2>Hello World!</h2>
<c:forEach items="${data }" var="i">
<h2>${i.id }${i.name }</h2>
</c:forEach>
</body>
</html>

Annotation based springapplication with no web.xml not working

I am trying to build a spring project without the use of web.xml, but I am frequently getting this error, I've tried everything but so far nothing has solved the problem,
**Sep 15, 2015 11:36:50 AM org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [/TestApp/] in DispatcherServlet with name 'dispatcher'**
here is my configuration:-
package com.springWeb.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcher ServletInitializer;
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer implements WebApplicationInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
System.out.println("\n\n\n\n\n\n now deploying");
return new String[]{ "/" };
}
}
My AppConfig Class
package com.springWeb.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
#EnableWebMvc
#Configuration
#ComponentScan(basePackages = "com.springweb.controller.*")
#Import({ SpringSecurityConfig.class })
public class AppConfig {
#Bean
public InternalResourceViewResolver viewResolver() {
System.out.println("\n\n\nello hello hello");
InternalResourceViewResolver viewResolver
= new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/pages/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
And My controller
package com.springWeb.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class TestController {
#RequestMapping(value = { "/", "/welcome**" }, method = RequestMethod.GET)
public String index() {
System.out.println("test est test ets tstsd");
return "index2";
}
}
I suspect it's your #ComponentScan directive. Try changing it to
#ComponentScan({"com.springWeb.*"})
Looks like you maybe have a type-o with com.springweb in all lowercase.

Resources