Servlets, How to make server available by the name in annotation? [duplicate] - servlets

This question already has an answer here:
How to set my webapp to appear as ROOTfor localhost:8080
(1 answer)
Closed 1 year ago.
I'm only starting to learn Servlets.
I have a simple template code below.
I thought that after writing annotation "#WebServlet("/hello-servlet")" my page will be available by the URL "http://localhost:8080/hello-servlet".
The problem is that it is not available by that adress only by "http://localhost:8080/demo_war_exploded/".
I do know that the problem is connected with Tomcat configurations. In settings it is said that url is "http://localhost:8080/demo_war_exploded". And deployment is "war exploded".
How can I make the server available by the name in annotation?
#WebServlet("/hello-servlet")
public class HelloServlet extends HttpServlet {
private String message;
public void init() {
message = "Hello World!";
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
// Hello
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>" + message + "</h1>");
out.println("</body></html>");
}
public void destroy() {
}
}

I found out the answer - you just need to delete application context from deployment

Related

How to read the following path from a servlet? [duplicate]

This question already has answers here:
Servlet and path parameters like /xyz/{value}/test, how to map in web.xml?
(7 answers)
Closed 1 year ago.
I have a servlet which works on organizations address (#WebServlet("/organizations")). This way using GET or POST method on address .../organizations leads to calling of this servlet. When I need to work with a current organization (for example, 12th), I should call .../organizations/12. This way I can write #WebServlet("/organizations/*"), but how to read this number (12 in this case)? Or can I replace it with a variable somehow like #WebServlet("/organizations/{orgNumber}") (this variant didn't work)?
You did not give us your code, but you can use the request object and string operations to find the part of the request URI you are looking for.
#WebServlet("/organizations/*")
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
// split the complete URI by /
final var split = request.getRequestURI().split("/");
// ...
// or use substrings
final var partOfPath = request.getRequestURI().substring(20,30);
// ...
// or use pathInfo to split only the path following the domain
final var split = request.getPathInfo().split("/");
// ...
}
}
You could map it on /organizations/* and extract information from getPathInfo():
#WebServlet("/organizations/*")
public class OrganizationsController extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String[] pathInfo = request.getPathInfo().split("/");
String id = pathInfo[1]; // {id}
String command = pathInfo[2];
// ...
//..
//.
}
}

Servlet 404 the requested resource [/ServletDemo/AddServlet] is not available [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 2 years ago.
I just started learning about Servlets. I followed the basic steps to create a new servlet project:
File -> new -> Dynamic Web Project -> new -> Servlet (AddServlet) with a basic print statement in the doGet()
package com.demo.servlets;
//all of my imports
#WebServlet("/AddServlet")
public class AddServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public AddServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().print("Hello");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
I'll I've done is make the servlet but I can't get past this step. I've looked at a million tutorials and stack overflow answers. I made sure Tomcat 9.0 was installed and connected to my project correctly, made sure the servlet version was 4.0, made sure my build path was correct, made sure that my servlet was in a package.
I've also even tried using web.xml instead of the web annotations but I get the same 404error. . Ive been working on this for the past 72 hours, and I don't understand what the problem is.
You need to override doGet and doPost from HttpServlet. For this reason you need to add #Override annotation above the doGet and doPost.

Servlet Response wrapper to add getHeaderNames and getHeaders methods to Servet 2.4 spec container not working

Since Servlet 3.0, HttpServletResponse#getHeaderNames() and HttpServletResponse#getHeaders() has been available. However, I'm using an older spec, specifically Servlet 2.4.
Having looked at the resource, How can I get the HTTP status code out of a ServletResponse in a ServletFilter?, I got an idea of how to write a wrapper. If I understand it right, I have to use setHeader() to facilitate the creation of getHeaderNames() and getHeaders(). I think I have a solid footing on how to store the headers to simulate the usage of these missing methods.
The problem is the filter which leverages this wrapper does not seem to be calling setHeader() automatically. I don't get it. I presume sincegetStatus() is working properly, I'm expecting setHeader() to behave in the same fashion. Specifically, I'm looking to print out all the response headers, after calling chain.doFilter(). I'm not sure what I'm doing wrong here. Maybe there is something wrong with how I'm storing header name-value pairs.
I would appreciate any help. Thank you.
public class ServletResponseWrapper extends HttpServletResponseWrapper {
private int httpStatus = SC_OK;
private HashMap<String, String> hashMapHeaders = new HashMap<String, String>();
public ServletResponseWrapper(HttpServletResponse response) {
super(response);
}
#Override
public void sendError(int sc) throws IOException {
httpStatus = sc;
super.sendError(sc);
}
#Override
public void sendError(int sc, String msg) throws IOException {
httpStatus = sc;
super.sendError(sc, msg);
}
#Override
public void setStatus(int sc) {
httpStatus = sc;
super.setStatus(sc);
}
public int getStatus() {
return httpStatus;
}
#Override
public void sendRedirect(String location) throws IOException {
httpStatus = SC_MOVED_TEMPORARILY;
super.sendRedirect(location);
}
#Override
public void setHeader(String name, String value) {
hashMapHeaders.put(name, value);
super.setHeader(name, value);
}
public String getHeader(String name) {
return hashMapHeaders.get(name);
}
public Enumeration<String> getHeaderNames() {
Enumeration<String> enumerationHeaderNames = Collections.enumeration(hashMapHeaders.keySet());
return enumerationHeaderNames;
}
}
public class ServletResponseWrapperFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
ServletResponseWrapper servletResponseWrapper = new ServletResponseWrapper( (HttpServletResponse) response );
chain.doFilter( request, servletResponseWrapper );
// Process response
// This works, even though I never explicitly call the setStatus() method
int status = response.getStatus();
// This returns NULL because no header values get set; I presume setHeader() gets called implicitly
Enumeration<String> headerNames = servletResponseWrapper.getHeaderNames();
}
public void init(FilterConfig config) throws ServletException {
//empty
}
public void destroy() {
// empty
}
}
web.xml file
<display-name>Tomcat App</display-name>
<filter>
<filter-name>ResponseHeadersFilter</filter-name>
<filter-class>com.company.filters.ResponseHeadersFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ResponseHeadersFilter</filter-name>
<url-pattern>/testfilter.jsp</url-pattern>
</filter-mapping>
I took the vendor's servlet out of the equation. The filter now fires on an empty JSP file. Tomcat is also hooked to a front-end web server, IIS. I disabled IIS. Now, I'm accessing the website directly over Tomcat, via port 8080. Despite all this, I dot see any response headers.
Using Fiddler, the response headers I see are few but existing, namely:
(Cache) Date
(Entity) Content- Length, Content-Type
(Miscellaneous) Server
And status response, i.e. HTTP/1.1 200 OK
I can get by without getting response headers in the filter. But the big question I have is this is a bug with Servlet version 2.4 or is there some kind of OS Server and/or Tomcat configuration change I need to enable? Unless there's some Tomcat configuration, I'm led to believe this is likely a bug. Perhaps a clean install using the default configuration of the Tomcat version I'm using, 5.5.28, would resolve the problem, but I cannot attempt that at this time.

Lifecycle/Scope of #WebServlet [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do servlets work? Instantiation, session variables and multithreading
I have a weird (but probably expected) behaviour in my WebServlet. Environment is:
- Apache 2.2.x
- Glassfish 3.1.1 + mod_jk
- JSF Mojarra 2.1.3
I have an abstract servlet that implements some code to check in the FacesContext/Session if there is a specific #SessionScoped managed bean and if so, whether the user is signed-in. If user is signed-in, then proceeds to the file delivery. The implementing #WebServlet only provides the actual file download.
Abstract Servlet:
public abstract class SecureDownloadServlet extends HttpServlet {
#EJB
private UserProductBean userProductBean;
private UserInfoView userInfoView = null;
private UserInfoView getUserInfoView(HttpServletRequest req) {
FacesContext context = FacesContext.getCurrentInstance();
if (context != null) {
userInfoView = (UserInfoView) context.getApplication()
.getELResolver().getValue(FacesContext.
getCurrentInstance().getELContext(), null, "userInfoView");
}
if (userInfoView == null) {
userInfoView = (UserInfoView) getServletContext().
getAttribute("userInfoView");
}
if (userInfoView == null) {
userInfoView = (UserInfoView) req.getSession().
getAttribute("userInfoView");
}
return userInfoView;
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse response)
throws IOException, ServletException {
if (getUserInfoView(req) == null || !getUserInfoView(req).getLoggedIn()) {
response.sendRedirect("message.xhtml?msg=noLogin");
return;
}
doDownload(req, response);
}
public abstract void doDownload(HttpServletRequest req,
HttpServletResponse response)
throws IOException, ServletException;
}
Then I have a #WebServlet that extends the above abstract HttpServlet and implements the abstract method:
#WebServlet(name = "SecureImageServlet", urlPatterns = {"/print","/m/print"})
public class SecureImageServlet extends SecureDownloadServlet {
#Override
public void doDownload(HttpServletRequest req, HttpServletResponse response)
throws IOException, ServletException {
// some code
}
}
Now here is the issue:
- From computer A, sign in, then call the SecureImageServlet servlet to get a file (i.e. http://www.example.com/print?id=12345). The userInfoView session bean is initialized as expected, and the file is delivered.
- From computer B, without being signed-in, call http://www.example.com/print?id=12345. The userInfoView is already initialized with the session of user on computer A!!! And the file is delivered too.
It looks like the WebServlet becomes ApplicationScope or something like that. Is it the #EJB injection that does that?
Note the the instance of userInfoView is the same (the object id in the debugger shows the same number) which means somehow the computer B is seen as the same user as computer A
Edited format
Ok, a friend of mine (without an account on SO :) ) pointed out my mistake:
I am using userInfoView as a class member instead of keeping it within the request scope. I fixed it by removing the class member and voila!

PlayN.Net returning empty String in HTML

I can't understand the problem im having with PlayN.net. Maybe it's trivial, but since im new to web based stuff, I'm kinda stuck, so I hope someone here can enlighten me :)
My problem: I would like to acess a servlet from my game, it works, but only in java. Html gives me back an empty string.
Simple Servlet:
public class Servlet1 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter writer = response.getWriter();
writer.println("test");
writer.close();
}
}
and simple call:
PlayN.net().get("http://localhost:8080/Test", new Callback<String>() {
#Override
public void onSuccess(String result) {
System.out.println("YAY "+result);
}
#Override
public void onFailure(Throwable cause) {
System.out.println("BUH");
}
});
So like I said, java prints "YAY test", HTML prints "YAY" and I cannot figure out why.
I tried running the servlet on an other server (not localhost) but the same reaction.
Anyone an idea what I'm doing wrong?
In the browser (HTML) you have to work with the 'Same origin policy': See http://en.wikipedia.org/wiki/Same_origin_policy
Suggested solutions and work-arounds:
Collaboration from PlayN client with server
Why net().get on success return empty string

Resources