Root Context path in spring application - spring

I am running application using tomcat server, when server start i will get url
http://localhost:8080/TestApp/
and displaying index.jsp file but when i click link in index file it is displaying url like
http://localhost:8080/testsuccess
but it should display like
http://localhost:8080/TestApp/testsuccess
can any please help me to solve this.
SpringConfiguration.java
#Configuration
#EnableWebMvc
#ComponentScan("com.testapp")
#EnableTransactionManagement
public class SpringConfiguration {
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
SpringWebAppInitializer.java
public class SpringWebAppInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
appContext.register(SpringConfiguration.class);
ServletRegistration.Dynamic dispatcher = container.addServlet(
"SpringDispatcher", new DispatcherServlet(appContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
MyController.java
#Controller
public class MyFirstController
{
#RequestMapping(value = "/" , method = RequestMethod.GET)
public String testApp() throws Exception{
return "index";
}
#RequestMapping(value = "/testsuccess", method = RequestMethod.GET)
public String testAppSuccess() {
Map<String, Object> model = new HashMap<String, Object>();
return "success";
}
}

got it i should use
Next
it will give the context path.

I think your problem comes from the link inside your index.jsp. They might look like ... You should use either jstl or spring tag lib to handle links / urls in your pages. They both have the ability to prepend the deployment / context path of your application.
jstl example:
with taglib xmlns:c="http://java.sun.com/jsp/jstl/core" included you can create an anchor like ..
spring example:
with taglib xmlns:spring="http://www.springframework.org/tags" your link will be created in two steps:
<spring:url value="/testsuccess" var="myurl" htmlEscape="true"/>
...
Update: Wrong function name in jstl taglib version.

Related

Thymeleaf - return rendered template to String

I was using this solution as an example:
Can I render Thymeleaf templates manually from a String?
but after processing template I am getting not rendered template:
my template (plans/test.html):
<!doctype html>
<html lang="pl">
<div th:text="${loki}"></div>
</html>
Java code that should renderd the template:
#RestController
public class PlansPageRestController {
#Autowired
TemplateEngine myTemplateEngine;
#RequestMapping(value = {"/public/plans"}, method = RequestMethod.POST, produces = "application/json")
public Map<String,String> getPlans(#RequestParam Map<String, String> requestParams) {
Context ctx = new Context();
ctx.setVariable("loki", "Some test value");
String htmlTemplate = myTemplateEngine.process("plans/test.html", ctx);
Map<String,String> result = new HashMap<>();
result.put("html", htmlTemplate );
result.put("result", "success" );
return result;
}
}
but as a result I am getting content of plans/test.html so:
<!doctype html>
<html lang="pl">
<div th:text="${loki}"></div>
</html>
I am working with spring boot 3.0.0 and regarding to pom I am using thymeleaf:
<artifactId>thymeleaf-spring6</artifactId>
<version>3.1.0.RELEASE</version>
Can anyone help me in finding what I am doing wrong?
my thymeleaf configuration:
#Configuration
public class ThymeleafConfiguration implements WebMvcConfigurer, ApplicationContextAware {
private ApplicationContext applicationContext;
#Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
#Bean
public TemplateEngine myTemplateEngine() {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setEnableSpringELCompiler(true);
engine.setTemplateResolver(templateResolver());
engine.setDialect(new LayoutDialect());
return engine;
}
private ITemplateResolver templateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setApplicationContext(applicationContext);
resolver.setPrefix("classpath:/templates/");
resolver.setTemplateMode(TemplateMode.HTML);
resolver.setCacheable(false);
resolver.setCacheTTLMs(0L);
resolver.setCharacterEncoding("UTF-8");
return resolver;
}
}
The reason your standard Thymeleaf expression is not being evaluated is because you have replaced the Thymeleaf "standard" dialect with the layout dialect:
engine.setDialect(new LayoutDialect());
(I should say "the Spring dialect", given you are using Spring-Thymeleaf.)
If you need to use the layout dialect, then you can add it to the engine - and still keep the standard dialect as well:
engine.addDialect(new LayoutDialect());
Or, you may not need the layout dialect at all (you do not use it in the sample HTML file in the question, but maybe you use it elsewhere). If that is the case, you can remove this line of code.
Just to add: The default Spring Boot settings should work without you needing to define any ThymeleafConfiguration class. But, again, there may be other places where you need to use a custom configuration (e.g. the UTF-8 encoding).

unable to load static file in spring 4

Hi I am trying to load the jquery file in jsp but getting 404
Find below the project structure
I have configured the following in configuration too
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = { "common.spring.controller" })
public class WebConfig {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
//viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/resources/");
}
}
below is how i include file in jsp
<script type="text/javascript" src="/resources/jsFiles/jquery-3.3.1.min.js"></script>
Dono why its not working.
UPDATE: I am able to see the resources folder under target/project snapshot/resources but getting 404 for url
http://localhost:8080/resources/jsfiles/jquery-3.3.1.min.js
directly hitting below Url didnt work either
http://localhost:8080/Sample/resources/jsfiles/jquery-3.3.1.min.js
Finally was able to resolve the issue
removing addResourceHandlers method and including the below code did the trick
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configure) {
configure.enable();
}
in jsp i used the include like below
<script type="text/javascript" src="resources/jsFiles/jquery-3.3.1.min.js"></script>

