transfer data to a servlet from a jsf page - java

I have an input in my jsf page like this
<html:inputText id="ResponseOK" value="#{bean.ResponseOK}" binding="#{bean.ResponseOKInput}" />
I want to get the value in a servlet (by request.getParameter ("ResponseOK")) when i click on a command button
<html:commandButton value="Valider" action="#{bean.callServlet}"/>
which call a function
public void callServlet()
{
String url = "http://localhost:8080/TestOne/Timers"; //servlet
FacesContext context = FacesContext.getCurrentInstance();
try {
context.getExternalContext().redirect(url);
}catch (Exception e) {
e.printStackTrace();
}
finally{
context.responseComplete();
}
}
Unfortunately, in my servlet the variable Ok , return only null
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String Ok = request.getParameter("ResponseOK");// return null
System.out.println(timerOk);
}
thank you very much

In order for you to be able to get a property from the request, the input must have the name attribute:
<html:inputText id="ResponseOK" value="#{bean.ResponseOK}" binding="#{bean.ResponseOKInput}" name="ResponseOK"/>
UPDATE:
I'm not too familiar with the JSF framework but i think your problem is the action button.
This button is not a submit button so the value of the input is not being sent to the request.
When calling a GET request, you need to pass the parameter in URL itself, so you need the url to look like:
http://localhost:8080/TestOne/Timers?ResponseOK=value
So you need to transfer the value of the ResponseOK input to the callServlet method.
Hope that helps.

Related

java: create and submit form from servlet and move to the target url

One of the webservices I am trying to connect requires me to submit a form to an url, lets say LINK_A.
I have a form view VIEW_A, I submit VIEW_A to my own servlet called SERVLET_A. Here in SERVLET_A from the form params, I generate a signature key, which is required by the webservice.
Then I need to submit to LINK_A programmaticaly from my servlet, BUT they told me that I need to submit it and redirects to LINK_A, so unlike what I've known so far (using httpclient httppost and getting the response data), I need to do something like a redirect with post data to their link.
So in summary:
1. from my view, submit a form
2. modify post data from servlet
3. submit the form to the webservice link and move to that link (as if the form from the view submit directly to the webservice link)
How can i do this?
If you need the form to be submitted from the browser (not from within your servlet using httpclient) your servlet needs to return a self-submitting form. E.g. use document.getElementById('myForm').submit() on documentReady.
If your form params can be submitted via GET you might also respond with a HTTP 302 redirect containing all params in the query string.
mean if you want collect request from previous form and check in servlet class and forward to new form den check this logic if its help
form code within servlet
rotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<html body=\"red\"> <center>");
pw.println("<form action=\"./NewFile.do\" method=\"get\">");
pw.println("<h2>enter the name </h2> <input type=\"text\" name=\"username\">");
pw.println("<h2>enter the password </h2> <input type=\"text\" name=\"passward\">");
pw.println("<input type=\"submit\" value=\"login\">");
pw.println("</form>");
pw.println("<center></body></html> ");
}
this below code to check and initialize path, before that you have to configure web.xml for this servlet class to behave as controller.
public class ServletControl extends HttpServlet {
#Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("inside the servlet");
String servletpath=request.getServletPath();
String path = null;
if(servletpath.equalsIgnoreCase("/NewFile.do")){
path="NewFile.jsp";
}
if(path!=null){
RequestDispatcher dis=request.getRequestDispatcher(path);
dis.forward(request, response);
}
}
}

How to send integer as parameter to servlet using $.ajax get?

