Apache Tomcat and servlet [duplicate] - apache

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
I've been struggling with a servlet in the maven web application for hours. I'm not able to run it. It always returns The requested resource is not available. I'm using Tomcat 8. This is my servlet code. I'm using this address http://localhost:8080/my-app/MyServlet to run it but I'm not successful.
#WebServlet(name = "MyServlet", urlPatterns = {"/MyServlet"})
public class MyServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet MyServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet MyServlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
}

Check if your tomcat works fine by using http://localhost:8080 (Tomcat welcome page is shown )
Check if your context path is "/my-app", "/" or something else. e.g. if you context path is just /, http://localhost:8080/MyServlet should work.

Related

url was not normalized error when using intellij but not when using STS

The developed website works fine on remote server and local machine (when using STS IDE) , recently I started use Intellij IDEA (I created a duplicate of the website code with no any changes ), I started getting the URL was not normalized error.
Does intellij handles Spring security somehow differently than STS ? or what could be the cause?
I don't want use custom httpfirewal .
#EnableGlobalMethodSecurity(prePostEnabled=true)
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider())
.jdbcAuthentication()
.usersByUsernameQuery(usersQuery)
.authoritiesByUsernameQuery(rolesQuery)
.dataSource(dataSource);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
// URLs matching for access rights
http.authorizeRequests()
.antMatchers( "/", "/contact","/register").permitAll()
.antMatchers("/accounts").hasAnyAuthority("SUPER_USER","ADMIN_USER")
.anyRequest().authenticated()
.and()
// form login
.csrf().disable().formLogin()
.loginPage("/index")
.failureUrl("/index?error=true")
.defaultSuccessUrl("/user")
.usernameParameter("email")
.passwordParameter("password")
.and()
// logout
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/").and()
.exceptionHandling()
.accessDeniedPage("/access-denied");
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**");
}
and this is from the properties :
# Spring MVC view prefix.
spring.mvc.view.prefix=/templates/
# Spring MVC view suffix.
spring.mvc.view.suffix=.html
the error is :
org.springframework.security.web.firewall.RequestRejectedException: The request was rejected because the URL was not normalized.
P.S: I'm using JDK8 ,Spring Boot 2,Spring Security ,thymeleaf,intellij U 2019.2
org.springframework.security.web.firewall.RequestRejectedException: The request was rejected because the URL was not normalized.
Which IDE to use should not have any differences for running the same source codes on the embeddable server configured by springboot. This error happens when the HTTP requests that send to server is not normalised which the URL contains character sequences like ./, /../ , // or /. So I doubt that it is due to you are using different URL to browse the app. For example, you are accidentally adding a '/' in the URL such as http://127.0.0.1:8080/app//index.html
You can change to use a less secure HttpFirewall to avoid such checking by :
#Override
public void configure(WebSecurity web) throws Exception {
web.httpFirewall(new DefaultHttpFirewall());
//another configuration .....
}
P.S. Though it is called DefaultHttpFirewall , it is not the default HttpFirewall used by Spring Security since 4.2.4 which is less secured than the actual default StrictHttpFirewall

Tapestry: How to redirect deprecated URLs to an error page

I have legacy web application built using apache Tapestry. I have deprecated most of the application's functionality except few pages. I want this application to be running in production, but I want to redirect deprecated pages/URLs to some error page with 404 error code. Where should I configure it? I have web.xml and jboss-web.xml. Do I need to do it in some Tapestry configuration file?
You can contribute a RequestFilter to the RequestHandler service, i.e. in your AppModule:
public void contributeRequestHandler(
OrderedConfiguration<RequestFilter> configuration)
{
// Each contribution to an ordered configuration has a name,
// When necessary, you may set constraints to precisely control
// the invocation order of the contributed filter within the pipeline.
configuration.add("DeprecatedURLs", new RequestFilter() {
#Override
public boolean service(Request request,
Response response,
RequestHandler handler) throws IOException
{
String path = request.getPath();
if (isDeprecated(path))
{
response.sendError(404, "Not found");
return;
}
return handler.service(request, response);
}
}, "before:*");
}
Notice the before:* ordering constraint, it should register this filter as the first in RequestHandler's configuration.

How can i add response header to a pdf in CQ5

