I created a simple application using Spring MVC(annotation based) and I am not able to view the results on JSP page. Below is the code which I have written:
In my AppConfig class:
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
in my controller class
#RequestMapping(value = { "/" }, method = RequestMethod.GET)
public String listNonClosedDeployments(ModelMap model) {
//DB operations to get the data
model.addAttribute("testMsg", "deployments are opened");
return "success";
}
My success JSP is:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<%# page isELIgnored="false" %>
</head>
<body>
${testMsg}
</body>
</html>
My output page is:
${testMsg}
Could you please let me know what am I missing here?
Thanks,
Venkat
it is not displaying the value because JSP's Expression Language is disabled by default. You have to enable it manually.
Add the below line to the top of your jsp page:
<%# page isELIgnored="false" %>
Related
I am trying to create a sample Spring MVC project but static file are not getting loaded.I am getting below mentioned error.
http://localhost:8080/BPMEI/static/css/bootstrap.css Failed to load resource: the server responded with a status of 404 (Not Found)
I will be grateful if someone can help me out to fix this issue.
Project Structure
Configuration Code
package com.dgsl.bpm.configuration;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.dgsl.bpm")
public class WebConfiguration extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("/");
}
}
Initializer code
package com.dgsl.bpm.configuration;
public class WebInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebConfiguration.class);
ctx.setServletContext(container);
ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
}
JSP Code
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Student Enrollment Form</title>
<link href="<c:url value='/static/css/bootstrap.css' />" rel="stylesheet"></link>
</head>
<body>
To F2:if you let it download itself instead of me downloading css files and telling Spring where they are,you must let the js files or somethings publish to the web which is not controlled by yourself.The building-owner’s purpose is how to load the static file in a Spring MVC project.I think the problem is on the code of addResourceLocations,it should be addResourceLocations ("classpath:/static/");
may be you made a wrong mapping.
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
this code should works, i tested it on my local machine.
addResourceLocations("/static/") the last slash is mandatory
in sping-core-4.2.5-release.jar StringUtils.java has the following code
public static String applyRelativePath(String path, String relativePath) {
int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);
if (separatorIndex != -1) {
String newPath = path.substring(0, separatorIndex);
if (!relativePath.startsWith(FOLDER_SEPARATOR)) {
newPath += FOLDER_SEPARATOR;
}
return newPath + relativePath;
}
else {
return relativePath;
}
}
if not end with a slash, this method will return relativePath
FYI, when i view your attached picture, i found "bootstrap.min.css" in your project. don't forget to use right file name. i wish my suggestion can help you
change addResourceHandlers like
#Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("/");
}
and also change css file name 'bootstrap.min.css'
Change your addResourceHandlers definition like below and try:-
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}
Please use the context path in your url:
<c:url value='${pageContext.request.contextPath}/static/css/bootstrap.css' />
This will give you the url value:
BPMEI/static/css/bootstrap.css
Let me know if that works.
Why JSP don't convert into HTML? so, I don't know what to show you
#Bean
public UrlBasedViewResolver urlBasedViewResolver(){
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/WEB-INF/views/**").addResourceLocations("/WEB-INF/views/");
}
One of my JSPs...
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Edit word</title>
</head>
<body>
<form action="edit" method="post">
<input name="id" type="hidden" value="${id}">
<input type="submit">
</form>
</body>
</html>
...
#RequestMapping(value = "/words/edit",method = RequestMethod.GET)
public String editWord(Model model, #RequestParam(required = false) String userID){
model.addAttribute("words",wordService.getAll());
return "/words/edit";
}
Displays as just opened JSP in browser:
I believe that using a UrlBasedViewResolver will only redirect to the file but a JSP need to be parse/compile.
The doc of Spring tell you that there is InternalResourceViewResolver and InternalResourceView that internally forward the jsp file. This will parse the file as you need.
For view technologies such as JSPs that are processed through the
Servlet or JSP engine, this resolution is usually handled through the
combination of InternalResourceViewResolver and InternalResourceView,
which issues an internal forward or include via the Servlet API’s
RequestDispatcher.forward(..) method or RequestDispatcher.include()
method.
Source :
http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/mvc.html#mvc-redirecting
Please return "words/edit" instead of "/words/edit". You have already set resolver.setPrefix("/WEB-INF/views/"); returning ""/words/edit" results in "//words/edit" .
I am trying to make my first web project using Spring MVC.
I have problem when i try to show variables that has been put into my model.
But on my page see my test parameter, but my table is empty.
Please, tell me, what i missed.
Im using tiles controller, so here is my tile of home.jsp where i want to show my list:
<div id="indexLeftColumn">
<div id="welcomeText">
<p>[ cool picture ]</p>
</div>
</div>
<div id="indexRightColumn">
<div id="deviceList">
Table with list of devices</br>
${blah}
<table class="table" border="1">
<thead>
<tr>
<th>Device ID</th>
</tr>
</thead>
<tbody>
<c:forEach items="${hubsIDList}" var="hub" >
<tr>
<td>${hub}</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
Here is part of my controller which adds values and returns my home.jsp
I added new parameter "blah" just to test, that parameters not disappear elsewhere
#RequestMapping(value = "/home", method = RequestMethod.GET)
public String home(Model model) {
log.info("Loading homepage");
UserDetailsImpl userDetails = (UserDetailsImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
ArrayList<String> hubsID =(ArrayList<String>) userDetails.getParameter("hubsID"); //checked - it's not empty and truly Array list of Strings
model.addAttribute("hubsIDList",hubsID);
model.addAttribute("blah","Test if parameters still here"); //added for test that my parameters aren't dissapear
return "home";
}
And here is my includes
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="spring_form" %>
<%# taglib uri="http://www.springframework.org/security/tags" prefix="sec" %>
UPD
Tried to use controller metod as below, but still no result - test parameter is visible on page, but table is empty
#RequestMapping(value = "/home", method = RequestMethod.GET)
public ModelAndView home(Model model) {
HashMap<String,Object> modelParams = (HashMap)model.asMap();
log.info("Loading homepage");
UserDetailsImpl userDetails = (UserDetailsImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
ArrayList<String> hubsID =(ArrayList<String>) userDetails.getParameter("hubsID");
modelParams.put("hubsIDList",hubsID);
modelParams.put("blah","Test if parameters still here");
return new ModelAndView("home",modelParams);
}
Problem is somewhere in my tiles controller. Somehow my taglibs was not connected to my home.jsp tile so my c: tags was unusable. If i use taglib directly in my jsp - all is works.
Hope this will help someone with same problem.
Thanx #Koitoer for helping me in my tries.
I use Spring MVC 3 in my project.
This is my AddressController :
#Controller
public class AddressController {
private static Logger logger = Logger.getLogger(AddressController.class);
#RequestMapping(value="/address",method=RequestMethod.GET)
public ModelAndView init(
#RequestParam(value="language",required=false,defaultValue="fr") String language){
Locale locale = new Locale(language);
logger.info("here");
String[] isoCountries = locale.getISOCountries();
Map<String,String> treeMap = new TreeMap<String,String>();
for(String isoCountry : isoCountries){
Locale countryLoc = new Locale(language, isoCountry);
String name = countryLoc.getDisplayCountry(locale);
if(!"".equals(name)){
treeMap.put(name,name);
}
}
Map<String,String> tree = new TreeMap<String,String>(treeMap);
ModelAndView modelAndView = new ModelAndView("address");
modelAndView.addObject("address",new Address());
modelAndView.addObject("countriesList", tree);
return modelAndView;
}
}
The first time, when I executed /address, it's going well to my controller and it returns my address.jsp by executing the javascript in this last one. But when I execute /address?language=fr or /address?language=en, the javascript code of my address.jsp is not executed.
This is a part of my address.jsp :
<%#page import="org.springframework.context.i18n.LocaleContextHolder"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="forms" uri="http://www.springframework.org/tags/form" %>
<%#page import="com.application.myGoogleAppEngine.Internationale"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# page import="java.util.Locale" %>
<%# page import="java.util.List" %>
<%# page import="java.util.ArrayList" %>
<%# page import="java.util.Collections" %>
<html>
<head>
<jsp:include page="ressources.jsp"></jsp:include>
<link rel="stylesheet" type="text/css" href="stylesheets/320x480/portrait/address.css" />
<%! Internationale internationale = Internationale.getInstance(); %>
<script>
$(document).ready(function(){
//checkParams();
alert("here");
var unit = "em";
alert("here2");
$("#backButton").attr("href","/index");
$('#validationBtn').click(function(){
var streetName = $('#streetName').val();
var streetNumber = $('#streetNumber').val();
var zipCode = $('#zipCode').val();
var city = $('#city').val();
var country = $('#country').val();
var ref = "MyServlet?streetName="+streetName+"&streetNumber="+streetNumber+"&zipCode="+zipCode+"&city="+city+"&country="+country;
$(this).attr("href",ref);
});
});
//rest of the script
</script>
<body>
<a id="backButton" data-role="button" data-icon="arrow-l"
data-ajax="false">
<spring:message code="backButton"/>
</a></div>
//rest of the code
</body>
In web MVC spring serves as server side technology. Javascript is client (browser) side technology, thus Spring "cannot" execute javascript.
I'm using Spring MVC to pass a ArrayList object from my Controller to JSP and I want to iterate it over there using JSTL (forEach), but it is always crashing Java server after 10~20 seconds loading the page. It's not throwing any exception.
Trying to use "c:out" to print the String representing the array works fine. Same to not empty validation. It always crashes when program reaches the forEach.
SIMPLIFIED EXAMPLE BELOW
Controller method
#RequestMapping(value = "/main", method = {RequestMethod.POST}, params = "create")
public ModelAndView createBranch (Branch branch) throws FxtrmServiceException, JsonGenerationException, JsonMappingException, IOException{
ModelAndView branchMV = new ModelAndView("branch");
ArrayList<String> array1 = new ArrayList<String>();
array1.add("test1");
array1.add("test2");
branchMV.addObject("alertMap1", array1);
populateAutoCompletes(branchMV);
return branchMV;
}
JSP:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
(...)
<c:if test="${not empty alertMap1}">
<c:forEach items="${alertMap1}" var="entry1">
<c:out value="${entry1}"/><br>
</c:forEach>
</c:if>