Strange message with servlets - java

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...

Related

Add dynamically radio button to JSP Form

I was trying to add dynamically extra fields to a Form. However only text/number fields are getting created as expected. The radio buttons got created but the choose list is being shared with all the objects. Also notice Im closing the FORM after the script close otherwise path FORM input will throw and error. rAny idea what Im missing? Thank you in advance.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-5 p-1">
<form:form method="POST" modelAttribute="investmentForm" class="p-4">
<div class="row">
<div class="col-lg-12">
<div id="inputFormRow">
<div class="form-group">
<label><h5><b>Invoice ID</b></h5></label>
<form:input path="invoiceNumber" name="invoiceNumber[]" class="form-control m-input" placeholder="E001-1234" required="required" />
</div>
<div class="form-group">
<label><h5><b>Amount</b></h5></label>
<form:input path="amountForm" name="amount[]" type="number" class="form-control m-input" step=".01" required="required" min="1" max="10000"/>
</div>
<label><h5><b>Currency</b></h5></label>
<div class="form-check form-check-inline">
<label class="form-check-label">
<form:radiobuttons class="form-check-input" path="currency" items="${curr}"/>
</label>
</div>
</div>
<div id="newRow"></div>
<button id="addRow" type="button" class="btn btn-info">Add Row</button>
</div>
</div>
<button type="submit" class="btn mt-4 btn-block p-2 btn-success shadowed">Invest!</button>
<script type="text/javascript">
// add row
var counter = 1;
$("#addRow").click(function () {
counter += 1;
var html ='<div id="inputFormRow">'
+'<div class="form-group">'
+'<label><h5><b>Invoice ID</b></h5></label>'
+'<form:input path="invoiceNumber" name="invoiceNumber[]" class="form-control m-input" placeholder="E001-1234" required="required" />'
+'</div>'
+'<div class="form-group">'
+'<label><h5><b>Amount</b></h5></label>'
+'<form:input path="amountForm" name="amount[]" type="number" class="form-control m-input" step=".01" required="required" min="1" max="10000"/>'
+'</div>'
+ '<div class="form-group">'
+'<label><h5><b>Currency</b></h5></label>'
+'<div class="form-check form-check-inline">'
+'<label class="form-check-label">'
+'<form:radiobuttons class="form-check-input" path="currency" items="${curr}"/>'
+'</label>'
+'</div>'
+'<div class="input-group-append">'
+'<button id="removeRow" type="button" class="btn btn-danger">Remove</button>'
+'</div>'
+'</div>'
$('#newRow').append(html);
});
// remove row
$(document).on('click', '#removeRow', function () {
$(this).closest('#inputFormRow').remove();
});
</script>
</form:form>

How to call a method in HTML(Thymeleaf, Spring, Java)?