I need to obtain an attribute from my Model project from my web application using java, but i need to send and integer as a parameter as well. I read the JQuery API Doc, but I'm very new to AJAX and JQuery and I still find it difficult to understand.
This is my code:
$(document).ready(function () {
// Locate HTML DOM element with ID "somebutton" and assign the following function to its "click" event...
$.get('ServletControlB', function (responseText) { // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
$('#divnombre').text(responseText); // Locate HTML DOM element with ID "somediv" and set its text content with the response text.
});
});
This is my ServletControlB doGet function:
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
int x; // x = parameter recieved from AJAX
//data is an instance from the Model class
String text = data.getNews().getNewsInPosition(x).getTitle(); //I send correct postition to my ArrayList
response.setContentType("text/html"); // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8");
response.getWriter().write(text);
}
How can I solve this problem? Is there a better way to approach this problem?
Try to use data object of jquery.get() like,
$(document).ready(function () {
$.get('ServletControlB',{id:1}, //<-- data object having id as key
function (responseText) {
$('#divnombre').text(responseText);
});
});
And in java use,
int x = Integer.parseInt(request.getParameter("id"));
You can parse the request parameter received as String to an Integer.
String x = request.getParameter("yourParameterName"); //get the parameter as String
int x1 = Integer.parseInt(x); //set the parameter here
As you are sending a GET request from jquery, so append query param in URL:
$.get('ServletControlB?yourparam=paramValue', function (responseText)
and you can retrieve in servlet doGet as mentioned here:
String yourParamValue = request.getParameter("yourparam");
$(document).ready(function () {
// Locate HTML DOM element with ID "somebutton" and assign the following function to its "click" event...
$.get('ServletControlB?x=' + valueOfX, function (responseText) { // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
$('#divnombre').text(responseText); // Locate HTML DOM element with ID "somediv" and set its text content with the response text.
});
});
in your controller do the following
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
int x = request.getParameter("x").toString() ;
//data is an instance from the Model class
String text = data.getNews().getNewsInPosition(x).getTitle(); //I send correct postition to my ArrayList
response.setContentType("text/html"); // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8");
response.getWriter().write(text);
}
I think you will have to change your front end like below.
$.get('ServletControlB',{ param: '1' }, function (responseText) {
$('#divnombre').text(responseText);
});

Render HTML response from remote call to the client

I have a working servlet wich originates back from this template:
http://www.objectdb.com/tutorial/jpa/eclipse/web/servlet
So the basic rountrip works.
I added a new feature where I POST data to the servlet, construct a call/request out of the data to a remote http server, retrieve the response-html-string (the content of the website I requested) and want to show this HTML String now as response to my original POST call.
I tried it like this:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
boolean showDetails = Boolean.valueOf(request.getParameter("showDetails"));
if (showDetails) {
String details = detailsLoader.loadDetails(String.valueOf(request.getParameter("value1")),
String.valueOf(request.getParameter("value2")));
response.getWriter().println(details);
response.getWriter().flush();
response.getWriter().close();
return; // <----------------- if showDetails then this is the end of doPost
}
// Display the list of guests:
doGet(request, response);
}
When I press the link that creates the POST event I see in the logfile, that "loadDetails" has succesfully loaded the content from the remote server, but the browser window does not refresh. Why?
PS: a simple redirect to the other side is not possible for technical reasons.
Try making a ajax request to your servlet which gives to html content as string sent it back to ajax call and set it to innerHTML of a div element.
I changed to use GET instead of POST and I used a separate Servlet for this kind of call. This solved my problem.
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String details = detailsLoader.loadDetails(String.valueOf(request.getParameter("value1")),
String.valueOf(request.getParameter("value2")));
response.getWriter().println(details);
response.getWriter().flush();
response.getWriter().close();
}

Reloading JSP page