setting up spring view resolver using spring-java-config

I am trying to setup view-resolver for spring using java-config. I have tried 3 different method with different config found in 3 different sites. All of them working fine. My question is that Is there any specific standard / method / signature / interface method to defining the view-resolver ?
#Bean
public InternalResourceViewResolver setupViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver ();
resolver.setPrefix ("/WEB-INF/pages/");
resolver.setSuffix (".jsp");
resolver.setViewClass (JstlView.class);
return resolver;
}
ref-link http://habrahabr.ru/post/226663/
#Bean
public InternalResourceViewResolver jspViewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setPrefix("/WEB-INF/pages/");
bean.setSuffix(".jsp");
return bean;
}
ref-link https://samerabdelkafi.wordpress.com/2014/08/03/spring-mvc-full-java-based-config/
#Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
List< ViewResolver > resolvers = new ArrayList< ViewResolver >();
InternalResourceViewResolver r1 = new InternalResourceViewResolver();
r1.setPrefix("/WEB-INF/pages/");
r1.setSuffix(".jsp");
r1.setViewClass(JstlView.class);
resolvers.add(r1);
JsonViewResolver r2 = new JsonViewResolver();
resolvers.add(r2);
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setViewResolvers(resolvers);
resolver.setContentNegotiationManager(manager);
return resolver;
}
ref-link http://fruzenshtein.com/spring-java-configurations/
The answer is it depends on your requirements.
setupViewResolver and jspViewResolver do the same as long as JSTL is available on the classpath:
public InternalResourceViewResolver() {
Class<?> viewClass = requiredViewClass();
if (viewClass.equals(InternalResourceView.class) && jstlPresent) {
viewClass = JstlView.class;
}
setViewClass(viewClass);
}
Whereas contentNegotiatingViewResolver shows a more complex example where you want to render the response depending on the request content type.
If you need to register just a specific view resolver you can shorten registration to a simple one liner in Spring 4.1:
#EnableWebMvc
#Configuration
public class HystrixMvcConfiguration extends WebMvcConfigurerAdapter {
#Override
public void configureViewResolvers(final ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/views/", ".jsp");
}
}
ViewResolverRegistry supports builder methods for Velocity, Freemarker, Groovy templates and Tiles out of the box.

Spring mvc + Primefaces resources not found