i'm beginner with Thymeleaf, but i want know how to call a method in HTML with Thymeleaf. I'm using Spring Boot with Spring MVC.
I want create a Button with a name like "Edit" and the user will edit the post of the blog, but if i want do that i have to know what's the ID from object Postagem.
My current code HTML: (blog.html)
<div th:each="postagem : ${postagens}">
<div class="blog-post">
<h2 class="blog-post-title" th:text="${postagem.titulo}"></h2>
<p class="blog-post-meta">25 de dezembro de 2019 publicado por Vitor</p>
<p th:text="${postagem.texto}"></p>
<form action="#" th:action="#{/blog}" th:object="${postagem}" method="post">
<button type="submit" class="btn btn-link" th:field="*{id}">Editar</button>
</form>
</div>
<!-- /.blog-post -->
</div>
My current method in Java: (PostagemController.java)
#PostMapping("/blog")
public String edit(Postagem postagem) {
for(Postagem post : postagens.findAll()) {
if(post.getId() == postagem.getId()) {
ModelAndView modelAndView = new ModelAndView("painel");
modelAndView.addObject("postagemEdit", post);
System.out.println("Id: " + post.getId());
System.out.println("Título: " + post.getTitulo());
System.out.println("Autor: " + post.getAutor());
System.out.println("Texto: " + post.getTexto());
break;
}
}
return "redirect:/painel";
}
My current code on "painel.html" where is my form that I want set the information
<form method="post" th:object="${postagemEdit}" th:action="#{/painel}" style="margin: 20px 0">
<div class="form-group">
<input type="text" class="form-control" placeholder="Título" th:field="*{titulo}" /> <br>
<input type="text" class="form-control" placeholder="Spoiler do artigo" th:field="*{spoiler}" /><br>
<input type="text" class="form-control" placeholder="Autor" th:field="*{autor}" /> <br>
<textarea id="mytextarea" th:field="*{texto}"></textarea> <br>
<button type="submit" class="btn btn-primary">Publicar</button>
</div>
</form>
It appears that you have not given the id a value in the html code. The default value for int in Java is 0 and that is possibly the reason why. Try to use 1 instead of *{id}.
If you are retrieving the blog post id and post content from the database which should be so then this problem will be solved.
issues
No name
Value not set
solution 1
<form action="#" th:action="#{/blog}" th:object="${postagem}" method="post">
<input type="hidden" name="id" class="btn btn-link" th:value="*{id}" />
<button type=submit class="btn btn-link">Editar</button>
</form>
solution 2
<form action="#" th:action="#{/blog}" th:object="${postagem}" method="post">
<button name="id" type=submit class="btn btn-link" th:value="*{id}">Editar</button>
</form>
solution 3
function myFunction(id) {
var f = document.createElement("form")
f.style.display="none"
f.action="/action_page.php"
f.method="get"
var inp = document.createElement("input");
inp.value=id
inp.name="id"
f.appendChild(inp);
document.body.appendChild(f);
f.submit();
}
<button type=submit class="btn btn-link" th:data-id="*{id}" onclick='myFunction(this.getAttribute("data-id"))'>Editar</button>
Following is the working code that i used in the html template to call java class function
<small th:text="${T(com.sample.util.UIclass).textContent(instr)}"> </small>
And below is the java class for the method :
package com.sample.util;
import com.sample.models.Instr;
public class UIclass {
public static String textContent(Instr instr)
{
return "Hello";
}
}
In case if you need to access same in javascript following is the code
let d = [[${T(com.sample.UIclass).textContent(instr)}]];
console.log(d);

405 - request GET and POST

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.

Post Form won't call Servlet

So i have a post form which calls a Servlet to perform a search but the problem is that when i push the submit button it's completely unresponsive. Although when used in the same form in a different .jsp page it works as it should. If it had something to do with the servlet mapping there would be an error page from the tomcat server but i do not get such an error page. It's just completely unresponsive.
My HTML form:
<form action="AnonSearchServlet" class="form-inline" method="post">
<input type="search" name="location" class="form-control input-lg" placeholder="Destination, City, Address" required>
<div class="input-group">
<input type="search" class="form-control input-lg" placeholder="When" name="daterange" value="" required/>
<div class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</div>
</div>
<input style="width: 20%; height: 46px" type="number" min="1" name="accomodates" class="form-control" placeholder="Guests" required>
<button type="submit" class="btn btn-danger btn-lg">Search</button>
</form>
My Servlet:
public class AnonSearchServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String start_date;
String end_date;
String date_range = request.getParameter("daterange");
UserBean user = new UserBean();
String[] tokens = date_range.split(" ");
start_date = tokens[0];
end_date = tokens[2];
try {
HttpSession session = request.getSession(true);
user.setUserID(0);
System.out.println(user.getUserID());
ResultSet search_rs = null;
SearchBean search_bean = new SearchBean();
search_bean.setUserId(user.getUserID());
search_bean.setLocation(request.getParameter("location"));
System.out.println(request.getParameter("location"));
search_bean.setStreet(request.getParameter("location"));
search_bean.setNeighbourhood(request.getParameter("location"));
search_bean.setAccomodates(request.getParameter("accomodates"));
search_bean.setStartDate(start_date);
search_bean.setEndDate(end_date);
search_bean = SearchDAO.search(search_bean);
session.setAttribute("current_search", search_bean);
response.sendRedirect("searchResults.jsp");
} catch (Throwable thException) {
System.out.println(thException);
}
}
}
And my web.xml:
<servlet>
<servlet-name>AnonSearchServlet</servlet-name>
<servlet-class>Servlets.AnonSearchServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AnonSearchServlet</servlet-name>
<url-pattern>/AnonSearchServlet</url-pattern>
</servlet-mapping>
#CharisAlex here is the problem in your jsp page <button> tag doesn't submit form action so you have to modify your code
<button type="submit" class="btn btn-danger btn-lg">Search</button>`
replace into
<input type='submit' class='btn btn-danger btn-lg' value="Search" />
Try to use
<input type="submit" value="submit">
instead of using
<button type="submit" class="btn btn-danger btn-lg">Search </button>

sending multiple row data (table) from HTML to Spring controller using thymeleaf

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?

Categories