I am creating sample Spring MVC application.In this application i have one form when i submit the form i perform some action.
My problem is after the form submit url is changed for example i have url as http://localhost:8080/SampleWeb/sample/user this is for my form display when i submit the form the url redirected to http://localhost:8080/sample/user-by-name
in my jsp
<form:form method="POST" action="/sample/user">
<table>
<tr>
In my controller
#Controller
#RequestMapping("/sample")
public class SampleController {
#RequestMapping(value = "/user", method = RequestMethod.GET)
return "redirect:" + "SampleWeb/sample/user-by-name";
when i change the redirect url to "/SampleWeb/sample/user-by-name"
it works in firefox but in chrome http://localhost:8080/SampleWeb/SampleWeb/sample/user-by-name it adds two times.
if i give return "redirect:" + "/sample/user-by-name"; means url will be http://localhost:8080/sample/user-by-name
I am new to the Spring mvc. Please anyone can help me
Remove the first slash from this line <form:form method="POST" action="sample/user-by-name">
Do not hard code the context path in your controller / jsp page. Mention context path in your JSP page as shown below. It worked for me.
<form:form method="POST" action="${pageContext.request.contextPath}/sample/user-by-name">
Or
<form:form method="POST" action="<%=request.getContextPath()%>/sample/user-by-name">
Try this:
<c:url var="myUrl" value="/sample/user-by-name"/>
<form:form method="POST" action="${myUrl}">
Related
I have a Spring Application and Server Side Rendering with Thymeleaf as Templating language.
A button sends a get or post request to the controller in Spring, which puts some message to the view, which is rendered into the HTML file and send back to the client. The message should be optional. Thats why the template must also be able to be called without the message.
Next i want the client browser to scroll down to the part of the page where this message is rendered into, which is normally very easy. You would just have to append the id of the element to the url like following example.
https://stackoverflow.com/#footer
In this example the browser scrolls down to the footer of the page.
Below is what i tried. Unfortunately it doesnt't work like that. Spring/Thymeleaf tries to find a index#messagebox template which can't be found. Hence a Whitelabel Error Page error is thrown/shown.
Page.html
<section>
<h2>Form to send request</h2>
<form action="showmessage" method="get">
<input type="submit" value="Click for message">
</form>
</section>
Controller.java
#GetMapping("showmessage")
public ModelAndView showMessage(){
return new ModelAndView("index#messagebox",Map.of("optionalmessage","Some message that is optioal"));
}
src/main/resources/templates/index.html
<body>
<h1>Index Page</h1>
<div id="messagebox" th:fragment="message" th:with="optionalmessage=${optionalmessage}">
<p th:if="${optionalmessage!=null}">[[${optionalmessage}]]</p>
</div>
</body>
The problem can be solved with Flashmessages and Redirects. The html basically keeps the same. If the message attribute is set, you render it.
src/main/resources/templates/index.html
<div th:if="${msg}">
<div class="message" >
<p>[[${msg}]]</p>
</div>
</div>
The most important changes had to be made in the controller. First a parameter of type RedirectAttributes is added to the Controller that handles the request.
If wanted the message is added with the RedirectAttributes.addFlashAttribute function as shown below. Finally a redirect is returned, which contains the needed tag. A second controller is also needed that handles the Get Request of the Redirect with a Model as input parameter and returns the needed Template. The #tag is simply passed throuhg to the client browser.
Controller.java
#GetMapping("showMessage")
public String postNotification(RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute("optinalMessage", "Hello I am an optional message");
return "redirect:/index#footer";
}
#GetMapping("index")
public String getIndex(Model model) {
return "index";
}
You add id in URL by using ?id=value.
And in controller #RequestMapping("/path/{id}")
to access that variable #PathVariable
I apologize in advance if this or a similar question has already been asked, but I could not find a suitable answer.
I have a simple form like this in EditUser.jsp (mapped to: .../admin/users/edit/{userId}):
<form action="/admin/users/edit/addRole/${user.userId}" method="POST">
<select name="role">
<c:forEach var="role" items="${roles}">
<option value="${role}">${role}</option>
</c:forEach>
</select>
<button type="submit" value="AddRole">Add Role</button>
</form>
And #RequestMapping like this:
#RequestMapping(value = "/admin/users/edit/addRole/${userId}", method = RequestMethod.POST)
public String addUserRole(
Model model,
#RequestParam("role") String role,
#PathVariable(value="userId") long userId)
{
...
return "redirect:/admin/users/edit/${userId}";
}
The problem is the result of the request: HTTP Status 404 - /admin/users/edit/addRole/7- "The requested resource is not available" (7 is some user id). A cannot map the POST request to the controller action. I already tried with th:action but it redirects me to the previous page .../admin/users.
Any help pointers appreciated .
I think you url is wrong. As long as you do not deploy the application in the servlets container root path, it will not work because the url is missing the applications name. So a correct url would be something like:
<form action="myAppName/admin/users/edit/addRole/${user.userId}" method="POST">
But better would been using <c:url> or <spring:url>-tag this adds the application name to the url (if the given url starts with an /)
<form action="<c:url value="/admin/users/edit/addRole/${user.userId}" />" method="POST">
for some more information have a look at this two answers:
How to use relative paths without including the context root name? (the highes ranked answer of BalusC is for an quite old jsp version (<2.0)) so take the answer with the c:url tag
How to use with an tag?
I finally found the error - $ sign in #RequestMapping annotation. A just removŠµ $ from annotation and from return "...url" and that's all.
I've a list of values to be passed from my controller to the jsp page. I've the below controller:
#RequestMapping(value="/addClient.do", method = RequestMethod.GET)
protected ModelAndView Submit(HttpServletRequest request, HttpServletResponse response) throws Exception {
MyForm = new MyForm();
MyForm.setClientList(MyService.getClientList(/*"30-JUN-15"*/));
System.out.println("Size of list : "+MyForm.getClientList().size()); //-- Displayed as 10 which is correct
ModelAndView model = new ModelAndView("feeMaintenance");
model.addObject("clientForm",MyForm);
model.addObject("selectedMenu", "MenuSelected");
model.addObject("clientsList",MyForm.getClientList());
return model;
}
And my jsp form is as below:
<body>
<form:form method="post" modelAttribute="clientForm" action="${userActionUrl}">
<tr> <td align="left">
<form:select path="clientList">
<form:option value="-" label="------Select Client ------">
<form:options items="${clientsLists}">
</form:options></form:option></form:select>
</tr> </td>
</form>
</body>
I've removed the additional unrelated code. The drop down only shows ----Select Client--- even though the controller shows the correct values of the clientList. Unable to figure out whats missing.
if MyForm.getClientList() is successfully return list of client data than
rewrite this line into jsp page.
you write key name into controller is clientsList and you write this into jsp page is clientsLists this is wrong.
I hope this is work.
try this code.
model.addObject("country", projectservice.getallCountry());
**Note:**itemLabel name is same as property name into pojo class and also itemValue name.
This may be a very basic question but I am confused. I have couple of doubts:
In spring form <form:form if method is not specified then is it GET or POST?
If a spring form has <form:form with commandName then is that GET or POST?
The second question is because I see a "form:form commandName=xyz action=abc" in the code
When I check the HTML code (view source) it translates to
"form action=abc method=POST"
Please help me with this.
HTML form without specified action is always GET. It's HTML standard.
http://www.w3.org/TR/html401/interact/forms.html#h-17.3
But when you look inside FormTag in Spring source you'll notice this code:
public class FormTag extends AbstractHtmlElementTag {
/** The default HTTP method using which form values are sent to the server: "post" */
private static final String DEFAULT_METHOD = "post";
So for spring tag <form:form action is post by default.
commandName is just name for model attribute binded with your form. It has nothing to method type. Moreover, it's equivalent to modelAttribute so you can use either.
Spring form has default method as POST. If you want to do the get, you have to write, method="get" in form:form tag.
I have the 404 error when requesting a page. I have a users page with a list of objects that the user can click on to then carry out a number of transactions, add, edit etc.
The controller for it
#RequestMapping(value="/main/user/setter/addpage/", method = RequestMethod.GET)
public String getAddPage(#RequestParam("userId") Integer userId, ModelMap model) {
Module module = new Module();
model.addAttribute("userId", userId);
model.addAttribute("module", module);
return "/main/user/setter/addpage";
}
The page I want to get
<c:url var="processUrl" value="/main/user/setter/addpage/?id=${userId}" />
<form:form modelAttribute="module" method="POST" action="${processUrl}" name="module"
enctype="multipart/form-data">
</form:form>
The page that I'm requesting it from:
<c:forEach items="${users}" var="setter" >
<c:url var="addUrl" value="/main/user/setter/addpage?userId=${setter.userId}" />
<td>
add
</td>
When I click on the add link above it goes to the 404 page. Obviously the url is going through. Any help would be great.
can you try :
#RequestMapping(value="/main/user/setter/addpage"
instead of
#RequestMapping(value="/main/user/setter/addpage/"