NanoHTTPD unable to process POST parameters - java

I have downloaded newest NanoHTTPD from link:
https://raw.githubusercontent.com/NanoHttpd/nanohttpd/master/core/src/main/java/fi/iki/elonen/NanoHTTPD.java
When processing very basic POST example, calling session.getParms() returns empty map. My code is:
#Override
public Response serve(IHTTPSession session) {
System.out.println( session.getMethod() + " " + session.getParms() );
return newFixedLengthResponse("Some response.");
}
Which returns:
{}
HTML code triggering nanoHTTPD is:
<html>
<body>
<form action="http://localhost:3388" method="POST">
<input type="text" name="username" value="a" />
<input type="submit" />
</form>
</body>
</html>
That all looks good. Do you see anything suspicious in my code, or just nanoHTTPD is not mature enough?

You should do parseBody before get parameters when you handle a POST request.
In your code, just like this:
#Override
public Response serve(IHTTPSession session) {
session.parseBody(new HashMap<String, String>());
System.out.println( session.getMethod() + " " + session.getParms() );
return newFixedLengthResponse("Some response.");
}

session.parseBody() only needed if you upload one or more files. Your codes are fine except you must provide enctype="multipart/form-data" in your html form tag. So your html code should be:
<html>
<body>
<form action="http://localhost:3388" enctype="multipart/form-data" method="POST">
<input type="text" name="username" value="a" />
<input type="submit" />
</form>
</body>
</html>

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

How can i open JSP page from another JSP page in java Spring MVC?

I want create 2 JSP pages. I have Controller:
#Controller
#RequestMapping(value = "/api/web/users")
public class ServletWebController {
#RequestMapping(method = RequestMethod.GET)
public String printWelcome(ModelMap model) {
model.addAttribute("message", "message");
return "hello";
}
}
It open first JSP page with form:
<html>
<body>
<form action="main.jsp" method="post">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
When I input data to the form and press submit button, I want to open second JSP page and print data from form:
<html>
<head>
<title>Using GET and POST Method to Read Form Data</title>
</head>
<body>
<center>
<h1>Using GET Method to Read Form Data</h1>
<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>
But the second JSP page not opened. So I input http://localhost:4000/api/web/users And i have form. Then I input data and press "Submit". Then I have this link http://localhost:4000/api/web/main.jsp and error:
HTTP Status 404 - /api/web/main.jsp
type Status report
message /api/web/main.jsp
description The requested resource is not available.
Apache Tomcat/8.0.26
I am new in Spring and JSP, how can I open JSP from another JSP?
in your Controller you can do something like this:
#RequestMapping(value="/successpage", method =RequestMethod.POST)
public void successpage(ModelMap model, Users user)
{
model.addAttribute("name", user.getFirstName());
}
#RequestMapping(value="/signupform", method=RequestMethod.GET)
public ModelAndView signupForm()
{
return new ModelAndView("user", "command", new Users()); //Object that contains your getter and setters
}
On your form you can modify your open Form tag to look like this:
<form action="/successpage" method="POST">
In your WEB-INF/jsp folder you will need the 2 pages: signupform.jsp and successpage.jsp
After all is said and done, you can pass the ${name} variable on your successpage.jsp to see the value from the form.

How to upload a image using vaadin

I have a below kind of html
<html>
<head>
<title>Upload a file please</title>
</head>
<body>
<h1>Please upload a file</h1>
<form method="post" action="http://localhost:8080/service/uploadFile" enctype="multipart/form-data">
<input type="text" name="name"/>
<input type="file" name="file"/>
<input type="submit"/>
<input type="hidden" name="smallSize" value="50x50">
<input type="hidden" name="mediumSize" value="100x100">
<input type="hidden" name="largeSize" value="150x150">
</form>
</body>
</html>
I want to do it using Vaadin Upload component?How can I achieve this?
You can't mix normal html pages with vaadin processing the "results".
They way to go would be to embedd vaadin in your html page.
Look here:
https://vaadin.com/de/book/vaadin7/-/page/advanced.embedding.html
I use https://vaadin.com/directory#addon/easyuploads for it.
Example:
final UploadField uploadField = new UploadField();
Button b = new Button("Show value");
b.addListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
Object value = uploadField.getValue();
mainWindow.showNotification("Value:" + value);
}
});
You can use vaadin-upload to upload one image with attribute (maxfiles) on

Liferay doesn't catch form in portlet, and doesn't process

