I want a servlet to print the parameters from a html form but in the servlet the request has no parameters.
<form method="post" action="LoginServlet" >
<input type="text" name="username" id="username" /><br/>
<input type="text" name="password" /><br/>
<input type="submit" />
</form>
and the servlet's doPost():
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("POST");
HttpSession session = request.getSession();
String redirectUrl;
Enumeration atributes = request.getAttributeNames();
while (atributes.hasMoreElements()) {
System.out.println((String )atributes.nextElement()+ ".");
}
String user = (String) request.getAttribute("username");
String pass = (String) request.getAttribute("password");
System.out.println("user:" + (String) request.getAttribute("username"));
}
So it doesn't output any parameters and the username parameters is NULL.
These are parameters - use getParameter(String).
Related
I'm trying to get form data from my html page on a post request but when I use the getFormAttribute() function, it returns null. Here is the code:
Route postArticleRoute = router
.post("/articlePosted")
.handler(routingContext -> {
HttpServerResponse response = routingContext.response();
HttpServerRequest request = routingContext.request();
String title = request.getFormAttribute("title");
String auth = request.getFormAttribute("author");
String body = request.getFormAttribute("body");
System.out.println(title + auth + body);
});
This code returns: 'nullnullnull'
I've double checked that these are the name attributes in the html form. Just in case, here is the html:
<form action="/articlePosted" method="post">
<label>Title of Article</label><br>
<input type="text" name="title" id="postArticle-title"><br><br>
<label>Author</label><br>
<input type="text" name="author" id="postArticle-auth"><br><br>
<label>Image</label><br>
<input type="file" name="file" id="postArticle-img"><br><br>
<label>Body</label><br>
<textarea style="width: 100%; height: 500px;" name="body" id="postArticle-body"></textarea><br><br>
<input type="submit" value="Post">
</form>
Any help would be appreciated.
In my jsp I am calling a servlet:
<form method="GET" action ="${pageContext.request.contextPath}/CurrencyController?action=listCurrency">
Currency code: <input type="text" name="currencyCode" id="currencyCode" />
<br />
<input type="submit" value="Search" />
</form>
But in my Servlet request.getParameter("action") is null. So how can I pass the action parameter?
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if (action.equalsIgnoreCase("delete")){
String currencyCode = request.getParameter("currencyCode");
...
} else if (action.equalsIgnoreCase("edit")){
String currencyCode = request.getParameter("currencyCode");
...
} else if (action.equalsIgnoreCase("listCurrency")){
request.setAttribute("currencies", dao.getCurrencyByCode(request.getParameter("currencyCode")));
} else {
forward = INSERT_OR_EDIT;
}
RequestDispatcher view = request.getRequestDispatcher(forward);
view.forward(request, response);
}
You can define another hidden parameter like this
<input name="action" type="hidden"
value="${pageContext.request.contextPath}/CurrencyController?
action=listCurrency" />
and then in servlet use the same code request.getParameter("action") to get its value.
I have the following JSP which contains a form. The user should be able to update and delete, so I have two buttons for these options:
<form method="GET" action ="${pageContext.request.contextPath}/CurrencyController">
Currency code: <input type="text" name="currencyCode" id="currencyCode" value="${currency.currencyCode}" />
<br/>
<input type="submit" value="Update" >
<input type="submit" value="Delete"/>
</form>
In my servlet CurrencyController I retrieve the action:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if (action.equalsIgnoreCase("update")){
...
if (action.equalsIgnoreCase("delete")){
...
So how can I pass the value for action in my form? It should be update if the first button is clicked and delete if the second button is clicked
Add action parameter using new input:
<input type="hidden" name="action" id="action" value="" />
Add onClick attribure to each submit button that will change its value. for example:
onClick="document.getElementId('action').value=this.value;return true;"
I'm working on my first web application. I am sending email with an url in it:
http://localhost:8080/HotelP/requeteSuccesO.jsp?hotelId=hampton&city=Montreal
When clicking on the link, requeteSuccesO.jsp displays the hotelId and city parameters:
out.println("<b>Hotel:</b> "+request.getParameter("hotelId")+"</br>");
out.println("<b>City:</b> "+request.getParameter("city")+"</br>");
Then the user can accept by clicking on a button:
<form method="get" action="acceptOffer">
<input type="submit" value="Accept" class="sanslabel">
acceptOffer is mapped to a servlet DecisionPage.java, and by clicking on that button it's calling the doGet() method.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("in do get DecisionPage, hotelId is "+request.getParameter("hotelId"));
this.getServletContext().getRequestDispatcher( VUE_PAIEMENT ).forward( request, response );
}
The parameter hotelId received by the doGet function is null, but I am expecting it to be the value found in the url (in our case, "hampton")
Can anyone tell me why I get null and not "hampton" ?
When you make a form and submit that form to some action, it will only create request parameters for the fields you have defined in your form.
So, while you run the application with mentioned URL, it would contain those parameters and will be avilable to your jsp but if you don't include them in your form it won't be available to servlet when you submit the form.
So, you need to include those parameters to some hidden fields if you don't won't to show them to user.
Example:
<form method="get" action="acceptOffer">
<input type="hidden" name="hotelId" value="<%= request.getParameter(\"hotelId\")" %> /> <---- this field will create a new parameter with name as hotelId
<input type="hidden" name="city" value="<%= request.getParameter(\"city\") %>" />
<input type="submit" value="Accept" class="sanslabel">
</form>
So, now as we made a new fields hotelId and city they will be sent to your servlet acceptOffer and then you'll be able to access them with request parameter as below:
request.getParameter("hotelId")
You have to include those paramters in the form itself because the scope of the paramters is request scope. Something like this
<form method="get" action="acceptOffer">
<input type="text" name="hotelId" value=assign the value from request here/>
<input type="submit" value="Accept" class="sanslabel">
</form>
I´m trying to create a form and validate its data via #Valid on the command object.
The validation performs well, but an error is ocurring going back to web.
This is what I have:
HTML
<div id="content" layout:fragment="contenido">
<div sec:authorize="isAnonymous()">
<form class="form-horizontal" action="#" th:action="#{register}" th:object="${userForm}" method="post">
<input type="hidden" name="_csrf" th:value="${_csrf.token}"/>
<fieldset>
<label for="alias" th:text="#{form.register.alias}">Alias</label>
<input id="alias" type="text" th:field="*{alias}" placeholder="Su alias" required="required" autofocus="autofocus"/>
<label for="pass" th:text="#{form.register.password}">Contraseña</label>
<input id="pass" type="password" th:field="*{password}" pattern="[\w\d-_]{5,15}" required="required" th:title="#{form.error.password}"/>
<p th:if="${#fields.hasErrors('password')}" th:errors="*{password}">Error en el dato ingresado</p>
<button type="submit" name="save" class="btn btn-primary" th:text="#{control.register}">Registrarme</button>
</fieldset>
</form>
</div>
</div>
Controller
#RequestMapping(value = "/register", params = {"save"}, method = RequestMethod.POST)
public String register (final ModelMap model, #Valid final UsuarioForm userForm, final BindingResult result) {
if (result.hasErrors()) {
return "register";
} else {
return "redirect:/" + HomeController.PAGE_NAME;
}
}
When Clicking on "submit" the "register" method is called, result.hasErrors() is true so the same page should be displayed, but this error occurs.
Stack
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'userForm' available as request attribute
org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:144)
org.thymeleaf.spring4.util.FieldUtils.getBindStatusFromParsedExpression(FieldUtils.java:396)
org.thymeleaf.spring4.util.FieldUtils.getBindStatus(FieldUtils.java:323)
org.thymeleaf.spring4.util.FieldUtils.getBindStatus(FieldUtils.java:289)
org.thymeleaf.spring4.processor.attr.AbstractSpringFieldAttrProcessor.processAttribute(AbstractSpringFieldAttrProcessor.java:98)
org.thymeleaf.processor.attr.AbstractAttrProcessor.doProcess(AbstractAttrProcessor.java:87)
org.thymeleaf.processor.AbstractProcessor.process(AbstractProcessor.java:212)
org.thymeleaf.dom.Node.applyNextProcessor(Node.java:1017)
org.thymeleaf.dom.Node.processNode(Node.java:972)
If I add "userForm" to the model in the Controller this way:
Controller Modified
#RequestMapping(value = "/register", params = {"save"}, method = RequestMethod.POST)
public String register (final ModelMap model, #Valid final UsuarioForm userForm, final BindingResult result) {
if (result.hasErrors()) {
model.addAttribute("userForm", userForm); //THIS LINE IS ADDED
return "register";
} else {
return "redirect:/" + HomeController.PAGE_NAME;
}
}
The error disappears, BUT... the expression in the HTML ${#fields.hasErrors('password')} results false, so I cant show the error messages to the user.
Any idea of why this behaviour is happening?
Thanks in advance!
PS: I am using Spring MVC 4.1.2 with Thymeleaf 2.1.4
This
public String register(final ModelMap model,
#Valid final UsuarioForm userForm,
final BindingResult result)
should be:
public String register(final ModelMap model,
#ModelAttribute("userForm") #Valid final UsuarioForm userForm,
final BindingResult result)
Notice the #ModelAttribute annotation.