Post Form won't call Servlet - java

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>

Related

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);

submit data from a java form as json type

I'm trying to submit data of a form as Json type . Here's a bunch of code, it doesn't work and I have no idea what to do next, please hold my hand and guide me:
.................................................................................................................................................
<%#include file="header.jsp" %>
<script src="resources/js/jquery.serializejson.js">
</script><script src="resources/js/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function() {
$("#frmRegStudent").on('submit', function() {
$.ajax({
dataType: "json",
data: $("#myformid").serialize(),
success: function() {
"/registerSuccessfully.jsp";
}
});
return false; // don't reload the page
});
});
</script>
<script type="text/javascript">
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if ((charCode > 31 && charCode < 48) || charCode > 57) {
return false;
}
return true;
}
</script>
<div class="container">
<div class="page-header">
<h1>Register Student</h1>
<p class="lead">Please fill in your information below</p>
</div>
<form id="frmRegStudent" name="frmRegStudent"action="/student /studentRegister" method="post" data-toggle="validator" role="form">
<div class="form-group has-feedback">
<label for="studentCode">studentCode</label>
<input type="text" onkeypress="return isNumber(event)" id="studentCode" name="studentCode"
class="form-control" data-error="please fill studentCode" required/>
<span class="glyphicon form-control-feedback" aria-hidden="true"></span>
<span class="help-block with-errors"></span>
</div>
<div class="form-group has-feedback">
<label for="firstname">Name</label>
<input type="text" id="firstname" name="firstname" class="form-control" data-error="please fill name" required/>
<span class="glyphicon form-control-feedback" aria-hidden="true"></span>
<span class="help-block with-errors"></span>
</div>
<div class="form-group has-feedback">
<label for="lastname">Family</label>
<input type="text" id="lastname" name="lastname" class="form-control" data-error="please fill lastName" required/>
<span class="glyphicon form-control-feedback" aria-hidden="true"></span>
<span class="help-block with-errors"></span>
</div>
<div class="form-group has-feedback">
<label for="lastname">phone</label>
<input type="text" onkeypress="return isNumber(event)" id="phone" name="phone" class="form-control" data-error="please fill phone" required/>
<span class="glyphicon form-control-feedback" aria-hidden="true"></span>
<span class="help-block with-errors"></span>
</div>
<div class="form-group has-feedback">
<label for="lastname">email</label>
<input type="text" onkeypress="return isNumber(event)" id="email" name="email" class="form-control" data-error="please fill email" required/>
<span class="glyphicon form-control-feedback" aria-hidden="true"></span>
<span class="help-block with-errors"></span>
</div>
<input type="submit" id="Register" value="Register" class="btn btn- success"/>
</form>
</div>
<%#include file="footer.jsp" %>
and this is my servlet class:
...........................................................................................................................................................
public class StudentServlet extends HttpServlet {
StudentServiceInter service = new StudentServiceImpl();
ObjectMapper mapper = new ObjectMapper();
String json = "";
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter out = resp.getWriter();
int id = Integer.parseInt(req.getParameter("data"));
Student student = service.findOne(id);
json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(student);
out.print(json);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String json = req.getParameter("data");
Student student = mapper.readValue(json, Student.class);
service.saveOrupdate(student);
}
#Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter out = resp.getWriter();
String json = req.getParameter("data");
out.print("edited successfully");
}
#Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter out = resp.getWriter();
int id = Integer.parseInt(req.getParameter("id"));
service.delete(id);
out.print("deleted successfully");
}
}
but it doesn't work anybody can help me .
You also must have web.xml, there is indicated servlet mapping:
<servlet>
<servlet-name>StudentServlet </servlet-name>
<servlet-class>package.to.servlet.StudentServlet </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>StudentServlet </servlet-name>
<url-pattern>/student/studentRegister/StudentServlet</url-pattern>
</servlet-mapping>

Strange message with servlets

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

Spring submit form get checkbox value not working

