making a servlet in netbeans and index.jsp - forms

i am trying to make a servlet in netbeans. It has to be called from an html form and take some data from it.
i overwrite doget and dopost putting just some testing outs in them.
when i try to run the servlet it only shows a hello word jsp page i found out that this was the index.jsp page that the servlet had by default.
How can i make the servlet run and actually make some output? other than the index welcome page?
Which url mast i use in order to call the servlet from the form?
th doget and dopost methods look like this
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
ResourceBundle rb =
ResourceBundle.getBundle("LocalStrings",request.getLocale());
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
String title = rb.getString("helloworld.title");
out.println("<title>" + title + "this is my anser</title>");
out.println("</head>");
out.println("</html>");
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);}

How can i make the servlet run and actually make some output? other than the index welcome page?
You should dispatch the request into the desired JSP page. You can do this with RequestDispatcher.
request.getRequestDispatcher("page.jsp").forward(request, response);
Which url mast i use in order to call the servlet from the form?
The one which you've mapped in web.xml.
You should also be putting HTML in JSP page only, not in servlet. It's also not a good practice to let doGet() and doPost() do the same. The doGet() is merely there to preprocess the data before displaying in JSP. The doPost() is merely there to postprocess the data after a HTML form submit.
In the tag info about [servlets] tag here you can find a hello world example and more links about starting with JSP/servlets.

Related

How to access suffixes using HTL/Sightly?

