calling servlet from action class - java

I am calling a servlet from an action class by using forward. It is then going to the servlet but it is not showing the output.
Actually I have create a PDF file which I need to show it on runtime. If I run that servlet only on server then it is showing the PDF file I want to.
But if I forward it from the action class it is not not showing anything.
I have given a simple condiiton on the action class like this:
if(id.equals("SGSY"))
{
forward = mapping.findForward("SGSY");
}
else
{
forward = mapping.findForward("fail");
}
After this it is going to servlet but not actually showing the output. I don't understand why. Am I doing something wrong?

Try response.sendRedirect 1st instead of forward mapping,if it works it means there must be problem with your path

Related

javascript called but not loaded on page

I am putting in changes to a tool we use, and I'm having trouble getting local javascript files to load in. The jquery library link works perfectly fine:
builder.append("<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>");
But js files stored within the project seem to be returning blank pages.
builder.append("<script src='/SessionInfo/js/session.js'></script>");
The project uses a custom controller that routes requests based on the uri, heres a snippet:
if ( lowerCaseUri.matches("/sessioninfo/v1/userid/?") ) {
UserIDHandlerV2.handleUserIdPrompt(output);
} else if ( lowerCaseUri.matches("/sessioninfo/v1/userid/.*") ) {
UserIDHandlerV2.handleUserIdSessionListDisplay(request, output);
} else if ( lowerCaseUri.matches("/sessioninfo/js/.*") ) {
response.setContentType("text/javascript");
}
Looking at fiddler and chrome tools, it shows 200 responses returning the correct content type, but 0 bytes are transferred and in resources/scripts it shows blank pages.
I would suggest, get rid of the "custom controller that routes requests based on the uri," and use a URL Rewrite filter like Tuckey Urlrewrite Filter
Your problem is obviously that your custom controller doesn't work. For one thing, look at this:
else if ( lowerCaseUri.matches("/sessioninfo/js/.*") )
{
response.setContentType("text/javascript");
}
If there is a request for a javascript file, all you are doing with that request is setting the content type to javascript. You aren't reading the javascript file and serving it.
What you are doing is trying to build your own url-rewriting, and that's not necessary.
You could also just take /sessioninfo/js/.* out of your controller. I'm assuming these are just normal .js files, right? So why are you using a controller to route them? The purpose of a controller is when you need to put backend information on a view, so you send the user to the controller (i.e. a servlet) first and then controller sets request attributes and then forwards to a JSP that simply displays them.
Use HttpServletRequest#getContextPath to append those sources:
builder.append("<script src='" + request.getContextPath() + "/SessionInfo/js/session.js'></script>");

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

Why getRequestDispatcher("/index.jsp").forward() dont work with JSP?

I try to redirect my page to another using request.getRequestDispatcher("/index.jsp").forward(request, response); . But it dont work. Why? But when I change it to response.sendRedirect it work fine.
I think the problem might be because of not using relative url.
You can try like this
request.getRequestDispatcher("index.jsp").forward(request, response);
I think you do need the forward slash with the JSP filename.
This is just a small possibility (need more info) - but do you have an init() method in your servlet?
If you do, you must call super.init(servletConfig) as the first line of your init() method, or you might get a NullPointerException when you try to forward.

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.

Grails redirects to wrong address when using app.context?

I'm noticing some odd behavior with redirect when I set my app.context a certain way. I found a bug in the Grails JIRA which describes my problem perfectly, but it was marked as UTR: http://jira.grails.org/browse/GRAILS-7546
Here is my description of the problem:
I'm currently using Grails 2.0M2. I have the following properties defined in my application.properties file:
app.context=/
app.name=foobar
When I call redirect in a controller, redirect is adding the app name onto the uri I provide, which then causes a 404. Here is how I'm doing this:
String partialUrl = createLink(mapping: 'helloworld') // returns `/hello/world`
redirect(uri: partialUrl) // INCORRECTLY redirects to
// `http://mysite.com/foobar/hello/world`
// instead of `http://mysite.com/hello/world`
Assume that I have a URL mapping named helloworld defined in my UrlMappings.groovy file with a path of /hello/world.
So, long story short, if I set the app.context to /, I would NOT expect the app.name to show up in my final redirect URL.
Is this a bug or expected behavior? Any idea on the easiest way I could build up the redirect URL without doing too many manual steps?
I hate to say it, but I cannot reproduce it either. I created a test project with one controller (named Hello), using your code to create an action that does nothing but redirect:
HelloController.groovy
package test1
class HelloController {
def index() {
def model = [:]
model.content = 'content...'
model
}
def redir() {
String partialUrl = createLink(mapping: 'helloworld') // returns `/hello/world`
redirect(uri: partialUrl) // INCORRECTLY redirects to
// `http://mysite.com/foobar/hello/world`
// instead of `http://mysite.com/hello/world`
}
}
I created an index page, index.gsp in the views/hello
index.gsp
<h1>index.gsp</h1>
<html>
<body>
<p>This data is coming from the model:</p>
<p>content: ${content}</p>
</body>
</html>
Setup helloworld in the UrlMappings to map to the index action of the hello controller:
UrlMappings.groovy
class UrlMappings {
static mappings = {
"/helloworld"(controller: "hello", action: "index")
"/$controller/$action?/$id?"{
constraints {
// apply constraints here
}
}
"/"(view:"/index")
"500"(view:'/error')
}
}
And changed the application.properties to have the app.context=/
application.properties
#Grails Metadata file
#Sun Nov 06 14:51:56 EST 2011
app.grails.version=2.0.0.RC1
app.context=/
app.name=test1
app.servlet.version=2.5
app.version=0.1
When I ran the app, I could go to localhost:8080/hello and it would show my simple GSP. I tried localhost:8080/helloworld and also got it as expected per the mapping. Then I tried localhost:8080/hello/redir and I was properly redirected to localhost:8080/helloworld.
However, if you're still facing this issue, I have a few suggestions
1) Try using the new link generator available in 2.0 instead of createLink. It may not do anything different, but worth a try: grailsLinkGenerator.link(mapping: 'helloworld')
2) If it's only on redirects from within controllers, you could just add the http://mysite.com portion yourself to the partialUrl.
3) Last resort, write a Filter attached to afterView that does a regex search and replace on the contents for mysite.com/foobar. Not sure this will catch redirects though, but if anything would, I'd assume this would be it since filters can be applied at broad level.
def yourAction = {
redirect(uri:"helloworld")
}
That doesnt work for you?
It's not a direct anwser to your question but my practice is : I never modify app.context in the grails properties since tomcat override it on production and I don't care which context it uses on my dev.

Categories

Resources