I have .jsp in liferay, and use javascript with applet, but after the form sent to the portlet, on the server side, portlet doesn't catch the form, and do not show in logs additional messages.
jsp page's snippet:
<script type="text/javascript">
function processSigning(){
var applet = document.applets["SignApplet"];
var path_to_certificate = document.getElementById("certificate").value;
var pass = document.getElementById("password").value;
var filePath = document.getElementById("documentSign").value;
applet.filePath = document.getElementById("documentSign").value;
applet.profileTestPKCS12(path_to_certificate, pass);
document.getElementById("file").value = applet.getDocumentString(filePath);
document.getElementById("sign").value = applet.getSignString();
document.getElementById("cert").value = applet.getCertificateString();
document.getElementById("mainForm").submit();
}
</script>
<form id="mainForm" action="<portlet:actionURL>
<portlet:param name="COMMAND" value="LOAD"/>
</portlet:actionURL>">
<hidden id="file" value="asdf"></hidden>
<hidden id="cert" value="asdf"></hidden>
<hidden id="sign" value="asdf"></hidden>
<input type="button" onClick="processSigning();" value="click here!" >
</form>
portlets snippet:
public void processAction(ActionRequest request, ActionResponse response) throws PortletException {
session = request.getPortletSession(true);
String command = request.getParameter("COMMAND");
System.out.println("command=" + command);
log.info("command=" + command);
if ("LOAD".equals(command)) {
{
System.out.println("file");
log.info("file");
String fileBase64 = request.getParameter("file");
System.out.println(request.getParameter("file"));
log.info(request.getParameter("file"));
}
}
}
Check your portlet.xml if the portlet-class is pointing to MVCPortlet or your custom portlet class. It should point to the custom portlet class.
Try this form and see if it works for you:
<portlet:actionURL var="myActionURL"></portlet:actionURL>
<form id="mainForm" action="${myActionURL}" method="post">
<input type="hidden" name="COMMAND" id="COMMAND" value="LOAD" />
<input type="hidden" name="file" id="file" value="asdf" />
<input type="hidden" name="cert" id="cert" value="asdf" />
<input type="hidden" name="sign" id="sign" value="asdf" />
<input type="button" onClick="processSigning();" value="click here!" >
</form>
Hope this helps.
There is method for the form must be specified, because Liferay Portal works with "post" method, also the names of hidden parameters must be used with "name" attribute, because request works with name, not ids

Set a request attribute depending on the link clicked

I would like to determine which link is being click, and set a request attribute accordingly; to be processed in the controller. The controller is generic. It will dispatch to another page according to the attribute set in the JSP. How can I achieve this?
EDIT:
I have followed the BalusC's advice where
Register
Login
RandomController :
#WebServlet(name = "RandomController", urlPatterns = {"/RandomController/*"})
public class RandomController extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int theRandom = 0;
Random myRandom = new Random();
RequestDispatcher dispatcher = null;
String pathInfo = request.getPathInfo();
String contextPath = request.getContextPath();
String dispatchesPath = contextPath + pathInfo;
System.out.println(pathInfo);
System.out.println(contextPath);
System.out.println(dispatchesPath);
theRandom = myRandom.nextInt(MAX_RANDOM);
request.setAttribute("random", theRandom);
if(pathInfo.equals("/Login")) {
dispatcher = request.getRequestDispatcher("Login.jsp");
dispatcher.forward(request, response);
}
else {
dispatcher = request.getRequestDispatcher("Register.jsp");
dispatcher.forward(request, response);
}
}
}
I have tried this approach but the Exception about maximum depth for nested request dispatchers : 20 is throw.
The generic controller is RandomController which servers two produces random number and set as attribute in request object and sent it to login or register page.
Login.jsp :
<%--
Document : Register
Created on : May 28, 2011, 5:49:35 PM
Author : nicholas_tse
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Online Store Register Page</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
</head>
<body>
<jsp:useBean id="randomBean" class="Helper.RandomInt"
scope="request">
</jsp:useBean>
<h1>Online Store</h1>
<p></p>
<div align="right">
<h3>
<c:if test="${not empty sessionScope.username}">
! Welcome ${sessionScope["username"]} !
<form action="LogoutController" method="POST">
<input type="submit" name="submit" value="Logout"/>
</form>
</c:if>
</h3>
</div>
<ul id="nav_list">
<li>Home</li>
<li>Product</li>
<li>Add Stock</li>
<li>Shopping Cart</li>
<li>Order Status</li>
<li>Register</li>
<li>Login</li>
</ul>
<br></br>
<p></p>
<c:if test="${!not empty sessionScope.username}">
<div id="registerForm" align="center"
style="border:1px solid black; width:760px" >
<form name="RegisterForm" action="RegisterController"
method="POST">
<p>
Username : <input type="text" id="username" name="username">
<c:if test="${message.msg} != null" >
${message.msg}
</c:if>
</p>
<p>
Password : <input type="password" id="password" name="password"
</p>
<p>
Name : <input type="text" id="name" name="name">
<c:if test="${message.msg} != null" >
${message.msg}
</c:if>
</p>
<p>
Address : <input type="text" id="address" name="address">
<c:if test="${message.msg} != null" >
${message.msg}
</c:if>
</p>
<p>
State :
<select>
<option>Selangor</option>
<option>Kuala Lumpur</option>
<option>Cyberjaya</option>
<option>Putrajaya</option>
</select>
</p>
<p></p>
<input type="submit" name="submit" value="Register">
<input type="reset" name="clear" value="Clear">
<p></p>
</form>
</div>
</c:if>
</body>
</html>
Without further info the only suggestion I can think of is to add a querystring to your URLs. Like this:
Page 1
This way you can look at the actiuon parameter in the request to determine what to do in your controller.
You can add a request parameter. This can be done in 2 ways depending on whether your form has a method of POST or GET.
You have implemented the submit buttons in the forms with a name attribute of submit and different value attributes. This should mean that the requests will include a submit parameter in the query string or the POST form data. On the server side, you can use this to figure out which of the submit buttons was clicked.

Categories