I have an authorization frame displayed on every page and I want to keep that page displaying even if the user will choose to log in (using jstl tags i will simply put instead of this frame user info and link to shopping cart). How can i achieve that ? I have some ideas, but they all breaking out my controller design.
public class FrontController extends HttpServlet {
private ActionContainer actionContainer = ActionContainer.getInstance();
public FrontController() {
super();
}
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#SuppressWarnings("unchecked")
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String page = null;
try {
Action action = actionContainer.getAction(request);
page = action.execute(request, response);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(page);
dispatcher.forward(request, response);
} catch (ActionNotFoundException e) {
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(PageNames.ERR_PAGE);
request.setAttribute(AttributeNames.ERR_MESSAGE_ATTRIBUTE, "Unknown Action command: " + e.getMessage());
dispatcher.forward(request, response);
} catch (Exception e) {
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(PageNames.ERR_PAGE);
request.setAttribute(AttributeNames.ERR_MESSAGE_ATTRIBUTE, "Exception:\n" + e.getMessage());
dispatcher.forward(request, response);
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Front Controller";
}
#Override
public void init() throws ServletException {
super.init();
Locale.setDefault(new Locale("ru","RU"));
}
}
I was thinking about of redirecting to especially written for this case page, which will redirect to the original page, or to check page string for null and reloading from controller the original page, but i cannot clearly understand how to do this.
Your question isn't clear enough. But I think you're asking how you can replace a certain component on a page (Login button) with an other (username, welcome message and shopping cart details) after the user logs in.
If I understand your requirements, then what I would do after the user logs in is set a cookie (or a value in localStorage). The cookie is added to the Set-Cookie response header by means of the addCookie method of HttpServletResponse. Here's an example:
Cookie userCookie = new Cookie("user", "uid1234");
response.addCookie(userCookie);
Then in your controller simply check if the "user" value is set or not and take the appropriate action. A tutorial on servlets with cookies.
If you need to handle the front-end component, and change values on the form without reloading the page, I would recommend using javascript to do this, you can find and remove the old DOM elements with new ones (User's name, Welcome message, shopping cart, whatever).
If your iFrame is doing the login, then on successful login, have it call a function in your top window that does the update after reading the updated values from the cookie.
If you want to handle this completely at the front-end, i.e. Javascript, then I would skip using cookies and use localStorage instead. There is plenty of help on Stackover and on the internet about what localStorage is, but I will suggest the YUI Storage Lite library which makes storing and loading data from localStorage very simple.
Regards,
Include the current URL as a hidden field of your authentication form. In the action handling the authentication, once the user is authenticated, redirect to this URL.
In the JSPs, test if the user is authenticated and include the authentication form or the shopping cart. This test can be done by just putting a boolean value in the HTTP session once the user is authenticated.

how to stop servlet?

I have a servlet that looks like this:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
String param1 = request.getParameter("param1");
String param2 = request.getParameter("param2");
validateInput(param1, param2, request, response);
//if nothing's wrong with the input, do this and that
}
private void validateInput(String param1, String param2, HttpServletRequest request, HttpServletResponse response) throws IOException{
boolean fail = false;
//validate input blah blah blah
if (fail){
PrintWriter out = response.getWriter();
out.write("invalid input");
//end process or servlet
}
}
The idea is that I want to pass param1 and param2 to function validateInput() to validate whether or not the input is valid. If input is invalid, write a message back and then end the process. My question is how to end the process? I'm aware of that calling return; in doPost() will end the process but I'm trying to avoid returning any value from validateInput() to doPost() just for the sake of ending the process. I personally feel that it's more readable this way rather than returning true or false to doPost() and call return; there. Is there a way to do it? Or is it simply impossible?
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
String param1 = request.getParameter("param1");
String param2 = request.getParameter("param2");
if(!isValidInput(param1, param2)){
PrintWriter out = response.getWriter();
out.write("invalid input");
return;
}
//if nothing's wrong with the input, do this and that
}
private boolean isValidInput(String param1, String param2){
boolean fail = false;
//validate input and return true/false
}
Control will always return to doPost after validateInput runs unless you throw an exception (either an unchecked exception or IOException in this case).
So if you do not return ANY value from validateInput to doPost, even if you commit the response, doPost will still go on to do whatever it is supposed to do. (Of course, if the response is commited, the browser will be entirely unaware of any further activity on the server side).
You will need to return a value, throw an exception (which doPost may catch) or set a global value that doPost checks (which is just messy).
More sophisticated way would be .
validate and setAttributes to request if error found and forward request to jsp
on jsp check for the error attribute if any present display them
See Also
our Servlet wiki page, it explains it very well with example
What are you calling "the process"? That single request? If yes, then sending a message back DOES end the servlet's responsibility. HTTP is a request/response protocol.
If you mean stopping the servlet, that's not right. The servlet runs in the container, which is still going. It waits for the next request.
I don't see anything that merits stopping. Validation and routing back with errors is common.
Try this:
I changed your validate to return a boolean, so you can run an if statement on it in the doPost method. I also made it return a success instead of failure, just so the check makes more sense once you've returned.
response.sendError will allow you to do a generic error page (See this: http://blogs.atlassian.com/2007/07/responsesenderror_vs_responses/) instead of your output. If you want that you'll want setStatus (again, see the link).
The return should terminate execution and prevent the rest from happening, but it won't shut down the servlet like a system.exit(0) would.
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
String param1 = request.getParameter("param1");
String param2 = request.getParameter("param2");
if (! validateInput(param1, param2, request, response)){
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
//Or you can use this instead...
//response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
//PrintWriter out = response.getWriter();
//out.write("invalid input");
return;
}
//if nothing's wrong with the input, do this and that
}
private boolean validateInput(String param1, String param2, HttpServletRequest request, HttpServletResponse response) throws IOException{
boolean success = false;
//validate input blah blah blah
return success;
}
It sounds like you want to get a reference to the OutputStream to write HTML back to the client?
You can make use of response.getOutputStream() that would return a ServletOutputStream.
Once you have written to this stream, you need to finish. You will have to close() and flush() once you are done.
Whatever you write to this stream will be sent to the browser. Also remember to call the
response.setContentType("text/html"); so the browser knows its dealing with HTML.
have you tried with either one of the following
response.sendRedirect("some view.jsp");
(or)
System.exit(0); // which exits from the program

Categories