No mapping found for HTTP request with URI [/resources/css/styles.css] in DispatcherServlet with name 'SpringDispatcher' - spring

I am developing simple web application using Spring MVC. Could you please point me out why the resources are not rendered on the page when I am accessing it? The whole page is being rendered however.
Here my project structure
I am receiving the following warning:
No mapping found for HTTP request with URI [/resources/css/styles.css] in DispatcherServlet with name 'SpringDispatcher'
JSP page that holds the links to the resources:
includes.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<c:set var="base" value="${pageContext.request.contextPath}"/>
<link href="<c:url value="${base}/resources/css/pure/pure-min.css" />" rel="stylesheet">
<link href="<c:url value="${base}/resources/css/styles.css" />" rel="stylesheet">
<link href="<c:url value="${base}/resources/css/menu.css" />" rel="stylesheet">
<script src="${base}/resources/js/validateInput.js"></script>
JSP page that has to be rendered:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<jsp:include page="/resources/includes.jsp"/>
</head>
<body>
<div id="main-container">
<div class="site-content">
<h1 class="fueling-header">Registration</h1>
<form class="pure-form pure-form-aligned"
action="/register"
method="post"
onsubmit="return validateUserInput();">
</fieldset>
</form>
</div>
</div>
</body>
</html>
Here is my WebAppInitializer code:
public class WebAppContextInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext annotationConfigWebApplicationContext = new AnnotationConfigWebApplicationContext();
annotationConfigWebApplicationContext.register(WebContextConfiguration.class);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
"SpringDispatcher",new DispatcherServlet(annotationConfigWebApplicationContext)
);
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
ContextConfiguration class
#Configuration
#EnableWebMvc
#Import(ServiceContextConfiguration.class)
#ComponentScan("controllers")
public class WebContextConfiguration {
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}
#Bean(name = "view_resolver")
public InternalResourceViewResolver internalResourceViewResolver() {
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
internalResourceViewResolver.setPrefix("/WEB-INF/jsp/");
internalResourceViewResolver.setSuffix(".jsp");
return internalResourceViewResolver;
}
}
And my simple controller
#Controller
public class BasicController {
#RequestMapping(value = "/greeting")
public String sayBasic(Model model){
model.addAttribute("greeting", "Hello world");
return "register";
}
}

The problem was that I had the cyclic reference in another controller i.e. the get method and post were mapped to the same logical view name. My configuration was correct.
For those who will meet the same problem: remove all request mappings and add them step by step till you will see where the problem occurred.

Remove ${base} as it is adding additional / Character.

Related

how to make group of radio buttons in spring form?