I am trying add canonical tags to PDF and for that i have to update response header when PDF is loaded. I was able to add header for cq:page very easily:
#SlingServlet(
resourceTypes = "cq:Page",
extensions = "html",
methods = "GET")
#Properties({
#Property(name = "service.description", value = "Servlet to handle all incoming widget modification")
})
public class canocalizePDF extends SlingAllMethodsServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
response.addHeader(“canonical", “test");
}
#Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
}
}
But when i try to same for PDF, it is not working. I have tried dam:Asset, dam:AssetContent as resourceTypes, but nothing seems to be working.
Any help would be great.
Thanks,
Vishal
The servlet that you've written is not handling your asset requests. If you want to handle this in AEM, you will need to override the OOTB AEM's AssetDownloadServlet with your own servlet implementation. You can then add the canonical link header in your servlet response.
How to override this is explained in detail in this blog post. They've also included a link to sample code for this customization.
However, if you have a webserver (e.g. Apache) in your setup, you should really handle this there. This is shown in this Moz blog post. Moz is the pinnacle of SEO best practices. I will recommend that.

JASPIC Login with Wildfly 9 Send HTTP Return Code

I'm still trying to implement a custom JASPIC login module for Wildfly 9. If the login is successful everything works as expected. But I would expect an HTTP 403 response, if the login is not successful. So I wrote this little test:
#Test
public void invalidCredentials() throws IOException, SAXException {
try {
WebConversation webConversation = new WebConversation();
GetMethodWebRequest request = new GetMethodWebRequest(deployUrl + "LoginServlet");
request.setParameter("token", "invalid");
WebResponse response = webConversation.getResponse(request);
fail("Got " + response.getResponseCode() + " expected 403!");
} catch (final HttpException e) {
assertEquals(403, e.getResponseCode());
}
}
The result is this:
Failed tests:
JaspicLoginTest.invalidCredentials:114 Got 200 expected 403!
I tried this three options to end the method validateRequest of the ServerAuthModule after invalid authentication:
return AuthStatus.SEND_FAILURE;
return AuthStatus.FAILURE;
throw new AuthException();
But none of the above produce a authentication failure HTTP response (403). Is this a Wildfly bug again? Or do I have to produce this return code in an other way?
Ok, obviously one can take the MessageInfo object and can do such like:
public AuthStatus validateRequest(MessageInfo messageInfo,
Subject clientSubject,
Subject serviceSubject) throws AuthException{
//Invalid case:
HttpServletResponse response =
(HttpServletResponse) messageInfo.getResponseMessage();
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return AuthStatus.SEND_FAILURE;
}

Exception error in google doc api

I am new to google api. I am trying to create a simple web application (Java EE) to read DocumentListFeed from google doc. My code in the servlet is:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
try
{
DocsService service = new DocsService("Document List Demo");
service.setUserCredentials(NAME, PASSWORD);
response.getWriter().println("helloooooo");
//URL documentListFeedUrl = new URL("http://docs.google.com/feeds/documents/private/full");
URL documentListFeedUrl = new URL("https://docs.google.com/feeds/default/private/full?v=3");
DocumentListFeed feed = service.getFeed(documentListFeedUrl, DocumentListFeed.class);
for(DocumentListEntry entry : feed.getEntries())
{
response.getWriter().println(entry.getTitle().getPlainText());
}
}
catch (Exception e)
{
response.getWriter().println(e);
}
}
But it is showing me the error: java.lang.NoClassDefFoundError: com/google/gdata/client/docs/DocsService
I am using Glassfish server and Ecllipse. And added external jar file: activation.jar, guava-r07.jar, mail.jar, servlet.jar, gdata-client-1.0.jar, gdata-client-meta-1.0.jar, gdata-core-1.0.jar, gdata-media-1.0.jar, gdata-docs-3.0.jar, gdata-docs-meta-3.0.jar.
I have copied this same code to java standard edition and it is working fine. Could please tell me why this thing is not working in Java EE? Is it a problem in GlassFish server?
It just means that the jars are not present in your Glassfish server classpath.
Add all the jars you listed to yuor glassfish server classpath. Since am not an Glassfish expert i cannot help you in adding the jars to your server.
In case of weblogic, you just need to package all the jars in your project APP-INF directory.
Hope it helps.