I work with a Spring Mvc app and get HTTP Status [404] – [Not Found]. The landing page is namely index.jsp,
and called from the controller method,
#Controller
public class BitcoinWalletController {
#RequestMapping("/")
public String showBitcoinWallet() {
return "index";
}
}
In the index.jsp page, send money button is initially disabled,
<div class="buttons_box">
<button type="button" class="btn btn-default btn-lg active" <%= canSendMoney ? "" : "disabled='true'"%>
data-toggle="modal" data-target="#myModal">Send money
</button>
</div>
and only be active if the synchronization is completed and boolean canSendMoney returns true.
If the button is active, the code handles the POST operation is provided,
<%--modal contents here--%>
<div class="modal-content">
<div class="model-header">
<button type="button" class="close" data-dismiss="modal">×!</button>
<h4 class="modal-title">Send Money</h4>
</div>
<form id="send-form" class="form-horizontal" action="sendMoney.jsp" method="POST">
<div class="modal-body">
<div class="form-group">
<label for="amount" class="col-sm-2 control-label">Send</label>
<div class="col-xs-4">
<input id="amount" name="amount" class="form-control" value="0">
</div>
<div class="btc-col">
<span>BTC</span>
</div>
</div>
<div class="form-group">
<label for="address" class="col-sm-2 control-label">to</label>
<div class="col-sm-10">
<input id="address" name="address" class="form-control">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-default">Send</button>
</div>
</form>
</div>
The sendMoney.jsp code is provided below,
<body>
<%
String amount = request.getParameter("amount").trim();
String address = request.getParameter("address").trim();
WalletSendMoneyController.getSendMoneyController().send(address, amount);
// New location to be redirected
String site = new String("/");
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
%>
</body>
When I put all the required and correct infos and press the button, It should return to the original page- index.jsp. Instead, I get the error, HTTP Status [404] – [Not Found],
I currently don't have any handle for the address http://localhost:8080/sendMoney.jsp. Because, if the POST submission is correct, I would like to redirect to the "/".
I have the jsps in the WEB-INF folder in the project directory,
The jsps location provided in the dispatcher-servlet.xml file,
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsps/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
The we.xml knows where the dispatcher-servlet.xml is located,
<servlet>
<description></description>
<display-name>dispatcher</display-name>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
How to solve the issue? Thanks.
Your code showing: You are actually trying to submit form to sendMoney.jsp which is not exist(might be, cause i can't see your whole project). Though you need to submit the form to a controller with a ModelAttribute which you need to create.
The following things you have to do for POST to controller from form.
Make a class for form fields
public class Data {
private String address;
private String amount;
public Data() {
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}
Bind a new Data object in GET controller where you load the form in HTML
#RequestMapping("/")
public String showBitcoinWallet() {
model.addAttribute("data", new Data());
return "index";
}
The following form will be in your index.jsp page, Where /send is the controller's mapping where to POST the form
<form:form id="send-form" modelAttribute="data" class="form-horizontal" action="/send" method="POST">
<div class="modal-body">
<spring:bind path="amount">
<div class="form-group">
<label for="amount" class="col-sm-2 control-label">Send</label>
<div class="col-xs-4">
<form:input path="amount" id="amount" name="amount" class="form-control" value="0"></form:input>
</div>
<div class="btc-col">
<span>BTC</span>
</div>
</div>
</spring:bind>
<spring:bind path="address">
<div class="form-group">
<label for="address" class="col-sm-2 control-label">to</label>
<div class="col-sm-10">
<form:input path="address" id="address" name="address" class="form-control"></form:input>
</div>
</div>
</spring:bind>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-default">Send</button>
</div>
</form:form>
Following controller for /send POST
#RequestMapping(value = "/send", method = RequestMethod.POST)
public String sendMoney(Data data) {
//here will be your code for send money and whatever you have to do..
...send(data.getAddress(), data.getAmount());
return "redirect:/"; //here will the location where you want to redirect
}
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
Have you defined this in your spring-config.xml file ??
Related
Hello i have problem with update object, i dont know how always aftre update data i have message: Request method 'GET' not supported. But date after refresh object is update.
Controller with GET and POST method to update object
#Controller
#RequestMapping("/packet")
public class PacketController {
#GetMapping("/modify/{id}")
public String modifyPacketGet(Model model, #PathVariable Long id)
{
model.addAttribute("channels", channelService.getAllChannels());
model.addAttribute("packet", packetService.getById(id));
return "packet/modify";
}
#PostMapping("/modify")
public String modifyPacketPost(Model model, #ModelAttribute PacketDto packetDto)
{
packetService.updatePacket(packetDto);
return "redirect:/packet/modify";
}
HTML form
<form th:action="#{/packet/modify}" method="post" th:object="${packet}" enctype="multipart/form-data">
<input type="text" hidden="hidden" readonly="readonly" th:field="*{id}" />
<input type="text" hidden="hidden" readonly="readonly" th:field="*{filename}" />
<div class="form-group">
<label for="name" class="h3 text-success">Name:</label>
<input id="name" type="text" th:field="*{name}" class="form-control">
</div>
<div class="form-group">
<label for="price" class="h3 text-success">Price:</label>
<input id="price" type="text" th:field="*{price}" class="form-control">
</div>
<div class="form-group">
<label for="description" class="h3 text-success">Description:</label>
<textarea class="form-control" rows="5" th:field="*{description}" id="description"></textarea>
</div>
<div class="form-group">
<label for="image" class="h3 text-success">Image:</label>
<input id="image" type="file" th:field="*{multipartFile}" accept="image/**" class="form-control">
</div>
<div class="form-group">
<label for="channel" class="h2 text-secondary">Channels:</label>
<ul class="list-inline">
<li class="list-inline-item" th:each="c : ${channels}">
<input id="channel" type="checkbox" th:field="*{channelIds}" th:value="${c.id}">
<label th:text="${c.name}"></label>
</li>
</ul>
</div>
<button type="submit" class="btn btn-success btn-lg mr-2">Add</button>
</form>
The http request GET /packet/modify is not being handled in your controller and you are redirecting your POST method to that http request:
return "redirect:/packet/modify";
To solve this you need to do one of the following:
Change the redirect request in your POST to an endpoint that is being handled:
return "redirect:/packet/modify/" + packetDto.getPacketId();
Or, handle that GET endpoint:
#GetMapping("/modify/")
public String retrievePacket(...) { ... }
Hope this helps.
I have implemented a registration process where you can send user data to the controller via post request.
The post request works fine, however now I want to pass another value (role, Long) from the form to the controller that is not an attribute of the user model.
That part is not working.
Does anyone know why?
HTML:
<form action="add_user" method="post" class="form-horizontal" th:object="${user}">
<div class="form-group">
<div class="col-sm-offset-1 col-sm-10">
<input th:field="*{username}" class="form-control" placeholder="Person ID" type="text" name="id" id="id"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-10">
<input th:field="*{firstName}" class="form-control" placeholder="First Name" type="text" name="firstname" id="firstname"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-10">
<input th:field="*{lastName}" class="form-control" placeholder="Last Name" type="text" name="lastname" id="lastname"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-10">
<input th:field="*{password}" class="form-control" placeholder="Password" type="password" name="password" id="password"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-10">
<select th:field="${role}" class="form-control" id="role">
<option value="1">Admin</option>
<option value="2" >User</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-10">
<button type="submit" class="btn btn-success" value="Submit">Save</button>
</div>
</div>
</form>
Controller:
#RequestMapping(value = "/users", method = RequestMethod.GET)
public String showUsers(Model model)
model.addAttribute("user", new User());
model.addAttribute("role", new Long(2));
return "users";
}
And:
#RequestMapping(value = "/add_user", method = RequestMethod.POST)
public String handleNewUser(#ModelAttribute("user") User user, BindingResult bindingResult, Model model, long role) {
if (user != null) {
System.out.println(role);
userService.save(user);
}
return "redirect:/users";
}
th:field="${role}" means name of field in the model object, not its value. You probably want to write th:value="${role}" instead of this.
I am using eclipse with tomcat here is my servlet ,the problem is when I click the button called GetStared it redirects me to empty html page with the text "surved at :myproject123" . myproject123 is the name of my project in the eclipse IDE.
#WebServlet("/home")
public class homeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String htmlFile = "loginPage.html";
RequestDispatcher view = request.getRequestDispatcher(htmlFile);
view.forward(request, response);
}
}
Here is my html file : called index.html
<div class="background-wrap">
<video id="video-bg-elem"
preload="auto"
autoplay="autoplay"
loop="loop" muted="muted">
<source src="video.mp4" type="video/mp4">
Video not supported
</video>
</div>
<div class="content">
<div class="info">
<div class="vertical_align">
<h2>Spotify</h2>
<output>Music for each moment.</output>
</div>
<div class="vertical_align2">
<form action="home" method="GET">
<button type="submit"
value="Get Started"
class="animated_button">
GET STARTED
</button>
</form>
</div>
</div>
</div>
Here is loginPage.html
<div class="myCirle">
<img src="logo10.png" />
<div class="under_logo">
<p>Spotify.</p>
</div>
</div>
<form class="form-signin" action="login" method="POST">
<div class="form-input" >
<input type="text" name="Username" placeholder = "Enter username" />
</div >
<div class="form-input" >
<input type="password" name="Password" placeholder="Enter password" />
</div >
<div class="form-input">
<input type="submit" name="submit" value="Sign In" class="btn-login" /><br />
<input type="submit" name="submit" value="Sign In With Facebook" class="btn-loginFB" />
</div>
<div class="form-input">
Forgot password?
</div>
<div class="form-input">
<input type="submit" name="submit" value="Not a spotifyier yet?" class="btn-reg" />
</div>
</form>
</div>
</body >
problem seems to be with forward the request....you can try this.. request.getRequestDispatcher("/"+htmlFile); or request.getRequestDispatcher("//"+htmlFile);
it is so because getRequestDispatcher () accepts link to the resources instead of direct file name.So if your file in inside your webapp like MyApp/myFile,then
request.getRequestDispatcher("/myFile");
if it is inside WEB-INF,then..
request.getRequestDispatcher("/WEB-INF/myFile");
and so on...
I am working on application using html, thymeleaf, Spring MVC, I wanted to send table data to spring controller but in when I clicked on save button of the application, getting an error on console:
java.lang.IllegalStateException: Neither BindingResult nor plain
target object for bean name 'salesProduct[0]' available as request
attribute
at org.springframework.web.servlet.support.BindStatus.(BindStatus.java:144)
at org.thymeleaf.spring4.util.FieldUtils.getBindStatusFromParsedExpression(FieldUtils.java:396)
Browser Error:
HTTP Status 500 - Request processing failed; nested exception is
org.thymeleaf.exceptions.TemplateProcessingException: Error during
execution of processor
'org.thymeleaf.spring4.processor.attr.SpringInputGeneralFieldAttrProcessor'
(sales:290)
I have added three attributes to controller like salesBean, paymentBean and salesProductFormBean, you can see in below spring controller code that is the reason in html I have not added th:object="${...}" in the form tag.
HTML
Sales.html
<form th:action="#{/salesForm}" method="post" class="mainData"
id="form">
<div class="buttonBar" id="mainbutton">
<div>
<button class="btn" id="save" type="submit">
<img th:src="#{/resources/images/save.svg}" /> Save
</button>
<button class="btn" id="reset" onclick="clearForm()" type="reset">
<img th:src="#{/resources/images/reset.svg}" /> Reset
</button>
<button type="button" class="btn" id="clientNew">
<img th:src="#{/resources/images/notebook.svg}" /> Client Creation
</button>
</div>
</div>
<div class="container">
<div class="mp-pusher" id="mp-pusher">
<nav id="mp-menu" class="mp-menu"></nav>
<div class="scroller-inner"></div>
<div class="containerMain">
<div class="mainArea">
<div class="inputArea">
<div class="ccode">
<lable class="lable">Client code</lable>
<input type="text" class="inputfield" id="ccode"
th:field="*{salesBean.client.clientId}" />
<button type="button" class="inputbutton" id="clientData"></button>
</div>
<div>
<ul class="tabs" data-persist="true">
<li>Basic data</li>
<li>Payment</li>
</ul>
<div class="tabcontents">
<div id="tab1">
<div class="invNo">
<lable class="lable">Invoice number</lable>
<input type="text" id="invNo" th:field="*{salesBean.salesId}"
name="salesId" class="inputfield disabled"
readonly="readonly" />
</div>
<div class="invdate calendar">
<lable class="lable">Invoice date</lable>
<input type="date" class="inputfield" id="invdate"
th:field="*{salesBean.invoiceDate}" /> <span
class="calendar"><img
th:src="#{/resources/images/calendar.svg}" /></span>
</div>
<div class="txtChallan">
<lable class="lable">Challan number</lable>
<input type="text" class="inputfield" id="txtChallan"
th:field="*{salesBean.challanNumber}" />
</div>
<div class="txtChallDt calendar">
<lable class="lable">Date</lable>
<input type="date" class="inputfield" id="txtChallDt"
th:field="*{salesBean.challanDate}" /> <span
class="calendar"><img
th:src="#{/resources/images/calendar.svg}" /></span>
</div>
<div class="txtPO">
<lable class="lable">P. O. ID</lable>
<input type="text" class="inputfield" id="txtPO"
th:field="*{salesBean.purchaseOrderId}" />
</div>
<div class="txtPoDt calendar">
<lable class="lable">Date</lable>
<input type="date" class="inputfield" id="txtPoDt"
th:field="*{salesBean.purchaseOrderDate}" /> <span
class="calendar"><img
th:src="#{/resources/images/calendar.svg}" /></span>
</div>
</div>
<div id="tab2">
<div class="txtCash">
<lable class="lable">Cash</lable>
<input type="number" class="inputfield" id="txtCash"
th:field="*{paymentBean.cash}" />
</div>
</div>
</div>
<!-- tabcontents -->
</div>
<!-- blank -->
<!-- for autocomplete -->
<div class="ui-widget" id="autocomplete_desc">
<div class="tableArea">
<div class="tablePanel">
<div class="tableButtonBar">Material entry</div>
<section class="tableHolder">
<table id="invoicetable" class="transactionTable table"
cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>Serial</th>
<th>Description</th>
<th>Nos.</th>
<th>Quantity</th>
<th>Rate</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr
th:each="salesProduct, stat: *{salesProductFormBean.salesProducts}">
<td th:text="${stat.count}">1</td>
<td><input type="text"
**Line no: 290** th:field="*{salesProduct[__${stat.index}__].numbers}" /></td>
<td><select type="select" class="selectfield"
id="product"
th:field="*{salesProduct[__${stat.index}__].product.productId}">
<option value="Select"></option>
<option th:each="prdList : ${productList}"
th:value="${prdList.productId}"
th:text="${prdList.productName}"></option>
</select></td>
<td><input type="number"
th:field="*{salesProduct[__${stat.index}__].quantity}" /></td>
<td><input type="number"
th:field="*{salesProduct[__${stat.index}__].rate}" /></td>
<td><input type="number"
th:field="*{salesProduct[__${stat.index}__].amount}" /></td>
</tr>
</tbody>
</table>
</section>
</div>
<!-- tablePanel -->
</div>
<!-- tableArea -->
</div>
</div>
<!-- inputArea -->
</div>
<!-- mainArea -->
</div>
<!-- containerMain -->
</div>
<!-- /container -->
</div>
</form>
Controller
#Autowired
private List<SalesProduct> salesProducts= new ArrayList<SalesProduct>();
#ModelAttribute("salesProducts")
public List<SalesProduct> salesProducts() {
return salesProducts;
}
#RequestMapping(value= "/sales", method = RequestMethod.GET)
public String salesInvoicePage(final ModelMap model) {
String userName = LoginController.getPrincipal();
model.addAttribute("user", userName);
model.addAttribute("salesBean", new Sales());
model.addAttribute("paymentBean", new Payment());
SalesProductForm salesProductForm = new SalesProductForm();
SalesProduct salesProduct= new SalesProduct();
salesProducts.add(salesProduct);
salesProductForm.setSalesProducts(salesProducts);
model.addAttribute("salesProductFormBean", salesProductForm);
//model.addAttribute("salesProducts", salesProducts);
List<Product> productList= productService.list();
model.addAttribute("productList", productList);
return "sales";
}
Model
public class SalesProduct implements java.io.Serializable {
private Integer salesProductId;
private Product product;
private UserDetail userDetailByModifiedBy;
private UserDetail userDetailByCreatedBy;
private Date createdDate;
private Date modifiedDate;
private String numbers;
private Float quantity;
private Float rate;
private Float amount;
private Set<Sales> saleses = new HashSet<Sales>(0);
//Setter and Getters
}
public class SalesProductForm {
private List<SalesProduct> salesProducts;
public List<SalesProduct> getSalesProducts() {
return salesProducts;
}
public void setSalesProducts(List<SalesProduct> salesProducts) {
this.salesProducts = salesProducts;
}
}
I got stuck in this issue but dont know what am I missing. Does anyone knows what am I doing wrong?
Hibernate Validator doesn't show error message. What did i miss? Please see my code below.
Here is a dependency:
<!-- Hibernate Validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency>
And Entity with annotated column:
#Entity
#Table(name = "transport")
public class Transport {
....
#NotEmpty
#Column(name = "name")
private String name;
....
}
Here are methods from controller:
//show all and add form
#RequestMapping (value = "/admin/transports", method = RequestMethod.GET)
public String findAll(ModelMap map){
List<Transport> transports = transportService.findAll();
map.put("transport", new Transport());
map.put("transports", transports);
return "admin/transports/list";
}
//add new
#RequestMapping(value = "/admin/transport/add", method = RequestMethod.POST)
public String addTypeShop(#ModelAttribute("type") #Valid Transport transport, BindingResult result) {
if (result.hasErrors()) {
return "redirect:/admin/transports";
} else {
this.transportService.addTransport(transport);
return "redirect:/admin/transports";
}
}
And jsp page:
<form:form role="form" action="/admin/transport/add" method="post" commandName="transport">
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="name">Name</label>
<form:input type="text" path="name" class="form-control input-sm" id="name" autofocus="true"/>
<form:errors path="name"/>
</div>
</div>
<input type="submit" class="btn btn-sm btn-primary" value="Add" onclick="loading()"/>
</form:form>
You do not have any code showing the errors back to the end user.
Please see the following link for an example:
http://www.mkyong.com/spring-mvc/spring-mvc-form-errors-tag-example/
Also, It doesn't look like you actually set your command object in your form. You might not have shown that code though.
Small side note, I would not do a redirect if you have validation errors, just send them directly back to the page they came from.
EDIT
After further review, I do see that you have . Normally this goes outside and above the form itself.
<form:errors path="transport"/>
<form:form role="form" action="/admin/transport/add" method="post" commandName="transport">
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="name">Name</label>
<form:input type="text" path="name" class="form-control input-sm" id="name" autofocus="true"/>
</div>
</div>
<input type="submit" class="btn btn-sm btn-primary" value="Add" onclick="loading()"/>
</div>
</form:form>