Is it possible to use the spring tag in jsp file to get the value from property place holder?! (The project is struts 2 base and we are not using spring MVC)
Below are not working:
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<spring:eval expression="#propertyConfigurer.getProperty('foo.bar')" />
<spring:eval expression="${'foo.bar'}" />
Any comment ?!
SpringEL tags are supposed to work with Spring model on the view layer in Spring MVC. So it's doesn't work in Struts 2. However you can use Spring EL expressions in Struts controller. E.g.
#Value("#{ propertyConfigurer.getProperty('foo.bar') }")
public void setSomeProperty(String property) {
...
}
Related
I'm a beginner in spring programming. (i'm not good in english)
I have a problem that I can not get value from the controller.
My previous jsp worked fine, but I did not work with this project about a week then back to work, and i founded all jsp that I created after can not get value from the controller. But my previous jsp page worked fine.
I have seen on the same question and they said the error focus on version in web.xml but I dont have this error because the previous page jsp is still work fine.
Web.xml
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"
JSP file
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<%# page isELIgnored="false" %>
</head>
<body> <h1>${check}</h1> </body> </html>
Controller
#Controller
public class SingleController {
#RequestMapping(value="/single", method=RequestMethod.GET)
public ModelAndView single() {
ModelAndView mav = new ModelAndView();
mav.setViewName("single");
mav.addObject("check", "123");
return mav;
}
}
I tried, in a project both jasper and thymeleaf, but can not coexist, as I would like to use jsp must comment out Spring-boot-starter-thymeleaf depend on the package, so that it can run. Looking for a solution so that both jasper and thymeleaf can co exist. I got a solution on stackoverflow if some one use servlet-context.xml ( Mixing thymeleaf and jsp files in Spring Boot ), where both jasper and thymeleaf coexist. But my requirement is how to include those attributes in pom.xml if I am using spring-boot-starter-web.
I was able to run both HTML and JSP page from embedded jar build inside Spring boot. But if you like to run it independently by copying the Jar in command prompt then you need to copy the JSP page folder structure as it will not be in the jar content and you need to change the pom file little bit so that the jar can add external content to it.
STEP 1: Add Thymeleaf and JSP dependencies
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>
STEP 2: Project structure and file creation
Under source folder src/main/resources create folder templates, under that create sub-folder thymeleaf. And create a html file sample.html(say)
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Hello</title>
</head>
<body>
THYMELEAF PAGE: <p th:text="${name}"></p>
</body>
</html>
Under src/main/webapp/WEB-INF create sub-folder views. Under views create a jsp file, sample.jsp(say)
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello</title>
</head>
<body>
JSP PAGE: Hello ${name}
</body>
</html>
STEP 3: In your application.properties set thymeleaf view names and JSP configuration for internal view resolution.
#tomcat-connection settings
spring.datasource.tomcat.initialSize=20
spring.datasource.tomcat.max-active=25
#Jasper and thymeleaf configaration
spring.view.prefix= /WEB-INF/
spring.view.suffix= .jsp
spring.view.view-names= views
spring.thymeleaf.view-names= thymeleaf
#Embedded Tomcat server
server.port = 8080
#Enable Debug
debug=true
management.security.enabled=false
STEP 4: Create controller for serving Thymeleaf and JSP pages:
package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
#Controller
public class TestController {
#RequestMapping(value="/jasper", method=RequestMethod.GET)
public String newjasper(Map<String, Object> m, String name){
//System.out.print("-- INSIDE JSP CONTROLER ------");
m.put("name", name);
return "views/sample";
}
#RequestMapping(value="/thymeleaf", method=RequestMethod.GET)
public String newthymeleaf(Map<String, Object> m, String name){
//System.out.print("-- INSIDE HTML CONTROLER ------");
m.put("name", name);
return "thymeleaf/sample";
}
}
STEP 5: Some cases you may required to create a configuration class SpringConfig.class (say) for view resolution for JSP pages. But optional, I don't use it in my configuration file.
import org.springframework.web.servlet.view.JstlView;
#Configuration
public class SpringConfig {
#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;
}
}
STEP 6: Testing application for both jsp and html.
When you hit this url in your browser: http://localhost:8080/thymeleaf?name=rohit . This will open our sample.html file with parameter name in center of page and with this url: http://localhost:8080/jasper?name=rohit will open sample.jsp page with parameter name in center.
from the viewresover javadoc.
Specify a set of name patterns that will applied to determine whether
a view name returned by a controller will be resolved by this resolver
or not.
In applications configuring several view resolvers –for example, one
for Thymeleaf and another one for JSP+JSTL legacy pages–, this
property establishes when a view will be considered to be resolved by
this view resolver and when Spring should simply ask the next resolver
in the chain –according to its order– instead.
The specified view name patterns can be complete view names, but can
also use the * wildcard: "index.", "user_", "admin/*", etc.
Also note that these view name patterns are checked before applying
any prefixes or suffixes to the view name, so they should not include
these. Usually therefore, you would specify orders/* instead of
/WEB-INF/templates/orders/*.html.
Specify names of views –patterns, in fact– that cannot be handled by
this view resolver.
These patterns can be specified in the same format as those in
setViewNames(String []), but work as an exclusion list.
viewResolver.setViewNames(viewNames);
I am new to Spring MVC. I have basic Rest Controller and JSP. I want to be able to access the URL in the request mapping annotations from the JSP. I noticed that mvcUrl in Spring MVC 4.1 allows you to do that. But I run into an error when I try this:
When I open localhost/test.jsp. I see this in the browser:
org.apache.jasper.JasperException: javax.el.ELException: Problems calling function 's:mvcUrl'
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:556)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:477)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
.....
java.lang.IllegalArgumentException: Cannot lookup handler method mappings without WebApplicationContext
org.springframework.util.Assert.notNull(Assert.java:115)
org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.getRequestMappingInfoHandlerMapping(MvcUriComponentsBuilder.java:521)
org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.fromMappingName(MvcUriComponentsBuilder.java:330)
org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.fromMappingName(MvcUriComponentsBuilder.java:313)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
....
Here is some sample code that I used
#RestController
#RequestMapping("/foo")
public class FooRestController {
#RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello() {
return "hello";
}
}
JSP File - test.jsp
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags" prefix="s" %>
Link to Hello
What could be setup wrong?
When I hit localhost/foo/hello I do get back a json string "hello". Doesn't that mean the dispatcher servlet is working fine and the WebApplicationContext is actually setup properly?
The problem here is: you only defined controller handler for /foo/hello, but not for /test.jsp . Try adding a new controller:
#Controller
#RequestMapping("/")
public class GeneralController {
...
#RequestMapping(value = "/test.jsp", method = RequestMethod.GET)
public String hello() {
return "test"; // put the view name here. You won't need ".jsp" because it would be automatically added by the view resolver in the configuration below
}
}
and make sure similar code exists in your configuration, so that the system know where to look for your view
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/[Your_JSP_FOLDER]"/>
<property name="suffix" value=".jsp"/>
</bean>
This not a problem with your configuration file as you are using
#RestController annotaion in your controller which is a convenience annotation that is itself annotated with #Controller and #ResponseBody . as you may know annotating your class with #ResponseBody will return you back the json response from the method of the coltroller which is the expected behavior in this case.
If you want to get the jsp file what you should have used is
1.use #Controller instead of #RestController
2.Assuming you have configured view resolver with prefix and suffix for jsp page and return test string from the method because your jsp file name says it's name is test .
Hope this answer your question.
I don't think this is a configuration issue we have also faced similar kind of issues the only solution was to use modelandview instead of returning the view as string in the controller
I'm following a tutorial about spring and I'm supposed to set a variable in a controller in order to be printed within the jsp rendering the request. The code is as follows:
#Controller
public class HelloController {
#RequestMapping(value="/hello.htm")
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String now = (new Date()).toString();
return new ModelAndView("WEB-INF/views/hello.jsp", "now", now);
}
}
Then, the hello.jsp code is as follows:
<%# page session="true"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<body>
<p>Greetings, it is now <c:out value="${now}" /></p>
</body>
</html>
I am expected to get an html showing this:
Greetings, it is now Mon Fri Dec 06 00:39:35 CET 2013
But all I get is:
Greetings, it is now ${now}
I've checked everything twice (or even more!) but everything seems to be as the tutorial says but there must be something missing, I hope...
What's wrong with my code?
This is an E xpression L anguage issue. Your ${} is not being resolved. This can happen for a number of reasons. One, and the most likely, is that your web.xml is declaring Servlet 2.3 and under. You'll have to specify 2.4+. Now, obviously, your Servlet container must also support that higher version.
Change this - the pad a library is bad:
<!-- %# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>-->
<%# taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
I tried to run the following lines.
<%=application.getInitParameter("tagline")%>
<br />
<%=config.getInitParameter("admincontact")%>
${initParam.tagline}
<br />
${pageContext.servletConfig.initParameter("admincontact")}
And my web.xml is
<servlet>
<jsp-file>/index.jsp</jsp-file>
<init-param>
<param-name>admincontact</param-name>
<param-value>8939302763</param-value>
</init-param>
</servlet>
<context-param>
<param-name>tagline</param-name>
<param-value>Each one Plant one</param-value>
I get a exception at
${pageContext.servletConfig.initParameter("admincontact")}
and null value for
<%=config.getInitParameter("admincontact")%>.
Regards,
John
There is an FAQ on JavaRanch about this.
It states the following;
How to access servlet init parameters using EL?
You cannot use the following syntax to access servlet init parameters:
${pageContext.servletConfig.initParameter.name}
You cannot get Servlet init parameters using this technique. The
getInitParameter(java.lang.String name) does not fit in this case,
because it requires some arguments.
According to the JavaBean spec, the property has getter & setter
methods in the form
public type1 getXXX() -- WITH NO ARGUMENTS.
public void setXXX(type1)
Now consider the pageContext as bean Object. The
PageContext class has methods like getServletConfig(), getRequest(),
getSession() etc. You can access these like pageContext.page,
pageContext.request etc in EL.
ServletContext object has a couple of methods like getMajorVersion(),
getMinorVersion() with no args. so we can access these methods
treating it as properties to sevletContext bean as
pageContext.servletContext.majorVersion and
pageContext.servletContext.minorVersion.
If you want to access Servlet init parameters using EL, then it is
better to create a Map of the init parameters for the servlet and
place it in the request as a scoped variable -- let's say
initParameters. You would then be able to obtain any param by name
with ${requestScope.initParameters.name}.
NOTE:
We can access context init parameters with ${initParam.name}
In addition to Mr Moose's answer, I have found this solution that uses EL defining a custom tag.
It worked in my case.
Here the link
Basically you have to create a Java class like this:
package example.customTags;
import javax.servlet.jsp.JspPage;
public class MyFunctions {
public static String getJspInitParameter(JspPage page, String param){
return page.getServletConfig().getInitParameter(param);
}
}
Create a tld file like this (my filepath is WEB-INF/myTags/customTags.tld):
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>Functions</short-name>
<function>
<name>getJspInitParameter</name>
<function-class>example.customTags.MyFunctions</function-class>
<function-signature>
java.lang.String getJspInitParameter(javax.servlet.jsp.JspPage, java.lang.String)
</function-signature>
</function>
</taglib>
And use it in your JSP like this:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="my" uri="../WEB-INF/myTags/customTags.tld"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Example</title>
</head>
<body>
<c:out value="${my:getJspInitParameter(pageContext.page, 'admincontact')}"/>
</body>
</html>