I am working on spring samples.I have a controller class named UserController2 as follows
#Controller
public class UserController2 extends MultiActionController {
private UserDAO userDAO;
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
#RequestMapping(params = "add", method = RequestMethod.POST)
public ModelAndView add(HttpServletRequest request,
HttpServletResponse response, User user) throws Exception {
userDAO.saveUser(user);
return new ModelAndView("redirect:User.htm");
}
public ModelAndView list(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelMap modelMap = new ModelMap();
modelMap.addAttribute("userList", userDAO.listUser());
modelMap.addAttribute("User", new User());
return new ModelAndView("userForm", modelMap);
}
}
and i have a jsp page called userForm.jsp
<form:form method="POST" action="add.htm" commandName="User" modelAttribute="User">
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td><form:label path="id">id</form:label></td>
<td><form:input path="id" /></td>
</tr>
<tr>
<td><form:label path="password">Name</form:label></td>
<td><form:input path="password" /></td>
</tr>
<tr>
<td><form:label path="gender">Name</form:label></td>
<td><form:input path="gender" /></td>
</tr>
<tr>
<td><form:label path="gender">Name</form:label></td>
<td><form:input path="gender" /></td>
</tr>
<tr>
<td><form:label path="country">Name</form:label></td>
<td><form:input path="country" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form:form>
what actually does the below codes returns
return new ModelAndView("userForm", modelMap);
and
return new ModelAndView("redirect:User.htm");
I am getting the following error
java.lang.IllegalStateException: Neither BindingResult nor plain target object for
bean name 'User' available as request attribute
I searched but i cannot find a proper explanation for modelandview..
When using the modelAttribute make user that:1. Your method parameter user is annotated with #ModelAttribute("user")2. A method parameter of type BindingResult is declared.
Also, the annotation parameter value is case sensitive, and should exactly match the value of the modelAttribute you declared in userForm.jsp.
Related
I tried all the solutions but I keep getting this error. Moreover if i don't use form:form in jsp file and use a simple HTML, I get the desired output.
Controller Class
#Controller
public class controller_class {
/*
* #RequestMapping(path = "/index", method = RequestMethod.GET) public
* ModelAndView mar() { return new ModelAndView("index","command",new marks());
* }
*/
#RequestMapping("/index")
public ModelAndView showComments() {
return new ModelAndView("marks","command",new marks());
}
#RequestMapping(value = "/addMarks", method = RequestMethod.POST)
public ModelAndView stud(#ModelAttribute("marks") marks m) {
ModelAndView mv = new ModelAndView("result");
int k = m.calculate();
mv.addObject("tot_marks", k);
return mv;
}
}
index.jsp
<form:form method = "POST" modelAttribute="marks" action = "/springmvc_qa3/addMarks">
<table>
<tr>
<td><form:label path = "sci_marks">Name</form:label></td>
<td><form:input path = "sci_marks" /></td>
</tr>
<tr>
<td><form:label path = "maths_marks">Age</form:label></td>
<td><form:input path = "maths_marks" /></td>
</tr>
<tr>
<td><form:label path = "eng_marks">id</form:label></td>
<td><form:input path = "eng_marks" /></td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
Correct Output if I use this instead
<form method="POST" action="/springmvc_qa3/addMarks" >
<table>
<tr>
<td><label >Science Marks</label></td>
<td><input type="text" name="sci_marks" /></td>
</tr>
<tr>
<td><label >Mathematics Marks</label></td>
<td><input type="text" name="maths_marks" /></td>
</tr>
<tr>
<td><label >English Marks</label></td>
<td><input type="text" name="eng_marks" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit" />
</td>
</tr>
</table>
</form>
What is the reason that I can't get the right output using the first method?
add the following to your controller class:
#ModelAttribute("marks")
public Marks nameOfMethodDoesntMatter(){
return new Marks();
}
make sure your Marks class has getters, setters and default constructor.
consider calling your class MarksDTO or something similar to convey its meaning better (DTO = data transfer object).
i have following scenario :
#ModelAttribute("persons")
public void addAttributes(Model model) {
Person person = new Person()
;
person.setAge(26);
person.setFirstName("mars");
model.addAttribute("persons", person);
}
#RequestMapping(value="/process-person")
public ModelAndView processPerson(#ModelAttribute Person person,#ModelAttribute ("persons")Person persons,ModelAndView modelAndView ) {
//
//ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("person-result-page");
modelAndView.getModel().remove("personObj");
modelAndView.addObject("pers", person);
----> modelAndView.addObject("pers2", persons);// persons holds the myname1 provided in input box
modelAndView.addObject("personObj", person);
return modelAndView;
}
As shown in the --> i want this variable -persons to hold the value obtained from addAttributes() method but it is taking the same values that i input from the jsp page :
<form:form method="POST" commandName="person-entity" action="process-person.html">
<table>
<tr>
<td><form:label path="firstName">Name:</form:label></td>
<td><form:input path="firstName" /></td>
</tr>
<tr>
<td><form:label path="age">Age:</form:label></td>
<td><form:input path="age" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
<td></td>
<td></td>
</tr>
</table>
</form:form>
<br/>
i saw few similar questions but none of them resolved this problem . Here i want values from addAttribute method to placed inside "persons" object, but it is taking the same value as that of "person" being provided from the form.jsp.
please help me out
i am trying to make simple spring mvc application, using jdbctemplate,but when i try to open registration page i got this error- java.lang.IllegalArgumentException: Attribute 'items' must be an array, a Collection or a Map.
last time i used this thing in another applicaton, it worked fine,but this time it is not working :(
here is my controller code and register.jsp
#RequestMapping("/register")
public ModelAndView registerEmployee(#ModelAttribute Employee employee) {
List<String> cityList = new ArrayList<String>();
cityList.add("kashipur");
cityList.add("moradabad");
cityList.add("delhi");
cityList.add("noida");
List<String> genderList = new ArrayList<String>();
genderList.add("male");
genderList.add("female");
Map<String,List<String>> map = new HashMap<String,List<String>>();
map.put("cityList",cityList);
map.put("genderList",genderList);
return new ModelAndView("register","map",map);
}
register.jsp is
<div>
<form:form method="post" action="/insert" modelAttribute="employee">
<table>
<tr>
<td>Name :</td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Gender :</td>
<td><form:radiobuttons path="gender" items="${map.genderList}" /></td>
</tr>
<tr>
<td>City :</td>
<td><form:select path="city" items="${map.cityList}" /></td>
<tr>
<tr>
<td>Email :</td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td>Phone :</td>
<td><form:input path="phone" /></td>
</tr>
<tr>
<td><input type="submit" value="Save" /></td>
</tr>
<tr>
<td colspan="2"><a href="getList">Click Here to See User
List</a></td>
</tr>
</table>
</form:form>
</div>
Try to change this List<String> cityList
to this ArrayList<String> cityList
same here
Map<String,List<String>> map = new HashMap<String,List<String>>();
Also try to access map element like this map['cityList']
You don't need to qualify with ${map.
Simply write
return new ModelAndView("register", map);
and in the JSP:
<td><form:radiobuttons path="gender" items="${genderList}" /></td>
and
<td><form:select path="city" items="${cityList}" /></td>
I am using Spring Security 4.0.2.RELEASE with Spring 4.2.0.RELEASE.
I am unable to create a logout link (I maen what must be the value of the href attribute).
Consider :
Configuring DelegatingFilterProxy in Java with WebApplicationInitializer:
public class SecurityWebInitializer
extends AbstractSecurityWebApplicationInitializer {
}
Simple configuration class to enable web security for Spring MVC
#Configuration
#EnableWebSecurity
public class SecurityConfig
extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin().and()
.authorizeRequests()
.antMatchers("/spitter/").authenticated()
.antMatchers(HttpMethod.GET, "/spitter/register").authenticated().and()
.logout().deleteCookies("remove")
.invalidateHttpSession(true).logoutUrl("/logout")
.logoutSuccessUrl("/");
}
#Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication().withUser("user").password("password")
.roles("USER").and().withUser("admin").password("password")
.roles("USER", "ADMIN");
}
}
Controller:
#Controller
#RequestMapping(value = "/spitter")
public class SpittrController {
private SpittleRepository spittleRepository;
#Autowired
public SpittrController(SpittleRepository spittleRepository) {
this.spittleRepository = spittleRepository;
}
#RequestMapping(value = "/register", method = RequestMethod.GET)
public String showRegistrationForm() {
return "registerForm";
}
#RequestMapping(value = "/register", method = RequestMethod.POST)
public String processingRegistration(#Valid Spitter spitter, Errors errors) {
if (errors.hasErrors()) {
return "registerForm";
}
spittleRepository.save(spitter);
return "redirect:/spitter/" + spitter.getUserName();
}
#RequestMapping(value = "/{username}", method = RequestMethod.GET)
public String showSpitterProfile(#PathVariable("username") String username,
Model model) {
Spitter spitter = spittleRepository.findByUsername(username);
if(spitter != null){
model.addAttribute(spitter);
}
return "profile";
}
}
registerForm.jsp:
<form method="post">
<table>
<tr>
<td>First Name:</td>
<td><input type="text" name="firstName" /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" name="lastName" /></td>
</tr>
<tr>
<td>User Name:</td>
<td><input type="text" name="userName" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td><input type="submit" value="Register" /></td>
</tr>
</table>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}">
</form>
After submission of registerForm.jsp, the profile.jsp is shown to the user:
profile.jsp:
<body>
<h1>Hello world!</h1>
<p>The time on the server is ${serverTime}.</p>
<h1>Your Profile</h1>
<h1>Logout</h1>
<table>
<tr>
<td>First Name:</td>
<td><c:out value="${spitter.firstName}" /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><c:out value="${spitter.lastName}" /></td>
</tr>
<tr>
<td>User Name:</td>
<td><c:out value="${spitter.userName}" /></td>
</tr>
</table>
</body>
When I hit
http://localhost:8080/web/spitter/register
I am redirected to the login page. After login and submitting the form, the profile.jsp is shown in which I have included a Logout link. On clicking that, HTTP 404 comes up.
I have gone through Spring Security docs, but they have taken thymeleaf into consideration. My is a simple JSP page.
Furthermore, I have also considered taking this into account,
By default POST request is required to the logout url. To perform
logout on GET request you need:
http
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
1:
http://docs.spring.io/spring-security/site/docs/3.2.x/guides/hellomvc.html
Any suggestions?
Update the your code in profile.jsp as
<h1>logout</h1>
<c:url var="logoutUrl" value="/logout" />
<form action="${logoutUrl}" method="post" id="logoutForm">
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
</form>
I'm learning Spring MVC with the tutorial of the site here
My question is basically in the code fragment bellow.
#RequestMapping(value = "/addContact", method = RequestMethod.POST)
public String addContact(#ModelAttribute("contact")
Contact contact, BindingResult result) {
System.out.println("First Name:" + contact.getFirstname() +
"Last Name:" + contact.getLastname());
return "redirect:contacts.html";
}
What should the value of #ModelAttribute be when just handling a POST request from a form submit?
Or in other words, what exactly does the "contact" value refers to in this situation?
The posted form is defined as follows:
<form:form method="post" action="addContact.html">
<table>
<tr>
<td><form:label path="firstname">First Name</form:label></td>
<td><form:input path="firstname" /></td>
</tr>
<tr>
<td><form:label path="lastname">Last Name</form:label></td>
<td><form:input path="lastname" /></td>
</tr>
<tr>
<td><form:label path="lastname">Email</form:label></td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td><form:label path="lastname">Telephone</form:label></td>
<td><form:input path="telephone" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Add Contact"/>
</td>
</tr>
</table>
</form:form>