#requestmapping and ModelAndView - spring

Hi help me please with Spring RequestMapping. I have page like this:
<form action="/add_photo" enctype="multipart/form-data" method="POST">
Photo: <input type="file" name="photo">
<input type="submit" />
</form>
and controller like this:
#Controller
#RequestMapping("/")
public class MyController {
private Map<Long, byte[]> photos = new HashMap<>();
#RequestMapping("/")
public String onIndex() {
return "index";
}
#RequestMapping(value = "/add_photo", method = RequestMethod.POST)
public ModelAndView onAddPhoto(#RequestParam MultipartFile photo) {
if (photo.isEmpty()) {
throw new PhotoErrorException();
}
try {
long id = System.currentTimeMillis();
photos.put(id, photo.getBytes());
ModelAndView model = new ModelAndView();
model.addObject("photo_id", id);
model.setViewName("result");
return model;
} catch (IOException e) {
throw new PhotoErrorException();
}
}
}
method "onIndex" is working but onAddPhoto seems not and when I click button whith URL "/add_photo" it gives me 404 instead page "result"

Use pageContext in your jsp page as:
<form action="${pageContext.request.contextPath}/add_photo" enctype="multipart/form-data" method="POST">
Photo: <input type="file" name="photo">
<input type="submit" />
</form>
For more details: Check this

Related

Thymeleaf input type="date" can not display and update

I can't find the right way to display the "birthday" field from datbase!
Even when i try to submit the new value to db, it doesn't work. What i'm doing wrong?
Here is my code:
Controller
#RequestMapping(value = {"/settings"}, method = RequestMethod.GET)
public ModelAndView settings() {
ModelAndView model = new ModelAndView();
model.addObject("user", user);
model.addObject("countries", getListOfCountries());
model.setViewName("user/settings");
return model;
}
#RequestMapping(value = {"/settings"}, method = RequestMethod.POST)
public ModelAndView updateUserGeneralSettings(#ModelAttribute User user) {
ModelAndView model = new ModelAndView();
userService.update(user);
model.addObject("user", user);
model.addObject("countries", getListOfCountries());
model.setViewName("user/settings");
return model;
}
HTML
<form method="POST" th:action="#{/settings}" th:object="${user}">
<div>
</div>
...
...
<div class="costum-field">
<label for="dateOfBirth" th:text="#{field.dateOfBirth}"></label>
<input type="date" id="dateOfBirth" class="form-control" th:field="*{dateOfBirth}"/>
</div>
...
...
<div>
</div>
</form
View in browser
So, as you can see all fields are working properly. Please suggest what is my mistake.

Post method in spring controller is not working

I have developed a form in jsp and in the form if user clicks submit button then the controller should capture the parameters but unfortunately it is not working.
/*<form action="http://localhost:8080/school" method="POST">*/
<form action="/school" method="POST">
School name: <input type="text" id="school" name="school" />
<input type="hidden" value="${firstName}" name = "firstName"/>
<input type="hidden" value="${lastName}" name = "lastName"/>
<input type="submit" value="Submit" />
</form>
The controller function is like this:
#RequestMapping(value = "/school", method = RequestMethod.POST)
public void setSchool(HttpServletRequest request,HttpServletResponse response){
String firstName= request.getParameter("firstName");
String lastName= request.getParameter("lastName");
String school= request.getParameter("school");
String status = userController.setSchool(firstName, lastName, school);
try {
if(!status.equals("SUCCESS")) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, status);
}
response.sendRedirect("http://localhost:8080/getInsideSchool?school="+school+"&firstName="+firstName+"&lastName="+lastName);
} catch (IOException e) {
e.printStackTrace();
}
}
When i click on submit button in the form i cannot reach the controller function. How do i map url or fix this issue?
Thank you
<form action="/school" method="POST">
First create a POJO
class User {
private String school;
private String firstName;
private String lastName;
// getter setter constructor
}
Then write the controller method as following
#RequestMapping(value = "/school", method = RequestMethod.POST)
public String home(#ModelAttribute User user) {
System.out.println(user.toString());
return "redirect:/home";
}

Spring form binding return null with many-2-one relationship

Here is the problem, when I try to submit form, user entity returns null.
Form is
<form:form class="g-form" modelAttribute="objView" id="userAssignmentForm">
<form:hidden path="id" value="${objView.id}"/>
${objView.user.id}
<div class="g-form-group required">
<label for="user">User</label>
<form:hidden id="user" path="user" value="${objView.user}"/>
<input type="text" value="${objView.user.userName}" readonly="true"/>
<input type="button" class="import-input" onclick="gImport.showImportUserForm()"/>
</div>
Controller is
#RequestMapping(value = "/create", method = RequestMethod.POST)
public #ResponseBody
String create(
#ModelAttribute("objView") UserAssignmentView objView, BindingResult result,
SessionStatus status,
HttpServletRequest request) throws UnsupportedEncodingException {
UserAssignment obj = new UserAssignment();
obj.setUser(objView.getUser());
userAssignmentService.create(obj);
return "ok";
}
Model is below contains a view entity. What am I missing?
public class UserAssignmentView extends UserAssignment {
public UserAssignmentView() {
}
public UserAssignmentView(UserAssignment obj) {
setId(obj.getId());
setStatus(obj.getStatus());
setUser(obj.getUser());
}
}
And this is form view part of controller
#RequestMapping(value = "/form", method = RequestMethod.POST)
public ModelAndView form(HttpServletRequest request) {
UserAssignment obj = new UserAssignment();
Account account = AccountRegistry.getByHttpSession(request.getSession());
ModelAndView modelAndView = new ModelAndView("forms/userAssignmentForm");
modelAndView.addObject("objView", UserAssignmentWrapper.wrap(obj));
return modelAndView;
}
I could not solve since 3 days, how can I set user to userassignment?

