I'm starting to learn java web, and i need some insight on why my code isn't working
when i try to submit my code i notice that when i go to the pages where should be an alteration it doesn't show anything.
i'll show some code
Post Method
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String titulo = request.getParameter("titulo");
String imagem = request.getParameter("imagem");
String descricao = request.getParameter("descricao");
String categoria = request.getParameter("categoria");
Noticias noticia = new Noticias();
System.out.println(titulo);
noticia.setTitulo(titulo);
System.out.println(descricao);
noticia.setDescricao(descricao);
System.out.println(categoria);
noticia.setCategoria(categoria);
System.out.println(categoria);
noticia.setImagem(imagem);
Noticias.dados.add(noticia);
response.sendRedirect(categoria);
}
Get Method
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
Inputs
<form>
<div class="form-group">
<label for="titulo">Titulo</label>
<input class="form-control" id="titulo" placeholder="Titulo">
</div>
<div class="form-group">
<label for="imagem">Imagem</label>
<input class="form-control" id="imagem" placeholder="Imagem">
</div>
<div class="form-group">
<label for="descricao">Descrição</label>
<input class="form-control" id="descricao" placeholder="Descrição">
</div>
<div class="form-group">
<label for="categoria">Categoria</label>
<input class="form-control" id="categoria" placeholder="Categoria">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
my sysout's dont show any output.
and it doesn't show any alteration on the pages, i guess post isn't being initialized
If you are submitting form you have to mention method and action attributes into form tag.
<form action="servletname" method="post">
That servlet should be present into web.xml too.
You can follow this link https://www.journaldev.com/1877/servlet-tutorial-java
Related
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>
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>
This is my first time setting up a Java Servlet, I am trying to retrieve values into my Java Servlet from my input fields in my JSP Form when the user clicks a specific button. I also, am unsure if I used the proper practice for creating my Servlet. I simply right-clicked on my Apache Tomcat 8.0 server and then selected new Servlet.
Java Servlet:
#WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
private static final long serialVersionUID = 3719628899527775749L;
public loginServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
// do some processing here...
// get response writer
PrintWriter writer = response.getWriter();
// build HTML code
String htmlRespone = "<html>";
htmlRespone += "<h2>Your username is: " + username + "<br/>";
htmlRespone += "Your password is: " + password + "</h2>";
htmlRespone += "</html>";
// return response
writer.println(htmlRespone);
}
}
JSP:
<form name="loginForm" action="loginServlet" method="post" id="loginForm">
<div class="imgcontainer">
<img src="images/img_avatar2.png" alt="Avatar" class="avatar">
</div>
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<button id="loginButton" name="loginButton" type="submit">Login</button>
<button id="registerButton" name="registerButton" type="button">Register</button>
<input type="checkbox" checked="checked"> Remember me
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" class="cancelbtn">Cancel</button>
<span class="psw">Forgot password?</span>
</div>
</form>
Your request attribute's name are uname and psw which are added on Jsp page. So you must change your doPost method like this.
String username = request.getParameter("uname");
String password = request.getParameter("psw");
Or
You must change your form in jsp page like this:
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required>
I'm new to servlets and jsp files, and I encountered the following problem:
I have the following jsp form file:
<FORM action="http://myApp/register" method="post">
<P>
First name: <INPUT type="text" name="firstname"><BR>
Last name: <INPUT type="text" name="lastname"><BR>
email: <INPUT type="text" name="email"><BR>
<INPUT type="radio" name="sex" value="Male"> Male<BR>
<INPUT type="radio" name="sex" value="Female"> Female<BR>
<INPUT type="submit" value="Send"> <INPUT type="reset">
</P>
</FORM>
and a servlet which handles a doPost request on the url above.
I want to give the values of the form (such as the first name and last name) to the doPost request.
Any ideas?
Thanks a lot! :)
You can get all the parameters by their name as request.getParameters("firstname") to get the value of the input fields.
public class ServletClass extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String firstName = request.getParameter("firstname");
String lastName = request.getParameter("lastName");
// and so on.....
}
}
I am newbie in HTML and Servlets. I have such a idex.jsp contents:
<form action="createCSV" method="get">
<input type="text" value="D:/">
<input type="submit" value="create">
</form>
And I want to use value of <input type="text" value="D:/"> inside of method Get in my Servlet:
protected void doGet( javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response )
throws javax.servlet.ServletException, IOException{}
Please, help me
change the input field in your html form like this:
<input type="text" name="userInput" value="D:/">
inside the servlet do that:
String userInput = request.getParameter("userInput");