how to include Servlet request parameters to a new JSP page? - java

In the Java Servlet, how to include original paramters after response ?
Servlet
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String cmd = request.getParameter("cmd");
System.out.println("service , cmd="+cmd);
request.setAttribute("name", "John"+System.currentTimeMillis());
RequestDispatcher rd = request.getRequestDispatcher("process.jsp");
rd.include(request, response);
}
JSP
main ${name}<br>
cmd ${cmd}
If I want to include all paramters, like "cmd", to a new jsp page, how to do it ?
based on No.1, if I want to add NEW attributes, like "name" to a new jsp page, how to do it ?
In the above codes, use include or forward, the results are same. why ?
Thanks

If I want to include all paramters, like "cmd", to a new jsp page, how to do it ?
All request parameters are in EL available by the ${param} map.
${param.cmd}
You don't need to prepare anything in the servlet.
based on No.1, if I want to add NEW attributes, like "name" to a new jsp page, how to do it ?
You already did it by request.setAttribute("name", name) and ${name}.
In the above codes, use include or forward, the results are same. why ?
Not exactly. If you use include(), the delegatee would not be able to control the response headers. You should be using forward() in this case. See also the javadoc. You should use include() only if you want to append something before and after instead of fully delegating the request/response.
See also:
Our Servlets wiki page
How do I execute multiple servlets in sequence?

It's the same request, you don't need to do anything at all.
A forward means you can't have committed any response (no output to client). Include doesn't allow any response status code or header changes.
See the docs for forward/include.