TLDR: Create a new AEM page called "mypage.html". Supply suffixes in the URL. Pass this suffixes to an Sling servlet. The suffixes act as URL parameters.
sample desired URL: http://localhost:4502/mypage.html/john/smith
So I created a servlet (used this guide: http://www.aemcq5tutorials.com/tutorials/sling-servlet-in-aem/) that can read a suffix.
#SuppressWarnings("serial")
#SlingServlet(paths="geometrixx/components/hompepage", selectors="name", extensions="html",methods="GET", metatype=true)
public class StaffProfileServlet extends SlingAllMethodsServlet {
private static final Logger log = LoggerFactory.getLogger(CourseBookmarkServlet.class);
#Override
protected void doGet(final SlingHttpServletRequest request,
final SlingHttpServletResponse response) throws ServletException, IOException {
RequestPathInfo rpi = request.getRequestPathInfo();
String[] suffixes = rpi.getSuffix().split("/");
and it working fine if I access it via http://localhost:4502/content/geometrixx/en.name.html/first/last
What I want to do next is create a new page called "mypage.html" and supply first and last as suffixes.
mypage will display information relevant to the person in a properly formatted page. With code above, all I get is JSON response.
Some assumptions/changes which I think is needed to achieve my goal:
I will be using paths and using request parameters (i.e. using request.getParameter("myparameter") on servlet code
I will be using AJAX to access the servlet
If my assumptions are correct, how do I access suffixes from HTL/Sightly? I understand I can get the URI via ${request.requestURI} or even Javascript. And using this value, I can then use this in my AJAX call.
But is this the AEM/Sling way of doing it? Or perhaps there is a better way to do what I want?
Thanks a lot!
You can use RequestPathInfo interface from HTL to access suffix's. ${request.requestPathInfo.suffix}
Global objects accessible through HTL -> here.
Methods accessible through request object -> here.

Why is sendRedirect(String path) not throwing IllegalStateException?

I've following code in my servlet
public class RedirectingExceptionServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello, response is being committed");
out.flush();
response.sendRedirect("redirectedExceptionServlet");
System.out.println("Tried redirecting after committing response");
}
}
Here, I'm trying to redirect after the response has been committed.
As per the specification Send Redirect java doc sendRedirect(String) should throw IllegalStateException if you try to call sendRedirect(path) after response is committed
Rather i see a page with message : Hello, response is being committed
Another interesting thing is, i'm unable to see statement "Tried redirecting after committing response" in server console
Can someone pls explain me this behavior?
Env details : Windows 7, Tomcat 7.0.47, J2EE-6
Once the container encounters out.flush(); it returns from there and doesn't execute remaining lines of code or simply ignores them and this is true only in case there is no redirection before out.flush();
I have tried a lot of combinations. If someone is interested to have a look at these combinations, I can share them

Calling Servlet From GWT FormPanel

How can I Pass parameter from FormPanel of GWT to Servlet?
FormPanel formPanel = new FormPanel();
formPanel.setAction(GWT.getModuleBaseURL()
+ "ntPdfDownload?myParam=" + String.valueOf(document.getId())+ "&myValue="+ConstantName.IS_REQUIRED.toString()+"");
formPanel.setMethod(FormPanel.METHOD_GET);
formPanel.setEncoding(FormPanel.ENCODING_MULTIPART);
formPanel.submit();
This is what I have done.. But I am not able to get parameters at Servelt.
If you want to use ENCODING_MULTIPART. Your method has to be POST. This is generally required when you want to upload files to server.
I guess you are passing simple parameters to your servlet.So, It should work without formPanel.setEncoding(FormPanel.ENCODING_MULTIPART);.
If you have changed the method from GET to POST, make sure that in the servlet you're also implementing
public void doPost(HttpServletRequest req, HttpServletResponse resp){...}
instead of just the doGet(...)

Communicating between an HttpServlet and the client side of a GWT application

I have a simple GWT application that consists of a FormPanel that contains a single FileUpload field. The action on this form is to send it to GWT.getModuleBaseURL() + "process", which web.xml in turn tells GWT is the FileProcessServlet.
FileProcessServlet is a class that I made that extends HttpServlet and overrides doPost(HttpServletRequest req, HttpServletResponse resp) to parse the uploaded file and turn it into a Base64 string using Base64Utils. Now, I would like to pass the client side a single string that is the Base64 encoding of the file just sent it.
For the life of me, I just cannot figure out how to do this. The GWT documentation on Communicating with the Server doesn't say anything about receiving information back from a FormPanel.submit(). There is no callback function associated with such a request, as is the case with GWT RPC. At the same time, I need to use a servlet, since I want to parse a file, and that can't be done by the client. Any suggestions?
~~~~
PS: One option is that I can write directly to the html page from the servlet using java.io's PrintWriter (as this suggests). This may present a kind of solution where I store the Base64 string in a div with a special ID and then use DOM to get this content on the client end. However, I have not yet gotten PrintWriter to cooperate with me. Anytime I use it, with varying content types and character encodings, I still see nothing printed on the page. What I currently have attempting to print this out is:
String base64 = Base64Utils.toBase64(file);
resp.setContentType("text/html; charset=UTF-8");
resp.setCharacterEncoding("UTF-8");
PrintWriter out = resp.getWriter();
out.print(base64);
out.flush(); out.close();
But nothing comes out. The debugger has confirmed that the string base64 is not null nor empty on the penultimate line. Any help on this related front would also be appreciated. Nonetheless, I sincerely hope there is a better way.
form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
public void onSubmitComplete(SubmitCompleteEvent event) {
// When the form submission is successfully completed, this event is
// fired. Assuming the service returned a response of type text/html,
// we can get the result text here (see the FormPanel documentation for
// further explanation).
Window.alert(event.getResults());
}
});
Whatever you write out from the servlet, will be in the event.getResults(), in your case the base64 String
Well I'm not 100% sure if your problem is on client or server side.
For the client:
formPanel.setAction("/[urlMappingOfYourServlet]");
formPanel.setEncoding(FormPanel.[CORRECT_ENCODING]);
formPanel.setMethod(FormPanel.METHOD_POST);
And to start the submission:
formPanel.submit();
Don't forget the mapping of your servlet in your web.xml. E.g.:
<servlet>
<servlet-name>nameOfYourServlet</servlet-name>
<servlet-class>your.package.server.YourServletClass</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>nameOfYourServlet</servlet-name>
<url-pattern>/urlMappingOfYourServlet</url-pattern>
</servlet-mapping>
On the server side you get the parsed data:
String data = request.getParameter("[NameOfYourFormPanelItem]");
You could use a javax.servlet.ServletOutputStream instead of PrintWriter.
ServletOutputStream out = resp.getOutputStream();
out.write(base64);
out.flush();
Another possibility is to use a RequestBuilder on the client side:
RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.POST, "/urlMappingOfYourServlet");
requestBuilder.sendRequest(someData, new RequestCallback() {
#Override
public void onResponseReceived(Request request,
Response response) {
// ToDo: Get your String here
response.getText();
}
#Override
public void onError(Request request, Throwable exception) {
// ToDo
}
});

How to fix Jersey POST request parameters warning?

