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>
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 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
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) {
...
}
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 have a demo web application that creates users. When I try to insert data in other languages (like french) the characters are not encoded correctly. The code on the controller is:
#SuppressWarnings("unchecked")
#RequestMapping(value = "/user/create.htm", params={"id"}, method = RequestMethod.GET)
public String edit(#RequestParam("id") Long id, ModelMap model) {
System.out.println("id is " + id);
User user = userService.get(id);
model.put("user", user);
return "user/create";
}
#RequestMapping(value = "/user/create.htm", method = RequestMethod.POST)
public String save(#ModelAttribute("user") User user, BindingResult result) {
System.out.println(user.getFirstName());
System.out.println(user.getLastName());
validator.validate(user, result);
if(result.hasErrors()) {
return "user/create";
}
userService.save(user);
return "redirect:list.htm";
}
my web.xml is:
...
<filter>
<filter-name>encoding-filter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding-filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
...
and the page is:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<!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=UTF-8">
...
<form:form method="post" commandName="user">
...
<form:input path="firstName" cssErrorClass="form-error-field"/>
...
when I enter some french characters in the first name then the output from the system.out.println is ????+????? or something similar.
I saw other people fixing this with the CharacterEncodingFilter but this doesn't seem to work.
Thanks a lot.
Edited the filter value.
Try making CharacterEncodingFilter the first filter in web.xml.
I realize this question is a little old, but I just ran into the same problem, and moving CharacterEncodingFilter fixed it for me.
If this still does not work and you're using Tomcat as your application server try to set the following option on every <Connector> element in the server.xml:
<Connector URIEncoding="UTF-8" ...>
...
</Connector>
This did the trick for me. There might be similar options for other application servers, so you might want to check the server documentation.
Perhaps I'm missing something, but if the page-encoding in your JSP is "UTF-8", shouldn't the encoding in your CharacterEncodingFilter be UTF-8 rather than ISO-8859-7?
You need to add accept-charset="UTF-8" to your form.
Output of System.out.println() depends on console encoding, so it's not a good way to debug encoding problems.
To check that your values are decoded properly, you should show it at another page. Actually, it's already done in the case of form validation failure, so your system works fine if values in the fields remains the same after validation error.
There are two things to help:
In your setenv.sh file add JAVA_OPTS="$JAVA_OPTS -Dfile.encoding=utf-8"
In the script that starts your tomcat process, set the LANG environment: export LANG='utf-8'
This can then be tested by examining the default character set: Charset.defaultCharset().