you can access all the request params using the request.getParameterMap() another question which can help you method, this returns a map of all params (key-value pair) which you can iterate and set the attribute.
request.setAttribute("name", "John"+System.currentTimeMillis());
What you've done here does add a new attribute called name (provided another entry doesn't exist with the key as name).
The result of include and forward are the same as
you are not adding any specific content to the response
when you forward a request, you are forwarding the control to handle the response to another component (in your case process.jsp)
when you include a jsp in your request, you are executing the included component and have the option of adding something extra to the stream (which you aren't doing).
thats why both the actions show you the same result.

Related

Redirect to another servlet in java

I am having troubles of directing to another servlet in a servlet file. I have a servlet file called NewDreamServlet.java and I want to redirect it to MyDreamsServlet.java.
This is what I currently have in the NewDreamServlet.java for redirecting.
request.getRequestDispatcher("/MyDreamsServlet").forward(request, response);
When I call this it ends up going to a blank page,
http://localhost:8080/ps10-austint/NewDreamServlet
How exactly would I accomplish this? Please let me know if there is any misunderstanding.
Did you try: response.sendRedirect("/YourApp/MyDreamsServlet")
Please try response.sendRedirect("/MyDreamsServlet"). Also, please note that you might have to add an return statement. The following post discusses this in more details java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed
All these answers to your question are wrong.
1. if you like to use RD().forward, which is more used for with in application calls, all you need to do is go to your web.xml file and for the url part of your 2nd servlet give it any name you would like eg. /fireServletTwo....
Now come back to your 1st servlet and in the getRqstDispatcher braces, write("/fireServletTwo"); this will tell the xml file to look for a servlet mapping with that name and run that servlet.
2. if you would like to use send.Redirect(); which takes a URL and is used to mostly pass controls outside of the application to another domain, its simple.. DO NOT USE A SLASH /.... just write the name of your servlet2 inside "";
Hope that helps
This one works for me but it usually better to have the context path:
response.sendRedirect(request.getContextPath() + "/home.jsp");

forwarding with RequestDispatcher after going through Java Filter

First of all let me describe what I'm trying to do, which I'm guessing is pretty simple.
I have a website with users and want to restrict access to a view_profile.jsp page only to logged users. I have a filter mapped to:
<url-pattern>/auth/*</url-pattern>
which looks like this
try {
HttpSession session = ((HttpServletRequest)request).getSession();
UserBean user = (UserBean)session.getAttribute("currentUser");
if (user != null && user.isValid()){
System.out.println("Filter: context -> " + ((HttpServletRequest)request).getContextPath()); //returns ""
chain.doFilter(request, response);
}
else{
((HttpServletResponse)response).sendRedirect("/login.jsp"); //works fine
}
This filter is run when on the index.jsp page user will click on a link:
<a href="./auth/view_profile?profile=${sessionScope.currentUser.username}">
//yeah, he will 'view' himself - it's just an example
which is suppose to take the user to the servlet mapped to ViewProfileServlet mapped to:
<url-pattern>/auth/view_profile</url-pattern>
which looks like that:
try {
String username = (String) request.getParameter("profile");
// here is getting info from database and setting request attributes
// works fine
//response.sendRedirect("/view_profile.jsp");
System.out.println("ViewProfileServlet: In context -> " + getServletContext().getContextPath()); // returns ""
dis = getServletContext().getRequestDispatcher("/view_profile.jsp");
// i've tried request.getRequestDispatcher. no difference
System.out.println("ViewProfileServlet: forward to '/view_profile.jsp'");
dis.forward(request, response);
}
Which in turn should take the user to the /view_profile.jsp (in the root context, not in /auth) and work, which it doesn't. What happens is the ViewProfileServlet runs and the view_profile.jsp shows, although it seems that the context is still /auth because all the links on view_profile.jsp point to i.e localhost:8080/auth/some-page.jsp. Also, css files are not being loaded, they're not even requested (at least according to firebug), and page source shows 404 Glassfish Error where css's suppose to be.
I would greatly appreciate any help, it's the first time i'm even doing something in jsp and i'm completely lost here.
A forward happens entirely at server-side. The browser doesn't know about it. When it sends a request to /auth/view_profile, and receives HTML from this response, he doesn't care if the HTML has been generated by a servlet, a JSP, both, or anything else. It reads the HTML and considers it comes from the path /auth/view_profile. All the relative path in the HTML are thus relative to /auth/view_profile.
It's far easier to use absolute paths to reference images, JS and CSS paths (and even other actions, most of the time). Just make sure to use the <c:url> tag to generate the URL, so that the context path of the web-app is prepended:
<script src="<c:url value='/js/myScript.js'/>" type="text/javascript"/>
^-- the slash here makes the path absolute.

How to add a parameter to the existing HttpServletRequest of my Java Servlet?

I want to add a new parameter to the parameter map of my HttpServletRequest.
The following code
request().getParameterMap().put("j_username", user);
request().getParameterMap().put("j_password", pwd);
creates this error
no modifications are allowed to a locked parameter map
What is the correct way to do this?
The parameters of a request are the values sent as parameters by the browser. There is no reason to change them. If you want to associate some value to the request, use an attribute rather than a parameter. This has the additional advantage that an attribute may be any object and not just a String:
request.setAttribute("user", new User(userName, password));
You may add parameters if you forward the request to another resource (although I wouldn't say it's a good practice):
request.getRequestDispatcher("/some/path?j_username=" + user + "&j_password=" + pwd).forward(request, response);
The parameters should be encoded correctly, though.
I ran into a similar issue and got around it by making a copy of the parameter map.
Map<String, String[]> params = new HashMap<String, String[]>(req.getParameterMap());

Wicket: how to render page programmatically and get result as string?

I'm in the process of converting an app to use i18n/l10n on all its pages. I'm very happy with Wicket's support for this, and it's going well so far. The one tricky part I've run into is the following:
We have a text file that is used as an HTML template to send email when users perform a certain operation on the site. When the user clicks a particular link, I read in this template manually, do some text substitutions like "Dear $USERNAME", and send the result as an HTML email to the user.
In order to support the 10 or so languages we're targeting, I'll either have to maintain 10 copies of this template file, or figure out a way to render this "page" using Wicket's built-in i18n support, grab the result as a string, and then send it.
Hence my question: how can I "render" a Wicket page programmatically and get the result as a string?
I'd prefer to avoid hacks like using HttpClient if at all possible; HttpClient won't have the user's Locale, won't be automatically logged in as the user, etc., so that doesn't seem like a good solution to me.
Two article regarding to this:
Render a Wicket page to a string for HTML email
Rendering Panel to a String
Currently the only other approach was using WicketTester for that, but I do not remember details how to do that.
If you just want the raw code, here it is: (This is practically the same as the solution described in the article.)
//I assumed that you want to use the current user's session for rendering. If this isn't the case, you'll have to use a mock session
MockHttpServletRequest mockReq = new MockHttpServletRequest( WebApplication.get(), ((WebRequest)getRequest()).getHttpServletRequest().getSession(), WebApplication.get().getServletContext() );
MockHttpServletResponse mockRes = new MockHttpServletResponse( mockReq );
WebResponse res = new WebResponse(mockRes);
ServletWebRequest req = new ServletWebRequest( mockReq );
RequestCycle cycle = new WebRequestCycle( WebApplication.get(), req, res );
PageParameters pp = new PageParameters();
//add page parameters here
//Your email page should really be a bookmarkable page, but if it isn't, you can replace the request target with something that better suits your case
cycle.request( new BookmarkablePageRequestTarget( EmailPage.class, pp ));
System.out.println( mockRes.getDocument() );
For newer Wicket versions: 6.7.0 came with a new ComponentRenderer precisely for this purpose!

Product browse in Java Servlets

I am creating a web application using EJBs and servlets. I have a page which displays a list of all items in the database. I would like to provide an option for the user to click on one of these items and this opens the SHOW servlet which gathers info regarding the item onto the page. I do not want to create a page for every single item. Instead I would like to create ONE SHOW servlet which can be used for all items. I am not sure how to provide this option through clicking on the name of an item, and also how to send the parameters...since it depends on what item the user chose.
Can someone help me please?
Thank you
When you generate the product listing, you can just make the IDs of all the database items parameters in the link.
Product Foo
Then in the doGet() method of your ShowProduct servlet, you can call the HttpServletRequest.getParameterValues() method to get that parameter's values and do the lookup in your database.
e.g.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String[] params = request.getParameterValues("productID");
String productID = params[0];
...
}
Pass the unique ID of the item into the SHOW servlet. Then get that item's data from the DB and create your new page with that data.
Try having the show link point to your show servlet like this:
"/ShowServlet?itemID="+itemID

Categories

Resources