I'm building a very simple REST API using Jersey, and I've got a warning in my log files that I'm not sure about.
WARNING: A servlet POST request, to
the URI
http://myserver/mycontext/myapi/users/12345?action=delete,
contains form parameters in the
request body but the request body has
been consumed by the servlet or a
servlet filter accessing the request
parameters. Only resource methods
using #FormParam will work as
expected. Resource methods consuming
the request body by other means will
not work as expected.
My webapp only has the Jersey servlet defined, mapped to /myapi/*
How can I stop these warnings?
For me the warning was showing for POST application/x-www-form-urlencoded. And I am using Spring Boot which has an HiddenHttpMethodFilter that does a getParameter before anything else... So I ended up doing this nasty override:
#Bean
public HiddenHttpMethodFilter hiddenHttpMethodFilter() {
return new HiddenHttpMethodFilter() {
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
if ("POST".equals(request.getMethod())
&& request.getContentType().equals(MediaType.APPLICATION_FORM_URLENCODED_VALUE)) {
filterChain.doFilter(request, response);
} else {
super.doFilterInternal(request, response, filterChain);
}
}
};
}
This message is meant to warn developers about the fact that the request entity body has been consumed, thus any other attempts to read the message body will fail.
It is safe to ignore the message or filter it out from the logs:
java.util.logging.Logger jerseyLogger =
java.util.logging.Logger.getLogger(WebComponent.class.getName());
jerseyLogger.setFilter(new Filter() {
#Override
public boolean isLoggable(LogRecord record) {
boolean isLoggable = true;
if (record.getMessage().contains("Only resource methods using #FormParam")) {
isLoggable = false;
}
return isLoggable;
}
});
The following thread describes the warning you are receiving. It sounds as though you might have a filter defined in your web.xml that is processing the request before Jersey does.
Finally got rid of this by making sure I had Content-Type: application/json in my request headers (obviously, on the client side)
I just had my ajax-function in JQuery set to contentType: "application/x-www-form-urlencoded; charset=UTF-8" because with a prior solution (without Jersey) I had some encoding problems. When I removed that the message was gone and everything worked fine.
This warning is the only thing the WebComponent logs, so just turn logging up to ERROR level or turn off logging for this component in your logback.xml or wherever you have logging configured. You don't need to write a custom filter to ignore this specific message since there are no other messages logged from this component.
Source code snippet from org.glassfish.jersey.servlet.WebComponent version 2.14:
if(!form.asMap().isEmpty()) {
containerRequest.setProperty("jersey.config.server.representation.decoded.form", form);
if(LOGGER.isLoggable(Level.WARNING)) {
LOGGER.log(Level.WARNING, LocalizationMessages.FORM_PARAM_CONSUMED(containerRequest.getRequestUri()));
}
}
The localized message that is used for this warning message is:
form.param.consumed=A servlet request to the URI {0} contains form parameters in the request body but the request body has been consumed by the servlet or a servlet filter accessing the request parameters. Only resource methods using #FormParam will work as expected. Resource methods consuming the request body by other means will not work as expected.
Turn logging off for the WebComponent in your logback.xml like so:
<logger name="org.glassfish.jersey.servlet.WebComponent" level="OFF" additivity="false"/>
Right.
So I've been suffering this issue, and I've been trying to solve it on different ways, but I did't want to change my web.xml settings, just because if I was testing my application with Postman it worked perfect, but when it was being integrated with the webapp it fails with the mentioned issue (A servlet request to the URI {MY_URI} contains form parameters in the request body but the request body has been consumed by the servlet or a servlet filter accessing the request parameters. Only resource methods using #FormParam will work as expected. Resource methods consuming the request body by other means will not work as expected.)
So as #clijk mentioned, you only have to set your headers as:
"Content-Type":"application/json"
"charset":"UTF-8"
and voilá, the warning it's gone.
Thanks
In my case I've fixed this error when I've changed the Object Date to String in the method.
Error:
#POST
#Path("/myPath")
#Produces(MediaType.APPLICATION_JSON)
public List<MyObject> myMethod(#FormParam("StartDate") Date date) throws Exception {
Fixed
#POST
#Path("/myPath")
#Produces(MediaType.APPLICATION_JSON)
public List<MyObject> myMethod(#FormParam("StartDate") String date) throws Exception {
Put this to your resource signature. Or find this string in your project someone already use this if #PUT or #POST is used. This should help
import javax.ws.rs.Consumes;
#Consumes(MediaType.APPLICATION_JSON)