le-annen.javaserver.0.1.source-code.ControllerPost Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of javaserver Show documentation
Show all versions of javaserver Show documentation
A minimal java http server which fulfills small portions of the
http specifications. This is not a full fledged or secure server. It should only be used
for learning purposes and contains no guarantees of any king.
The newest version!
import java.io.*;
import java.net.URLDecoder;
import java.util.HashMap;
class ControllerPost implements ControllerInterface {
@Override
public ResponseParameters getResponse(RequestParameters requestParams) throws IOException {
HashMap formData = this.parseFormData(requestParams.getBodyContent());
String formContent = this.formatFormData(formData);
return new ResponseParameters.ResponseBuilder(200)
.setDate()
.setContentLength(formContent)
.setContentType(formContent)
.setBodyType(formContent)
.setBodyContent(formContent)
.build();
}
HashMap parseFormData(String bodyContent) throws UnsupportedEncodingException {
String[] formFields = bodyContent.split("&");
HashMap formData = new HashMap<>();
for(String field: formFields) {
String[] fieldKeyValue = field.split("=");
formData.put(URLDecoder.decode(fieldKeyValue[0], "UTF-8").trim(),
URLDecoder.decode(fieldKeyValue[1], "UTF-8").trim());
}
return formData;
}
String formatFormData(HashMap formData) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("\n" +
"\n" +
"\n" +
"\n" +
"Title of the document \n" +
"\n" +
"\n" +
"");
for (String key: formData.keySet()) {
String value = formData.get(key);
stringBuilder.append("" + key + ": " + value + "
");
}
stringBuilder.append("\n" + "\n" + "");
return stringBuilder.toString();
}
}