Link to / goes to Apache root - spring

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='/' />"

Related

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.

Displaying validation Errors in form with Spring MVC

I've searched through several tutorials and answers to this forum to try to solve my problem: I want to show the validation errors from my bean in my form using spring MVC.
No matter what I try, I can't get it to work. Im not using redirections, my binding results are directly after the model class and so on.
Here's what I have so far:
Login Class:
public class LoginUser implements Serializable {
#NotNull
#Column(name="username", unique=true)
#Size(min=5)
private String username;
#NotNull
#Size(min=5)
private String password;
Login Controller:
#Transactional
#Controller
public class LoginController {
#Autowired
UserDao dao;
#RequestMapping(value = "enter", method = RequestMethod.POST)
public String doLogin(#ModelAttribute("user") #Valid LoginUser user, BindingResult result, HttpSession session) {
if (result.hasErrors()) {
return "login/loginForm";
} else {
if (dao.authenticate(user)) {
session.setAttribute("userLoggedIn", user.getUsername());
return "forward:index";
} else {
return "redirect:login";
}
}
}
Login Form:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%# 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">
<script type="text/javascript" src="resources/js/bootstrap.js"></script>
<script type="text/javascript" src="resources/js/jquery-3.1.0.min.js"></script>
<link rel="stylesheet" href="resources/css/bootstrap.css">
<title><spring:message code="title.login" /></title>
</head>
<body>
<spring:message code="login.message.login" />
<form:form action="enter" commandName="loginForm" method="POST">
<spring:message code="username.login" />
<input type="text" name="username" id="username" /><br />
<form:errors path="username" />
<spring:message code="password.login" />
<input type="password" name="password" id="password" /><br /> <input
type="submit" value="<spring:message code='button.login'/>"><br />
<spring:message code="does.not.have.account.login" />
<spring:message code="register.link.login" />
</form:form>
</body>
</html>
Ohh, I forgot to add - I have a messages.properties configured (working fine, tested) and the messages are comming from there. Here is the line related to the form:
messages_en.Properties
NotEmpty.loginForm.username= Please fill the username field
By the way, it may be worth to note that my view is mounted trough a composite view (made of JSP includes of header, mainpage and footer) that overrides the customary viewloading in Sping-MVC.
You are using RedirectAttributes but you are not redirecting user any where. Try to use "redirect:/<register_path>" or just add Model model to method params and use model.addAtribute("someName", result);
Try below code..
<form:form action="enter" commandName="loginForm" method="POST">
commandName is loginForm so #ModelAttribute("loginForm").
#RequestMapping(value = "enter", method = RequestMethod.POST)
public String doLogin( #Valid #ModelAttribute("loginForm") LoginUser user, BindingResult result, Map<String, Object> model, HttpSession session) {
if (result.hasErrors()) {
return "login/loginForm";
} else {
if (dao.authenticate(user)) {
session.setAttribute("userLoggedIn", user.getUsername());
return "forward:index";
} else {
return "redirect:login";
}
}
}
UPDATE :
You are using NotEmpty.loginForm.username= Please fill the username field which is wrong,It should be NotNull.loginForm.username= Please fill the username field
And also
#NotNull will not validate for empty string..Request from the front end will be "" which is not null.So use #NotEmpty instead.
If you still want to use #NotNull add InitBinder in your controller as shown below
#InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
}
Then it will validate for empty string.
That is the reason you are getting size error directly and since you have not mentioned any message for that no message is displaying.

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

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.

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

How to pass variable value from jstl to controller

I have name and password in jsp/jstl
i tried to pass name and password to controller.
this is my controller class
package com.simple.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping("/welcome")
public class HelloController {
private String name;
private String password;
private String user;
#RequestMapping(method = RequestMethod.POST)
public String printWelcome(ModelMap model) {
System.out.println(user);
model.addAttribute(name);
model.addAttribute(password);
model.addAttribute("message", "Spring 3 MVC Hello World");
return "hello";
}
}
this is index.jsp with form tag and c tag libraries
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>Registration Page</title>
</head>
<body bgcolor="#999966">
<p> </p>
<form method="POST" action="welcome">
<p><font color="#800000" size="5">
UserName:</font><input type="text" name="name" size="20"></p>
<c:set var="user" value="{param.name}" scope="request">
</c:set>
<p><font color="#800000" size="5">
password:</font><input type="text" name="password" size="20"></p>
<p><input type="submit" value="Submit" name="B1"></p>
</form>
</body>
</html>
i am trying to pass the variable user( the value is taken from the name variable) from this form to controller.
<c:set var="user" value="{param.name}" scope="request">
</c:set>
can any body help me how to do this with c tags..
i have done with using commandName="registereduser" where user is the object of class RegisteredUser.
But i am trying with just passing the variable (with c tags)
I am getting null value for user in sysout
is there any way to do with c tags with the set
thank you..
In your controller:
#Controller
#RequestMapping("/welcome")
public class HelloController {
#RequestMapping(method = RequestMethod.POST)
public String printWelcome(ModelMap model, #RequestParam String name, #RequestParam String password) {
// do something with name & password
model.addAttribute(name);
model.addAttribute(password);
model.addAttribute("message", "Spring 3 MVC Hello World");
return "hello";
}
}
and in your JSP (you have to use a regular HTML form):
<form method="POST" action="welcome">
<table>
<tr>
<td>User Name :</td>
<td><input type="text" id="name" name="name"/></td>
</tr>
<tr>
<td>Password :</td>
<td><input type="password" id="password" name="password"/></td>
</tr>
</table>
<tr>
<td colspan="2"><input type="submit"></td>
</tr>
</table>
</form>
EDIT TO QUESTION (user variable added):
You need to pass user to controller with an input hidden and add another #RequestParam to controller method:
JSP:
<input type="hidden" id="user" name="user" value="${name}"/>
Controller method:
public String printWelcome(ModelMap model, #RequestParam String name,
#RequestParam String password, #RequestParam String user) {
...
I think you can't send user value to server with c tags, you need to submit data (form) to controller.

Resources