I am trying to start my new project using spring webmvc (version 4.1.6) with primefaces (version 5.2) I am able start up the project, however when trying to acces css or other resources the urls looks like: http://localhost:8080/rais/public//javax.faces.resource/theme.css?ln=primefaces-aristo and results in a 404. The part: http://localhost:8080/rais/public/ looks as expected.
My configuration:
#Configuration
#EnableTransactionManagement
#EnableSpringConfigured
#EnableWebMvc
public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
//Set init params
// Use JSF view templates saved as *.xhtml, for use with Facelets
servletContext.setInitParameter("javax.faces.DEFAULT_SUFFIX", ".xhtml");
servletContext.setInitParameter("javax.faces.FACELETS_VIEW_MAPPINGS", "*.xhtml");
ServletRegistration.Dynamic facesServlet = servletContext.addServlet("Faces Servlet", javax.faces.webapp.FacesServlet.class);
facesServlet.setLoadOnStartup(1);
facesServlet.addMapping("*.xhtml");
ServletRegistration.Dynamic registration = servletContext.addServlet("dsp", new DispatcherServlet());
registration.setInitParameter("contextConfigLocation", "");
registration.setLoadOnStartup(1);
registration.addMapping("/");
servletContext.addListener(ConfigureListener.class);
servletContext.addListener(org.springframework.web.context.request.RequestContextListener.class);
//Add OpenEntityManagerInViewFilter Filter
servletContext.addFilter("openEntityManagerInViewFilter", OpenEntityManagerInViewFilter.class).addMappingForUrlPatterns(null, true, "/*");
super.onStartup(servletContext);
}
WebMVC configuration:
#Configuration
#EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
#Bean
ViewResolver viewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setViewClass(org.springframework.faces.mvc.JsfView.class);
resolver.setPrefix("/WEB-INF");
resolver.setSuffix(".xhtml");
return resolver;
}
faces-config.xml (ani hint in moving this to java config also greatly appreciated)
<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
<action-listener>org.primefaces.application.DialogActionListener</action-listener>
<navigation-handler>org.primefaces.application.DialogNavigationHandler</navigation-handler>
<view-handler>org.primefaces.application.DialogViewHandler</view-handler>
</application>
Any help is greatly appreciated. Please ask if additional information is required:
Ok changed the UrlBasedViewResolver(); to a InternalResourceViewResolver(); now it seems to be working.

Spring application can't reach jsp pages

In my spring application, I using the configuration based on java code instead xml files. When I try access any page from my application, the browser is redirect to the correct mapped url, but I still face a 404 error page.
My controller class is created this way:
#Controller
#RequestMapping(value="acesso")
public class AcessoController {
#RequestMapping(value="login")
public ModelAndView login() {
ModelAndView mav = new ModelAndView();
mav.setViewName("acesso/login");
return mav;
}
}
My WebAppInitializer.java is this:
#Order(value=1)
public class WebAppInitializer implements WebApplicationInitializer {
#SuppressWarnings("resource")
#Override
public void onStartup(ServletContext container) {
// Create the 'root' Spring application context
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(WebAppConfig.class);
// Create the dispatcher servlet's Spring application context
AnnotationConfigWebApplicationContext jspContext = new AnnotationConfigWebApplicationContext();
jspContext.register(JspDispatcherConfig.class);
// Register and map the dispatcher servlet
ServletRegistration.Dynamic jsp_dispatcher = container.addServlet("jsp_dispatcher", new DispatcherServlet(jspContext));
jsp_dispatcher.setLoadOnStartup(1);
jsp_dispatcher.addMapping("*.jsp");
// Create the dispatcher servlet's Spring application context
AnnotationConfigWebApplicationContext jsonContext = new AnnotationConfigWebApplicationContext();
jsonContext.register(JsonDispatcherConfig.class);
// Register and map the dispatcher servlet
ServletRegistration.Dynamic json_dispatcher = container.addServlet("json_dispatcher", new DispatcherServlet(jsonContext));
json_dispatcher.setLoadOnStartup(2);
json_dispatcher.addMapping("*.json");
// Create the dispatcher servlet's Spring application context
AnnotationConfigWebApplicationContext xmlContext = new AnnotationConfigWebApplicationContext();
xmlContext.register(XmlDispatcherConfig.class);
// Register and map the dispatcher servlet
ServletRegistration.Dynamic xml_dispatcher = container.addServlet("xml_dispatcher", new DispatcherServlet(jspContext));
xml_dispatcher.setLoadOnStartup(3);
xml_dispatcher.addMapping("*.xml");
}
}
My jspDispatcherConfig.java is this:
#Configuration
#Import(WebAppConfig.class)
public class JspDispatcherConfig {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/view/jsp/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
In my folder WEB-INF, I have the following structure:
-view
--json
--jsp
---acesso
----login.jsp
---erro
----publico
----privado
---privado
----admin.jsp
----customer.jsp
--xml
Anyone can tell me what I am doing wrong here?
OK, then I solve this problem modifying the mapping string in the controllers: instead of use, by example,
#RequestMapping(value="login")
I use this:
#RequestMapping(value="login.htm")
(or other extension, depending of type of the view - jsp, json or xml). Now it's working fine.

Resources