Very simple Spring MVC sample with thymeleaf not working - spring-mvc

I am very disappointed, I followed a tutorial on how to add Thymeleaf to a Spring MVC project but it doesn't even work with a 3-classes sample project. Thymeleaf cannot find my views and I don't know what I am missing.
Stacktrace :
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "ServletContext resource [/WEB-INF/views/test.html]")
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:866)
javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
SpringMVCConfiguration.class
#Configuration
#ComponentScan({ "main.java" })
#EnableWebMvc
public class SpringMVCConfiguration implements WebMvcConfigurer {
#Autowired
private ApplicationContext applicationContext;
#Bean
public SpringResourceTemplateResolver templateResolver() {
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(applicationContext);
templateResolver.setPrefix("/WEB-INF/views/");
templateResolver.setSuffix(".html");
return templateResolver;
}
#Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
templateEngine.setEnableSpringELCompiler(true);
return templateEngine;
}
#Override
public void configureViewResolvers(ViewResolverRegistry registry) {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
registry.viewResolver(resolver);
}
}
DispatcherServletConfiguration.class
public class DispatcherServletConfiguration extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { SpringMVCConfiguration.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
TestController.class
#Controller
public class TestController {
#GetMapping("/test")
public String test(Model model) {
System.out.println("controller test");
return "test";
}
}
In Eclipse, the HTML file is located here :
-- Project
-- WebContent
-- WEB-INF
-- views
- test.html
test.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
</head>
<body>
<h1>TEST</h1>
</body>
</html>

To get off the ground running faster, I would suggest using spring-boot with its thyme-leaf starter. It handles most of the frustrating wiring code to avoid these issues.
https://www.mkyong.com/spring-boot/spring-boot-hello-world-example-thymeleaf/
Per your code, I'm guessing your component scan is wrong. Can you switch it from main.java to the root of your package hierarchy... whatever that is? Its probably the package name that the main.java file is in.
Also, maybe try moving your WEB-INF to src/main/web-app/WEB-INF?

Related

Use JSP and Thymeleaf views in Spring Boot app

There are several similar questions on the site and on the web in general but I haven't been able to make them work in my example as much as I've tried.
I'm working with Spring Boot for the first time and I'm stuck trying to include JSP views via an InternalResourceViewResolver. I already got Thymeleaf views to work.
Application.java
#SpringBootApplication
#ComponentScan("controller")
#EnableWebSecurity
#Configuration
public class Application extends WebSecurityConfigurerAdapter {
public static void main(String args[]) {
SpringApplication.run(Application.class, args);
}
#Bean
public ITemplateResolver templateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setPrefix("classpath:/templates/");
resolver.setSuffix(".html");
resolver.setTemplateMode(TemplateMode.HTML);
resolver.setCharacterEncoding("UTF-8");
resolver.setCacheable(false);
resolver.setOrder(1);
return resolver;
}
//intended for the .jsp view
#Bean
public InternalResourceViewResolver jspResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("classpath:/templates/jsp/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
resolver.setOrder(2);
return resolver;
}
#Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.addTemplateResolver(new UrlTemplateResolver());
templateEngine.addTemplateResolver(templateResolver());
//IKD if/how I should somehow add jspResolver() here
templateEngine.addDialect(new SpringSecurityDialect());
templateEngine.addDialect(new LayoutDialect(new GroupingStrategy()));
templateEngine.addDialect(new Java8TimeDialect());
return templateEngine;
}
#Bean
#Description("Thymeleaf View Resolver")
public ThymeleafViewResolver viewResolver() {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setOrder(0);
return viewResolver;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/users/**").hasRole("USER")//USER role can access /users/**
.antMatchers("/admin/**").hasRole("ADMIN")//ADMIN role can access /admin/**
.antMatchers("/quests/**").permitAll()// anyone can access /quests/**
.anyRequest().authenticated()//any other request just need authentication
.and()
.formLogin();//enable form login
}
#Override
protected void configure(AuthenticationManagerBuilder builder) throws Exception {
builder.inMemoryAuthentication()
.passwordEncoder(passwordEncoder())
.withUser("tim").password(passwordEncoder().encode("123")).roles("ADMIN")
.and()
.withUser("joe").password(passwordEncoder().encode("234")).roles("USER");
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
MainController.java
#Controller
public class MainController {
#GetMapping("/")
ModelAndView index(Principal principal) {
ModelAndView mv = new ModelAndView("home");
if (principal != null) {
mv.addObject("message", principal.getName());
} else {
mv.addObject("message", "anon.");
}
return mv;
}
#GetMapping("/**")
String request(HttpServletRequest request, Model model) {
Authentication auth = SecurityContextHolder.getContext()
.getAuthentication();
ModelAndView mv = new ModelAndView("home");
model.addAttribute("uri", request.getRequestURI())
.addAttribute("user", auth.getName())
.addAttribute("roles", auth.getAuthorities());
return "html"; //<-- whenever I change this to return "jsp/jsp"; it breaks
}
html.html (Thymeleaf)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<body>
<p>
URI: <h3 th:text="${uri}"></h3>
User: <h3 th:text="${user}"></h3>
Roles: <h3 th:text="${roles}"></h3>
/admin/<br/>
/users/<br/>
/others/<br/>
/quests/<br/><br/>
</p>
<form th:action="#{/logout}" method="post">
<input type="hidden"
name="${_csrf.parameterName}"
value="${_csrf.token}"/>
<input type="submit" value="Logout">
</form>
</body>
</html>
When I try to make this work with a JSP file well, the browswer only outputs
HTTP Status 500 ? Internal Server Error
and in NetBeans Output window, where gradle's task run is, well, running, the log shows this at the very top (the whole log is quite extensive):
2018-10-07 18:09:40.070 ERROR 6024 --- [nio-8080-exec-4] org.thymeleaf.TemplateEngine : [THYMELEAF][http-nio-8080-exec-4] Exception processing template "jsp/jsp": An error happened during template parsing (template: "class path resource [templates/jsp/jsp.html]")
JSP view I'm trying to include
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html lang="en">
<body>
<p>URI: ${uri} <br/>
User : ${user} <br/>
roles: ${roles} <br/><br/>
/admin/<br/>
/users/<br/>
/others/<br/>
/quests/<br/><br/>
</p>
<form action="/logout" method="post">
<input type="hidden"
name="${_csrf.parameterName}"
value="${_csrf.token}"/>
<input type="submit" value="Logout">
</form>
</body>
</html>
Finally, my project tree:
My assumption is that the app does not know about the file jsp.jsp inside folder templates/jsp, which is why I'm aiming the question to view resolvers, but as I said, I could easily be wrong about it.
This is just an example I'm trying to materialize and build on, so feel free to shred it with suggestions, thanx.
Just adding one more view resolver for jsp won't do,
we also need to add one more template resolver for jsp and connect it to spring template engine. JSP template resolver order must be the last, because it throws exception (smth like 'page not found') when can not resolve. The code below works in Spring Boot 2.
package org.jwebshop.webshop.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
import javax.annotation.Resource;
#Configuration
#EnableWebMvc
public class ViewConfiguration implements WebMvcConfigurer {
#Resource
protected ApplicationContext applicationContext;
#Resource
protected SpringTemplateEngine springTemplateEngine;
#Bean
public ThymeleafViewResolver thymeleafViewResolver(){
final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setViewNames(new String[] {"thyme/*"});
viewResolver.setExcludedViewNames(new String[] {"jsp/*"});
viewResolver.setTemplateEngine(springTemplateEngine);
viewResolver.setCharacterEncoding("UTF-8");
return viewResolver;
}
#Bean
public InternalResourceViewResolver jspViewResolver(){
final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
viewResolver.setViewNames("jsp/*");
return viewResolver;
}
#Bean
public SpringResourceTemplateResolver thymeleafTemplateResolver(){
final SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(applicationContext);
templateResolver.setPrefix("/WEB-INF/views/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(TemplateMode.HTML);
templateResolver.setCacheable(false);
templateResolver.setOrder(0);
return templateResolver;
}
#Bean
public SpringResourceTemplateResolver jspTemplateResolver(){
final SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(applicationContext);
templateResolver.setPrefix("/WEB-INF/views/");
templateResolver.setSuffix(".jsp");
templateResolver.setTemplateMode(TemplateMode.HTML);
templateResolver.setCacheable(false);
templateResolver.setOrder(1);
templateResolver.setCharacterEncoding("UTF-8");
return templateResolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/webjars/**").addResourceLocations("/webjars/");
registry.addResourceHandler("/images/**").addResourceLocations("/images/");
registry.addResourceHandler("/css/**").addResourceLocations("/css/");
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
}
}
package org.jwebshop.webshop.controller.web.thymeleaf;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class RootController {
#Secured("ROLE_CUSTOMER")
#GetMapping({"/", "/index"})
public String root() {
return "thyme/index";
}
}
package org.jwebshop.webshop.controller.web.jsp;
import org.jwebshop.webshop.dto.converter.impl.UserDataConverter;
import org.jwebshop.webshop.dto.data.UserData;
import org.jwebshop.webshop.entity.User;
import org.jwebshop.webshop.service.UserService;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import javax.annotation.Resource;
#Controller
public class LuckyController {
#Resource
protected UserService userService;
#Resource
protected UserDataConverter userDataConverter;
#Secured("ROLE_CUSTOMER")
#GetMapping("/lucky")
public String hello(final Model model, final Authentication auth) {
final User user = userService.findByEmail(auth.getName());
final UserData userData = userDataConverter.convertFrom(user);
model.addAttribute("userData", userData);
return "jsp/lucky";
}
}
Folder structure:
webapp
|
WEB-INF
|
views
| |
jsp thyme
https://imgur.com/qOTgYZW
I haven't actually tried it yet, as I used jsp and thymeleaf on totally different project. And also converted jsp into thymeleaf, but not use it together. I just want to help, as I bump into this question and I find it interesting.
I assume you already checked this thread? Using both Thymeleaf and JSP
According to this blog, you can leave as is the default configuration of thymeleaf. You just need to add InternalResourceViewResolverfor the jsp configuration.
Full example here:
Add below dependencies to your pom.xml file
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
In your application.properties set thymeleaf view names and JSP
configuration for internal view resolution
spring.view.prefix:/WEB-INF/
spring.view.suffix:.jsp
spring.view.view-names:jsp/*
spring.thymeleaf.view-names:thymeleaf/*
create a configuration class for view resolution for JSP pages
package com.example.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
#Configuration
public class JspConfig {
#Value("${spring.view.prefix}")
private String prefix;
#Value("${spring.view.suffix}")
private String suffix;
#Value("${spring.view.view-names}")
private String viewNames;
#Bean
InternalResourceViewResolver jspViewResolver() {
final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix(prefix);
viewResolver.setSuffix(suffix);
viewResolver.setViewClass(JstlView.class);
viewResolver.setViewNames(viewNames);
return viewResolver;
}
}

Can not connect to the JpenMQ queue in citrus-simulator-jms

It would not be bad to expand the documentation on citrus for different types of queues!
This is the piece of code in which I'm trying to start the Simulator.class:
#SpringBootApplication
public class Simulator extends SimulatorJmsAdapter {
public static void main(String[] args) {
SpringApplication.run(Simulator.class, args);
}
#Override
public ConnectionFactory connectionFactory() {
QueueConnectionFactory factory = new QueueConnectionFactory();
try {
factory.setProperty(ConnectionConfiguration.imqAddressList, "mq://192.168.116.21:7676");
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new QueueConnectionFactory();
}
#Override
public boolean synchronous(SimulatorJmsConfigurationProperties simulatorJmsConfiguration) {
return true;
}
}
And here context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:citrus="http://www.citrusframework.org/schema/config"
xmlns:citrus-jms="http://www.citrusframework.org/schema/jms/config"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.citrusframework.org/schema/jms/config http://www.citrusframework.org/schema/jms/config/citrus-jms-config.xsd
http://www.citrusframework.org/schema/config http://www.citrusframework.org/schema/config/citrus-config.xsd">
<citrus:schema-repository id="schemaRepository">
<citrus:locations>
<citrus:location path="classpath:xsd/HelloService.xsd"/>
</citrus:locations>
</citrus:schema-repository>
<!-- Test JMS client -->
<citrus-jms:sync-endpoint id="simulatorEndpoint"
destination-name="Citrus.Simulator.Inbound"/>
<bean id="connectionFactory" class="com.sun.messaging.QueueConnectionFactory.QueueConnectionFactory">
<property name="ConnectionConfiguration" ref="ConnectionConfiguration" />
</bean>
<bean id="ConnectionConfiguration" class="com.sun.messaging.ConnectionConfiguration">
<property name="imqAddressList" ref="mq://192.168.116.21:7676" />
</bean>
</beans>
When I run clean install, spring-boot: run. I get this error: C4003: Error occurred on connection creation [localhost:7676].
Somebody can help me, why it is happen? And how I correctly to create file context I need some example?
Here my answer: In class EndpointConfig I added few Beans:
#Bean
public QueueConnectionFactory connectionFactory() throws JMSException {
QueueConnectionFactory connectionFactory = new QueueConnectionFactory();
connectionFactory.setProperty(ConnectionConfiguration.imqAddressList, "mq://#####.stage.tema:7676");
return connectionFactory;
}
#Bean
public DefaultJmsListenerContainerFactory jmsListenerContainerFactory(QueueConnectionFactory connectionFactory,
PlatformTransactionManager transactionManager) {
DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
factory.setTransactionManager(transactionManager);
factory.setSessionTransacted(true);
factory.setSessionAcknowledgeMode(Session.SESSION_TRANSACTED);
// factory.setErrorHandler(errorHandler);
return factory;
}
#Bean
public JmsTemplate jmsTemplate(QueueConnectionFactory qcf) throws JMSException {
JmsTemplate template = new JmsTemplate();
template.setConnectionFactory(qcf);
return template;
}
In my test I send my personal object which was injected in pom.Here code:
#CitrusTest
#Test
public void send() {
action(new AbstractTestAction() {
#Override
public void doExecute(TestContext context) {
MORequest req = new MORequest(param1, param2, param3);
//Method of object
req.setSourcePort(4);
jmsTemplate.send("queue_name", (Session sn) -> sn.createObjectMessage(req));
}
});
}

Spring Boot OAuth2 Resource server configs not reflecting

Hi I am setting up spring boot Oauth2, for some reason the resource server configs are not being recognised.
I am able to generate the bearer token but when I try to hit any of the url the response is the login page from basic http spring security.
My guess I am missing some backend stuff the spring boot does by default.
I have used similar configs for a normal spring MVC project and it worked. Any pointers as to why this is happening will be helpful.
Like to add one more question spring seems to be finding these config classes earlier we needed to use #Import some one explain how spring does this or links to any documentation will also do.
AppStart.java
#SpringBootApplication(scanBasePackages = { "com.spr.*" })
public class AppStart extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(AppStart.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(AppStart.class);
}
}
AuthorizationServer.java
#Configuration
#EnableAuthorizationServer
public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {
#Autowired
private TokenStore tokenStore;
#Autowired
#Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
#Autowired
private DataSource dataSource;
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("confidential").secret("secret").authorizedGrantTypes("password").scopes("read",
"write");
// clients.jdbc(dataSource);
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore).authenticationManager(authenticationManager);
}
#Bean
#Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setSupportRefreshToken(true);
tokenServices.setTokenStore(tokenStore);
return tokenServices;
}
}
AppSecurityConfigs.java
#Configuration
#EnableWebSecurity
public class AppSecurityConfigs extends WebSecurityConfigurerAdapter {
#Autowired
private DataSource dataSource;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("asd").password("asd").authorities("USER");
}
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Bean
public TokenStore tokenStore() {
// return new JdbcTokenStore(dataSource);
return new InMemoryTokenStore();
}
}
ResourceServer
#Configuration
#EnableResourceServer
public class ResourceServer extends ResourceServerConfigurerAdapter {
#Override
public void configure(final HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/private/**").hasAuthority("USER");
http.authorizeRequests().anyRequest().permitAll();
}
}

Spring MVC java config via AbstractAnnotationConfigDispatcherServletInitializer

Hi I have a strange problem,
I'am following this Tutorial (http://websystique.com/springmvc/spring-4-mvc-and-hibernate4-integration-example-using-annotations/) and at step 5, configurting initializer class there are two ways of doing that:
1 with WebAppInitializer (my code below)
public class SpindleSpringWebAppInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
appContext.register(AppConfig.class);
appContext.setServletContext(servletContext);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
"SpringDispatcher", new DispatcherServlet(appContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
With AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer (my code here)
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
This is my AppConfig.java
#Configuration
#EnableWebMvc
public class AppConfig extends WebMvcConfigurerAdapter{
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/").setCachePeriod(31556926);
}
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
}
The Thing is that when I use the first method everything works, but when I use the second one i get 404 (description The requested resource is not available). I have no other errors and I have no idea how to debug this. I wouldn't bother but I'm trying to implement Spring Security to the code and as I understand the secon type of initializer is the preffered type nowdays.
I'm using Maven, STS, Pivotal tc Servert Developer Edition. Thanks for any feedback.
The problem is solved. Target folder still held web.xml and context.xml files. Deleting target folder and reinstalling the app was the right thing to do

Get exception when using injection with a simple HelloEJB project

I am now learning EJB and got a problem when testing the Injection functionality. Here is my code (I create an EJB project in Eclipse).
I run the EJB with embedded Glassfish, and run the test(main) independently, but always get this exception:
java.lang.NullPointerException
at com.example.MainUsingInjection.runTest(MainUsingInjection.java:11)
at com.example.MainUsingInjection.main(MainUsingInjection.java:20)
I hope anyone can help me with this. Thank you very much.
HelloSessionBean.java
package com.example;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
#Stateless
#LocalBean
public class HelloSessionBean implements HelloSessionBeanRemote {
public HelloSessionBean() { }
public void helloMethod() {
System.out.println("Hello World!\n");
}
}
HelloSessionBeanRemote.java
package com.example;
import javax.ejb.Remote;
#Remote
public interface HelloSessionBeanRemote {
public void helloMethod();
}
MainUsingJnjection.java
package com.example;
import javax.ejb.EJB;
public class MainUsingInjection {
#EJB(name="HelloSessionBean")
public static HelloSessionBeanRemote bean;
public void runTest() throws Exception {
bean.helloMethod();
}
public static void main(String[] args) {
MainUsingInjection cli = new MainUsingInjection();
try {
cli.runTest();
} catch (Exception e) {
e.printStackTrace();
}
}
}
The stack trace suggests that you've directly launched the main method. In order to use injection in the main class, you must use the application client container.

Resources