I can use Servlet, it is nothing wrong:
this is my Servlet code:
Configuration of web.xml:
But when I use HttpServlet, the mistake happened:
this is My HttpServlet code:
and this is Configuration of it:
I already inspect the things all i imagine.
I have found a lot of places that have no results,
I am a senior high school student in grade two,
If the text is in a mess, I'm sorry, I don't know why the pictures in here will be links. Whether you can help me or not, I still want to thank you for see it.
The problem is this line:
super.doGet(req, resp);
This is delegating to the default implementation of doGet provided by the HttpServlet class. The problem is that that version of doGet is version that is used when you don't implement your own doGet, and its behavior is to tell the remote client that GET is not supported by the servlet.
Solution: remove that call.
Related
I am using java ee 6 and trying to find out if it is possible to start a conversation from a servlet or a filter. so far I have the following code:
a method:
private static HttpConversationContext getHttpConversationContext() {
return Container.instance().deploymentManager().instance().select(HttpConversationContext.class).get();
}
and then i have :
final HttpConversationContext httpConversationContext = getHttpConversationContext();
httpConversationContext.associate((HttpServletRequest) request);
httpConversationContext.getCurrentConversation().begin(conversationId);
But this does not seem to work. Also when i try to check if the conversation began with the following code:
Conversation conversation = httpConversationContext.getConversation(conversationId);
the conversation is always null, since the previous code did not work.
Any clue how to do it in the right way?
Please note although jboss7 is used in the tag, i dont mind if the solution related to another server is posted, ie. wildfly.
Many Thanks.
If you want to do it in a Java EE fashion, then you should inject a Conversation Scoped Session bean into the Servlet.
I have implemented the OpenSessionInViewFilter for my MVC webapp and it works almost perfect. Only problem is that it also creates a session for every image, js, css etc that are requested from the webserver. This i dont want.
Im using struts2, spring and hibernate and this is my web.xml
<filter>
<filter-name>lazyLoadingFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>lazyLoadingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
So because i am mapping url-pattern /* it also takes all the images etc..
I tried setting it to *.jsp, and *.action, but then i get the lazyloading-exceptions again...
How should i do this? I've been looking for answers for 5 hours now and im getting a litle bit crazy in my head.
All i need to do is to make this filter IGNORE all the static resources. Thats it! And for everything else it can run. It sounds so simple, but its really really annoying me that i cant figure out how.
Any help would be greatly appriciated.
Do i need to extend the filter to write my own filter and exclude within it? And if so. How?
EDIT:
It seems like i could set up filter-mappings for my static files at the top of the filter-chain. And then send those to a "ByPassFilter", thus bypassing the filterchain for these static resources. Is this the way to go??
Thanks guys!
The general practice in such a scenario is to use the combination of Apache Web server with an application server (Tomcat/JBoss) with mod_jk module.
Here is link describing how to use this combination. (Another link)
The chief advantage of using this configuration is
Static content can be served by Apache web server.
The dynamic content requests (like *.jsp, *.action etc) are delegated to tomcat.
There are may other useful modules like content compression for static contents hence improving the response time.
Its more secure than the scenario wherein the app server is serving everything.
I understand this may not be precisely the solution you looking for, I suggested this as this is a general practice.
As far as your implementation of having a Bypassfilter is considered , if you have such a filter in front then once you skip the next filter in filter chain then basically the rest of filters in the chain will also get skipped (which doesn't seem to be a desirable thing to do in most situations ) . Also as the filter invocations for a request behave like
Filter1 -> Filter2 -->Struts Action/BL --> Filter 2 -->Filter 1
Hence the OpenSessionInViewFilter will kick in after the request is processed in your struts action ( which can be avoided by placing another bypass filter after open session in view filter in web.xml ) . However overall it has always appeared undesirable to me to skip the entire filter chain for skipping a single filter .
I haven't ever faced a need to skip OpenSessionInViewFilter ever , however if i had to do it then instead of having a Bypassfilter i would have a filter extending the OpenSessionInViewFilter filter which would be skipping my static resources from processing .
Include only those elements of the pattern that you need.
Something like this:
<filter-mapping>
<filter-name>lazyLoadingFilter</filter-name>
<url-pattern>*.html</url-pattern>
<url-pattern>/profile/edit</url-pattern>
<url-pattern>/cars/*</url-pattern>
</filter-mapping>
Just in case someone needs a solution with extending OpenSessionInViewFilter.
It prevents Hibernate session creation for pre-defined static resources.
/**
* Skips OpenSessionInViewFilter logic for static resources
*/
public class NonStaticOpenSessionInViewFilter extends OpenSessionInViewFilter {
static final Pattern STATIC_RESOURCES = Pattern.compile("(^/js/.*)|(^/css/.*)|(^/img/.*)|(^/fonts/.*)|(/favicon.ico)");
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String path = request.getServletPath();
if (STATIC_RESOURCES.matcher(path).matches()) {
filterChain.doFilter(request, response);
} else {
super.doFilterInternal(request, response, filterChain);
}
}
}
Basically Spring should have provided some property like excludePatterns for OpenSessionInViewFilter.
I totally agree with the answer from #Santosh.
the OpenSessionInViewFilter creates a resource and adds it the the ThreadLocal object, if the session is never used then the session is never actually created, this also means that a db connection is not used for that request. ( this is probably the answer to your question ).
If you still require to control things you can always create another filter extending the OpenSessionInViewFilter and execute the getSession method based on which resource is being called.
I've a third-party servlet inside a JAR that I cannot change. I've extended that servlet and been using it normally as a servlet should be used, the client side makes an HTTP request that invokes my servlet.
But now the client wants an automatic service, that is, I will need to do some requests to that third party servlet from the same webapp where the servlet is.
I looked at the the third party servlet code but I didn't found a place to bypass the servlet because the HttpServletRequest and HttpServletResponse objects are passed from method to method... Basically it seems that I would need to re-implement all the third party code.
Solutions I found but do not satisfy me:
Call servlet from URL with HttpURLConnection: My common sense says that calling the third party servlet from a url is not the best way to
go, besides the overhead added, I don't want to expose the third party
servlet. Calling my servlet from a url also brings problems with
sessions and other things.
Call the doGet directly: This seems to be out of the question because there is no implementation for the HttpServletRequest and
HttpServletResponse.
Use jMock or something like that: Didn't explore this solution yet, but it seams wrong to use a test-driven library in the real
environment.
Anyone has an idea how to interact with that third party servlet?
EDIT:
Since my English is not very good and I'm finding difficult to explain myself here goes a schematic to try to explain better
EDIT2: After a meeting the third party maker they offer to isolate the methods I need to avoid calling the servlet. If you don't have the same luck I did check out both gigadot and BalusC answers.
If I understand your question correctly, you have implemented or have a third party servlet that generate the report for you.
Now what you want to do is to periodically generate the report and store in session so that when user want to get the report they can retrieve it using another servlet.
If this is the case then you want the task to be running periodically on your server. You will need some sort of task scheduler to run on your server and what the task does is just make a http request to your servlet (this can be http GET or POST).
Calling my servlet from a url also brings problems with sessions and other things.
If that's the sole problem, then just use the CookieManager to maintain the cookies (and thus also the session) in subsequent URLConnection calls.
// First set the default cookie manager.
CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
// All the following subsequent URLConnections will use the same cookie manager.
URLConnection connection = new URL(url).openConnection();
// ...
connection = new URL(url).openConnection();
// ...
connection = new URL(url).openConnection();
// ...
See also:
Using java.net.URLConnection to fire and handle HTTP requests
You could try to separate out your servlet logic into several phases. The entry point that takes the request/result, the action that processes parameters sent and generates the output.
public void doGet(HttpServletRequest req, HttpServletResponse rsp){
relay(rsp,act(req.getParameter("a"));
}
public static String act(String a){
return "You provided: " + a;
}
public static void relay(HttpServletResponse rsp, String content){
rsp.setResponseCode(200);
rsp.getOutputStream().write(content.getBytes());
}
This lets you call act(whatever) to do what you want, and then do what you want with the response. If returning a string is not enough, you could make any return type you want, probably something that could contain a list of headers, response code, and content template.
I am just getting started on web app development. I have an index.jsp that has just ONE line.
< jsp:forward page="landing.do?"/>
What does
the above line do?
page="landing.do?" actually refer to?
what does the question mark "?" next to "landing.do?" signify?
As Bozho rightly pointed out, a servlet called "action" is mapped to handle "*.do" in my web.xml (as shown below).
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
Now
How do I find out what the servlet "action" corresponding to "landing.do" actually does?
Thanks.
The <jsp:forward> forwards a client request to the url declared on the page attribute.
I also need to mention that in your example, you should have a / as first character inside your page declaration, if you want to specify a relative URL, i.e.:
This, in effect, is translated as a redirection to (if localhost)
http://localhost:8080/MyAPP/landing.do? (yours would have been translated to http://localhost:8080/MyAPPLanding.do?)
The ? allows you to append application/x-www-form-urlencoded parameters into your declaration.
More info here.
To know what landing.do does, do the following:
Go to your struts-config.xml (found in WEB-INF folder in your project) file and find any action (<action>) that a path="/landing") attribute.
Once you find your action, there's an attribute called type (inside that action). The type is a the class name of the action class that Struts calls to execute the action. The class name is fully qualified name.
Open the java file of the class (if it exists) and depending on the action (Action, DispatchAction, LookupDispatchAction), you will have to find its mappings and see what method Struts invokes.
In your example, my assumption will be based that your landing.do is of type Action. Therefore, read what the execute() method does. All actions actually, is execute() by Struts. The other actions are just Template Method patterns that knows what method to call by some mapping.
you probably have a servlet mapped to handle *.do in your web.xml
the ? means nothing here - generally it marks the start of get parameters (like ?param=value)
forward changes the current page with the specified, without the client knowing the change has happened.
This line will forward user to another page of the site, in particular to landing.do
page="landing.do?" actually refer to some page of the site landing.do. I believe this page is written with Struts framework. (But can be other)
what does the question mark "?" next to "landing.do?" mean nothing in this case. Generally after "?" there should be a list of request parameters. In this cases there will just be no parameters.
Update:
You should find servlet class which is mapped to that servlet name. After that you will be able to try to understand what that servlet class does. Also, look at the Struts tutorials or specification to get understanding of Struts framework workflows.
sorry but I do not have the actual code with me, but I will try to explain:
I have a servlet mapped to the following:
/admin/*
So, this goes to a servlet:
public class AdminController extends MainController {
public void doPost(HttpServletRequest request, HttpServletResponse response) {
// Do stuf here
}
}
Here is MainController:
public class MainController extends HttpServlet {
#Override
public void service(ServletRequest request, ServletResponse response) {
String requesturi = ((HttpServletRequest)request).getRequestURI();
reqlist = Arrays.asList(requesturi.substring(requesturi.indexOf(Util.rootPath) + Util.rootPath.length()).split("/"));
reqlist = reqlist.subList(1, reqlist.size());
doPost((HttpServletRequest)request, (HttpServletResponse)response);
}
So, the request is passed to AdminController, no problem, but then I reallized something:
The servlet is being called twice!. And this is causing me many errors..
Does anybody have a clue on this? It is because I used some kind of heritance?
Thank you for all!
Though it is old thread but my answer may help someone.
Today I faced the same issue. My particular servlet is working fine earlier and suddenly it has started calling doGet method twice. On investigation, I found that my chrome browser has html validator extension which is calling the servlet again with same request to do html validation.
After I disabling the extension, the problem got resolved.
The HttpServlet.service method gets called for all request types and what you are seeing is a HEAD request and then a GET or POST request. Instead of implementing service just implement doGet or doPost. What is commonly done is to just implement one of doPost or doGet and then call the other from the one you don't have an implementation for.
I solved same problem with simple way.
If you are developing local and access to your app with address http://127.0.0.1 which is loopback network, change address to http://localhost which is direct.
This problem won't happen if you actually run it on webhosting or server and access to it from outer network.
Had the same issue, and I tried anything mentioned above and on other posts, but the issue was only on local.
If nothing works for you too, try a deploy :)
I had the same issue. I had a servlet to handle a post request.
But after calling doPost it suddenly started to call doGet method.
So the doGet was called by a chrome plugin that I installed (FireBug Lite).
Problem solved after I deactivated that plugin.