Neither BindingResult nor plain target object for bean name 'loginuser' available as request attribute

#Controller
#RequestMapping("Page/Login.do")
public class HomeController
{
#RequestMapping(method = RequestMethod.GET)
protected String showLoginPage(HttpServletRequest req,BindingResult result) throws Exception
{
loginuser lu=new loginuser();
lu.setLoginn("Amit");
System.out.println(lu.getLoginn());
return "Login";
}
}
Above code is ##HomeController.java##
loginuser.java
package Com.Site.Name.Order;
public class loginuser
{
private String Loginn;
public String getLoginn()
{
System.out.println("hi i m in login get");
return Loginn;
}
public void setLoginn(String loginn)
{
System.out.println("I m in Loin set");
Loginn = loginn;
}
}
My JSP PAGE IS
Login.jsp
<form:form action="Login.do" method="post" commandName="loginuser">
<div id="Getin">
<img alt="" src="Image/loginttt.png">
</div>
<div id="login">
</div>
<form:input path="Loginn"/>
<input type="submit" value="LOGIN"/>
</form:form>
You are trying to use a Model attribute (commandName) but there is no such attribute added to the model or request attributes. You need to add it. Also, the BindingResult in your handler makes no sense. Remove it.
#RequestMapping(method = RequestMethod.GET)
protected String showLoginPage(HttpServletRequest req, Model model) throws Exception
{
loginuser lu=new loginuser();
lu.setLoginn("Amit");
System.out.println(lu.getLoginn());
model.addAttribute("loginuser", lu);
return "Login";
}
The Model attributes are added to the request attributes and are therefore available in the jsp.

Spring MVC Form Validation - The request sent by the client was syntactically incorrect

I am trying to add form validations to a working application. I started by adding a NotNull check to Login Form. I am using Hibernate impl of Bean Validation api.
Here's the code I have written
#Controller
#RequestMapping(value="/login")
#Scope("request")
public class LoginController {
#Autowired
private CommonService commonService;
#Autowired
private SiteUser siteUser;
#InitBinder
private void dateBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
binder.registerCustomEditor(Date.class, editor);
}
#ModelAttribute
protected ModelMap setupForm(ModelMap modelMap) {
modelMap.addAttribute("siteUser", siteUser);
return modelMap;
}
#RequestMapping(value="/form", method = RequestMethod.GET)
public ModelAndView form(ModelMap map){
if (siteUser.getId() == null){
map.addAttribute("command",new SiteUser());
return new ModelAndView("login-form",map);
}else {
return new ModelAndView("redirect:/my-dashboard/"+siteUser.getId());
}
}
#RequestMapping(value="/submit", method=RequestMethod.POST)
public ModelAndView submit(#Valid SiteUser user, ModelMap map, BindingResult result){
if (result.hasErrors()) {
map.addAttribute("command", user);
System.out.println("Login Error block");
return new ModelAndView("login/form",map);
}
else {
User loggedInUser = commonService.login(user.getEmail(), user.getPassword());
if (loggedInUser != null) {
siteUser.setId(loggedInUser.getId());
siteUser.setName(loggedInUser.getName());
System.out.println("site user attr set");
}
return new ModelAndView("redirect:/my-dashboard/"+loggedInUser.getId());
}
}
}
The Model is
#Component
#Scope("session")
public class SiteUser {
private Integer id = null;
#NotNull
private String name = null;
private String email = null;
private String password = null;
private List<String> displayPrivList = null;
private List<String> functionPrivList = null;
// And the getters and setters
}
The JSP is
<c:url var="loginSubmitUrl" value="/login/submit"/>
<form:form method="POST" action="${loginSubmitUrl}">
<form:errors path="*" />
<div class="row">
<div class="span4">
</div>
<div class="span4">
<h3>Please Login</h3>
<label><span style="color:red">*</span>Email</Label><form:input path="email" type="text" class="input-medium" />
<label><span style="color:red">*</span>Password</Label><form:input path="password" type="password" class="input-medium" />
<br/>
<button type="submit" class="btn btn-primary">Login</button>
<button type="button" class="btn">Cancel</button>
</div>
</div>
</form:form>
I have added messages.properties and the annotation driven bean def in the context xml.
Other answers on the subject talk about form fields not getting posted. In my case, that's the expected behavior - that if I submit a blank form, I should get an error.
Please advise what am I missing?
I think this question had the same issue as yours
Syntactically incorrect request sent upon submitting form with invalid data in Spring MVC (which uses hibernate Validator)
which just points out
You have to modify the order of your arguments. Put the BindingResult result parameter always directly after the parameter with the #Value annotation
You need this: <form:errors path="email" cssClass="errors" />
Use the tag form:errors for each input with the same "path" name.
It is also possible to list all the error at the same time if you don't put a path.
Here, check an full example with sample code that you can download to learn how to do:
http://www.mkyong.com/spring-mvc/spring-3-mvc-and-jsr303-valid-example/
Can you try changing the <form:form> by including the commandName to it like this
<form:form method="POST" action="${loginSubmitUrl}" commandName="user">

Resources