I cannot get "remember-me" checkbox value (getting 400 Required boolean parameter 'remember' is not present)
Trying to user #RequestParam. (as for inputs email/password).
How to get checkbox value and not 400 error?
Controller
#RequestMapping(value = "/login", method = RequestMethod.POST)
private String doLogin(#RequestParam(value = "inputEmail") String inputEmail,
#RequestParam(value = "inputPassword") String inputPassword,
#RequestParam(value = "remember") boolean remember,
HttpSession session) {
HTML form
<form class="form-login" method="post" action="/login">
<h2 class="form-login-heading">Please log in</h2>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" name="inputEmail" class="form-control" placeholder="Email address" required
autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" name="inputPassword" class="form-control" placeholder="Password" required>
<div class="checkbox">
<label>
<input type="checkbox" name="remember" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block btn-login" type="submit">Log in</button>
</form>
Please remove value="remember-me" from your check box.
When you will tick checkbox spring will map string value "remember-me" with Boolean which is not possible as i know.

Same URL on request forward from servlet hence operation repeated again

I have been trying to make my project more structured hence i have been following the example in netbeans ecommerce sample project in https://netbeans.org/kb/docs/javaee/ecommerce/page-views-controller.html#controller. I changed my controller according to the example. Now I'm having trouble with going to the page where I display the values in the database.
My Servlet is given below.
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
Op_Stock ops = new Op_Stock();
String userPath = request.getServletPath();
String param = null;
Map<String, String> prdMap = new LinkedHashMap<String, String>();
Map<String, String> lvlMap = new LinkedHashMap<String, String>();
ArrayList<HashMap<String, String>> stkList = new ArrayList<>();
switch (userPath) {
case "/ViewStock":
stkList = ops.getAllStockDetails();
request.setAttribute("stkList", stkList);
userPath = "Stock.jsp";
param = "type=m&page=stk";
break;
case "/AddStockForm":
prdMap = ops.getAllProducts();
lvlMap = ops.getAllLevels();
request.setAttribute("prdMap", prdMap);
request.setAttribute("lvlMap", lvlMap);
userPath = "Insertstk.jsp";
param = "type=m&page=stk";
break;
case "/AddStock":
System.out.println("prdId: " + request.getParameter("prdId"));
int iprdId = Integer.parseInt(request.getParameter("prdId"));
int istkIn = Integer.parseInt(request.getParameter("stkIn"));
int istkthld = Integer.parseInt(request.getParameter("stkthld"));
int ilvlId = Integer.parseInt(request.getParameter("lvlId"));
int stkIn = ops.insertStockDetails(iprdId, istkIn, istkthld, ilvlId);
stkList = ops.getAllStockDetails();
request.setAttribute("stkList", stkList);
if (stkIn > 0) {
userPath = "/Stock.jsp";
param = "message=Stock Details Created!&pg=stk&type=m";
} else {
prdMap = ops.getAllProducts();
lvlMap = ops.getAllLevels();
request.setAttribute("prdMap", prdMap);
request.setAttribute("lvlMap", lvlMap);
userPath = "/Insertstk.jsp";
param = "message=Could not create!&pg=stk&type=m";
}
break;
case "/DeleteStock":
int delStk = ops.deleteStockDetails(request.getParameter("stkId"));
if (delStk > 0) {
userPath = "Stock.jsp";
param = "message=Stock Details Deleted!&pg=stk&type=m";
stkList = ops.getAllStockDetails();
request.setAttribute("stkList", stkList);
} else {
userPath = "Stock.jsp";
stkList = ops.getAllStockDetails();
request.setAttribute("stkList", stkList);
param = "message=Could not delete!&pg=stk&type=m";
}
break;
}
// use RequestDispatcher to forward request internally
String url = userPath + "?" + param;
request.getRequestDispatcher(url).forward(request, response);
//response.sendRedirect(url);
}
In the servlet I'm setting attribute to the request in which the database contents are stored.
Suppose I'm doing an insert operation which is in the switch case "/AddStock" After doing this the request is forwarded to my page where the table is displayed, since i'm using forward it will go to the display page but the URL in the address bar will stay the same with all request parameters from my insert form, hence when I refresh the page the insertion operation will happen again. If I use response.sendRedirect(url), I wont be able to use the request attributes and hence wont't be able to display the DB values.
My Insert form is given below.
<div class="col-md-10">
<form method="POST" action="AddStock" class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label">Product</label>
<div class="col-sm-4">
<select id="s_prdname" class="form-control" name="prdId" required>
<option>Select</option>
<c:forEach items="${prdList}" var="mapItem">
<option value="${mapItem.key}">${mapItem.value}</option>
</c:forEach>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Level</label>
<div class="col-sm-4">
<select id="s_lvlname" class="form-control" name="lvlId" required>
<option>Select</option>
<c:forEach items="${lvlList}" var="mapItem">
<option value="${mapItem.key}">${mapItem.value}</option>
</c:forEach>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">In-Stock</label>
<div class="col-sm-2">
<input type="number" name="stkIn" class="form-control" id="stkIn"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Threshold</label>
<div class="col-sm-2">
<input type="number" name="stkthld" class="form-control" id="stkthld"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default btn-primary"><strong>Submit</strong></button>
</div>
</div>
</form>
</div>
My Display page is given below.
<div class="table-responsive">
<table class="table table-bordered table-striped table-hover">
<thead>
<th><strong>Product Name</strong></th>
<th><strong>Level</strong></th>
<th><strong>In Stock</strong></th>
<th><strong>Threshold</strong></th>
<th><strong>Expiry</strong></th>
<th><strong>Operations</strong></th>
</thead>
<tbody>
<jsp:useBean id="lvl" scope="request" class="Level.Level"/>
<jsp:useBean id="prd" scope="request" class="Product.Product"/>
<c:forEach items="${stkList}" var="row">
<tr>
<td><jsp:setProperty name="prd" property="prdId" value="${row.prdStk}"/><jsp:getProperty name="prd" property="prdName"/></td>
<td><jsp:setProperty name="lvl" property="lvlId" value="${row.lvlStk}"/><jsp:getProperty name="lvl" property="lvlName"/></td>
<td>${row.inStk}</td>
<td>${row.thldStk}</td>
<td>${row.expStk}</td>
<td>
<button type="button" class="btn btn-default btn-sm btn-danger" onclick="deletedata('${row.idStk}');">
<span class="glyphicon glyphicon-trash"></span>
</button>
<button class="btn btn-info btn-sm" data-toggle="modal" data-target="#myModal">
<span class="glyphicon glyphicon-eye-open"></span>
</button>
</td>
</tr>
</c:forEach>
</tbody>
<tfoot>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tfoot>
</table>
</div>
Please help me to solve this problem, if the method I used is wrong please suggest the right one.
To solve this problem I used.
response.sendRedirect(url);
Instead of
request.getRequestDispatcher(url).forward(request, response);
And Instead of displaying the values in the DB by setting an attribute in request, I have used to access the method in my class as shown below.
<jsp:useBean id="stk" scope="request" class="Stock.Op_Stock"/>
<c:forEach items="${stk.allStockDetails}" var="row">
// Values in the map displayed here
</c:forEach>

Categories