i am creating a quiz application where i want to group options in a radio button list after fetching options from database. My code is below so that one option from optionList of Question object is selected seprately.
i want to list group of questions and their options in a single page options with their relative questions .if i select option of one question i should be able to select another option of another question. how do i seprate radio buttons for each questions???
#Controller
public class ApiController {
#Autowired
private QuestionRepository qr;
#Autowired
private OptionRepository or;
#Autowired
private ActivitiesCrudRepository acr;
#RequestMapping("/questions")
public String ShowQuestions(#ModelAttribute("questions") Question question) {
return "questions";
}
#RequestMapping("/save")
public String save(#ModelAttribute("questions") Question question) {
qr.save(question);
return "questions";
}
#RequestMapping("/pq")
public String playQuiz(Model m, #ModelAttribute("questions") Question qsn) {
Iterable<Question> q = qr.findAll();
System.out.println(q);
m.addAttribute("q", q);
return "play-quiz";
}
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# page isELIgnored="false"%>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form:form action="play" modelAttribute="questions">
<c:forEach var="temp" items="${q}">
${temp.qsn_Name}<br>
<c:forEach var="temp1" items="${temp.options}">
<form:radiobuttons path="options[0].name" value="${temp1.name}"
items="${????????????}" />
<br>
</c:forEach>
<br>
</c:forEach>
<input type="submit" value="submit">
</form:form>
</body>
</html>
When using using the taglib function form:radiobuttons you don't need to iterate over the options you want in the radiobutton group.
You can replace
<c:forEach var="temp1" items="${temp.options}">
<form:radiobuttons path="options[0].name" value="${temp1.name}"
items="${????????????}" />
<br>
</c:forEach>
with
<form:radiobuttons path="options[0].name" items="${temp.options}" />
Be aware of the difference between form:radiobutton which create one single button and form:radiobuttons which creates the whole group.
See f.x. https://www.tutorialspoint.com/springmvc/springmvc_radiobuttons.htm or https://mkyong.com/spring-mvc/spring-mvc-radiobutton-and-radiobuttons-example/for more examples.

Why model.addAttribute and ${} is not matching and it shows just . on web?

I just started to learn jsp and spring. I deleted formattedDate (as a default) in HomeController.java and changed to model.addAttribute("answer", "yes") and on web, it only shows . and i don't understand why.
I tried to put definition like String answer = "yes" but it didnt work.
this is HoneController.java:
#Controller
public class HomeController {
#RequestMapping("/main")
public String home(Locale locale, Model model) {
model.addAttribute("answer", "yes");
return "home";
}
}
and here is home.jsp:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page session="false" pageEncoding="UTF-8" %>
<html>
<head>
<title>Home Page</title>
</head>
<body>
<h1>
hello
</h1>
<P> Is it happening? : ${answer}. </P>
</body>
</html>
There was no error messages

Type [java.lang.String] is not valid for option items

I am trying to bind a list to drop down in JSP. Below is my controller and JSP.
Controller:
#Controller
public class WeatherServiceController {
#Value("#{'${countryList}'.split(',')}")
private List<String> countries;
#ModelAttribute("CountriesList")
private List<String> getCountries(){
System.out.println(countries.size());
return countries;
}
#RequestMapping(value = "/getweather", method=RequestMethod.GET)
public ModelAndView getWeather(){
Place p = new Place();
ModelAndView mav = new ModelAndView();
mav.addObject("place",p);
mav.setViewName("home");
return mav;
}
}
JSP:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!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>Weather Service Client - Home</title>
</head>
<body>
<h2>Welcome to Weather Service</h2>
<form:form modelAttribute="place" action="getWeather">
<table>
<tr>
<td><form:label path="country">Country:</form:label></td>
<td>
<form:select path="country" items="${CountriesList}">
</form:select>
</td>
</tr>
</table>
</form:form>
</body>
</html>
But I am getting error like "Type [java.lang.String] is not valid for option items". Country list is not coming in jsp page. Please help me what I did wrong here.
It is working now.
I have added below line in jsp page.
<%# page isELIgnored="false" %>
I thought by default "isELIgnored" is set to false, so I haven't included earlier. After including this page is binding list result.

Link to / goes to Apache root

Here is the controller :
#Controller
public class HomeController {
#Autowired
private UserDAO userDao;
#RequestMapping("/")
public ModelAndView accueil() throws Exception {
List<User> listUsers = userDao.list();
ModelAndView model = new ModelAndView("UserList");
model.addObject("userList", listUsers);
return model;
}
#RequestMapping(value = "/new", method = RequestMethod.GET)
public ModelAndView newUser() {
ModelAndView model = new ModelAndView("UserForm");
model.addObject("user", new User());
return model;
}
...
}
Inside a jsp I placed a button inside a link so that when clicked then the action "accueil" in the controller would be called :
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
...
<tr>
<td>
<input type="submit" value="Save">
</td>
<td><input type="button" value="Annuler" /></td>
</tr>
</form:form>
...
The problem is that when I click the "Annuler" button then I reach to localhost:8080 ! So how to write correctly the link target ?
If the application is not the root application, you need to prepend the context path of the application to the URLs.
Use
href="${pageContext.request.contextPath}/"
or add the JSTL core library to your JSP, and use
href="<c:url value='/' />"

Flash attributes and ResourceBundleViewResolver

I am facing an issue with the flash attributes which I have not able to retrieve it in the GET phase of POST/redirect/GET scenario. This is only happening when I use the ResourceBundleViewResolver.
view resolver
<bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basename" value="spring-views" /> </bean>
view properties
form.(class)=org.springframework.web.servlet.view.JstlView
form.url=/WEB-INF/pages/form.jsp
home.(class)=org.springframework.web.servlet.view.JstlView
home.url=/WEB-INF/pages/home.jsp
home_redirect.(class)=org.springframework.web.servlet.view.RedirectView
home_redirect.url=home
form.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>Insert title here</title>
</head>
<body>
<form action="register" method="post">
Name: <input type="text" name="name"/> <br/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
home.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<body>
<h2> ${status} </h2>
</body>
</html>
so in this page, home.jsp, the status should contain the value set as the flash attribute.
controller
#Controller
public class WebController {
#RequestMapping(value="/form", method=RequestMethod.GET)
public String showFormPage(){
return "form";
}
#RequestMapping(value="/register", method=RequestMethod.POST)
public ModelAndView login(#RequestParam("name") String name, RedirectAttributes flashMap){
System.out.println("name = " + name);
flashMap.addFlashAttribute("status", "Registered successfully");
//return new RedirectView("home"); -- with this returned its working
return new ModelAndView("home_redirect"); //-- with this returned its not working
//return "redirect:home"; // -- not working
}
#RequestMapping(value="/home")
public String showHomePage(){
return "home";
}
}
on the whole this is the observation made:
if used resource bundle view resolver
return view names as string - not working
return ModelAndView - not working
return RedirectAndView - working
if used internal view resolver
return view names as string - working
2 return modelandview - cannot be used to redirect
return RedirectAndView - working

Resources