I am using Eclipse IDE, a simple HelloServlet.java file and a simple index.jsp file. When I run the local server, the program starts but the following code does not execute:
/**
* #see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
System.out.println("Init Firing: ");
}
I have the Console tab open, and the last statement I receive is: INFO: Server startup in 1442 ms. What might I do to get the init method to fire?
The container will only call the init() method of the servlet when it's called, not on the container startup.
If you want to start things on container startup, you can use the ContextListener as suggested here call method on server startup
This code works for me
package mine;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySL extends HttpServlet {
private static final long serialVersionUID = 1L;
public void init(ServletConfig config) throws ServletException {
System.out.println("xyz="+config.getInitParameter("xyz"));
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet");
}
}
and web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>jsp</display-name>
<servlet>
<servlet-name>mySL</servlet-name>
<servlet-class>mine.MySL</servlet-class>
<init-param>
<param-name>xyz</param-name>
<param-value>123</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>mySL</servlet-name>
<url-pattern>/MySL</url-pattern>
</servlet-mapping>
</web-app>
When the server starts, nothing happens, because the init() method is called when the servlet is called.
On the first servlet call (e.g. opening in your browser something like http://myserver.mydomain:8080/myapp/MySL), you'll get
xyz=123
doGet
On the second servlet call, you'll get
doGet
Please notice that this is the "old way" of declaring things. Nowadays, Servlets configuration can be made using annotations. Careful to not mix annotations with XML declarations for the same servlet.
Servlets with annotations look like this
package mine;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(urlPatterns = { "/OtherSL" }, initParams = { #WebInitParam(name = "abc", value = "456", description = "some parameter") })
public class OtherSL extends HttpServlet {
private static final long serialVersionUID = 1L;
public void init(ServletConfig config) throws ServletException {
System.out.println("abc=" + config.getInitParameter("abc"));
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet");
}
}
Related
I tried below way which is working fine
package test;
import static org.junit.Assert.assertEquals;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Application;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.DeploymentContext;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.ServletDeploymentContext;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.glassfish.jersey.test.spi.TestContainerException;
import org.glassfish.jersey.test.spi.TestContainerFactory;
import org.junit.Test;
import com.mkyong.rest.HelloWorldService;
public class HelloWorldServiceTest extends JerseyTest{
#Path("hello")
public static class HelloResource {
#GET
public String getHello() {
return "Hello World!";
}
}
#Override
protected Application configure() {
return new ResourceConfig(HelloResource.class);
}
#Override
protected TestContainerFactory getTestContainerFactory() throws TestContainerException {
return new GrizzlyWebTestContainerFactory();
}
#Override
protected DeploymentContext configureDeployment() {
return ServletDeploymentContext.forPackages(
getClass().getPackage().getName()).build();
}
#Test
public void testSingleNode() throws Exception {
final String hello = target("hello").request().get(String.class);
assertEquals("Hello World!", hello);
}
}
When i tried to replace the resource with resource which is outside of this test class and package like below
package test;
import static org.junit.Assert.assertEquals;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Application;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.DeploymentContext;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.ServletDeploymentContext;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.glassfish.jersey.test.spi.TestContainerException;
import org.glassfish.jersey.test.spi.TestContainerFactory;
import org.junit.Test;
import com.mkyong.rest.HelloWorldService;
public class HelloWorldServiceTest extends JerseyTest{
#Path("hello")
public static class HelloResource {
#GET
public String getHello() {
return "Hello World!";
}
}
#Override
protected Application configure() {
return new ResourceConfig(HelloWorldService.class);
}
#Override
protected TestContainerFactory getTestContainerFactory() throws TestContainerException {
return new GrizzlyWebTestContainerFactory();
}
#Override
protected DeploymentContext configureDeployment() {
return ServletDeploymentContext.forPackages(
getClass().getPackage().getName()).build();
}
#Test
public void testSingleNode() throws Exception {
final String hello = target("hello").path("Test").request().get(String.class);
assertEquals("Jersey say : Test", hello);
}
}
HelloWorldService.java
package com.mkyong.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
#Path("/hello")
public class HelloWorldService {
#GET
#Path("/{param}")
#Produces(MediaType.APPLICATION_JSON)
public Response getMsg(#PathParam("param") String msg) {
String output = "Jersey say : " + msg;
return Response.status(200).entity(output).build();
}
}
RestApplication.java
package rest;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;
import com.mkyong.rest.HelloWorldService;
public class RestApplication extends Application{
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> s = new HashSet<Class<?>>();
s.add(HelloWorldService.class);
return s;
}
}
web.xml
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Restful Web Application</display-name>
<servlet>
<servlet-name>rs-servlet</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>rest.RestApplication</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>rs-servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
I got an exception
javax.ws.rs.NotFoundException: HTTP 404 Not Found
at org.glassfish.jersey.client.JerseyInvocation.convertToException(JerseyInvocation.java:917)
at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:770)
at org.glassfish.jersey.client.JerseyInvocation.access$500(JerseyInvocation.java:90)
at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:671)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:423)
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:667)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:396)
at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:296)
at test.HelloWorldServiceTest.testSingleNode(HelloWorldServiceTest.java:48)
Can any one correct me where i went wrong...
Look at this
#Override
protected DeploymentContext configureDeployment() {
return ServletDeploymentContext.forPackages(
getClass().getPackage().getName()).build();
}
The forPackages is saying what package to scan for #Path and #Provider annotated classes, and automatically register them. The reason it works in the first example is that the resource class (the class annotated with #Path is in the getClass().getPackage().getName() package.
This method
#Override
protected Application configure() {
return new ResourceConfig(HelloWorldService.class);
}
is never called, because you override the getDeploymentContext(). Normally, if you don't override that method, it will call the configure method to register the application with the deployment context. But you neve do this.
So instead of the forPackages, you should use one of the ServletDeploymentContext.builder methods, that accept an Application class
return ServletDeploymentContext.builder(configure()).build()
return ServletDeploymentContext.builder(RestApplication.class).build();
OR
#Override
public ResourceConfig configure() {
return new ResourceConfig(HelloWorldService.class);
}
#Override
public ServletDeploymentContext configureDeployment() {
return SerlvetDeploymentContext.forServlet(new ServletContainer(configure));
}
One thing to note it that you only need to override the getTestContainerFactory and the configureDeployment if you wan to set up a servlet environment. Meaning, you need to use servlet APIs like HttpServletRequest, ServletContext, etc, in your application. If you don't need a servlet environment, just overriding configure is enough.
I am new in spring MVC.I don't know how to forward sessionExpired.jsp in Spring MVC globaly, when session expired.
I googled a lot but I didn't get any solution.What ever I am getting they are using spring security.In our application we are not using Spring security.
Please provide some sample code.
If you add this code it should solve your issue
<security:session-management invalid-session-url="SessionExpired.jsp" session-authentication-error-url="AlreadyLoggedIn.jsp">
<security:concurrency-control max-sessions="1" expired-url="SessionIsDuplicated.jsp" error-if-maximum-exceeded="false" />
</security:session-management>
Without using security, there are two ways in Spring MVC you can use HandlerInterceptorAdapter or Filters in Servlets.
Using HandlerInterceptorAdapter
In springContext.xml
<mvc:interceptors>
<bean class="com.nalashaa.interceptor.SessionValidatorInterceptor" />
</mvc:interceptors>
package com.nalashaa.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
#Component
public class SessionValidatorInterceptor extends HandlerInterceptorAdapter {
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (request.getServletPath().equals("/login.htm")) { //for Login Page
return true;
}
if(request.getSession().getAttribute("userName")!=null){
return true;
}else{
response.sendRedirect("login.htm");
return false;
}
}
}
Using Filter
In web.xml
<filter>
<filter-name>SessionValidatorFilter</filter-name>
<filter-class>com.nalashaa.filter.SessionValidatorFilteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SessionValidatorFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
package com.nalashaa.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class SessionValidatorFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
// initialization
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if(((HttpServletRequest)request).getRequestedSessionId() != null && ((HttpServletRequest)request).isRequestedSessionIdValid() == false) {
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/login.jsp");
requestDispatcher.forward(request, response);
}else {
chain.doFilter(request, response);
}
}
public void destroy() {
//Destroy code
}
}
I have the following class...
package org.me.test
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/servlet")
public class TestServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
resp.setContentType("text/plain");
resp.getWriter().write("Test Servlet");
super.doGet(req, resp);
}
}
and the following Web.xml...
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<servlet>
<display-name>srv</display-name>
<servlet-name>srv</servlet-name>
<servlet-class>
org.me.test.TestServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>srv</servlet-name>
<url-pattern>/srv/*</url-pattern>
</servlet-mapping>
</web-app>
but I get...
Error 405: HTTP method GET is not supported by this URL
You are getting the 405 error because you are calling super.doGet() at the end of your doGet(). Try removing that line.
The default implementation of doGet() in the base class HttpServlet returns that 405 error. To support the GET operation, you must override doGet() without calling the parent implementation, otherwise it returns the same error intended to be displayed when there is no override.
I have created a fresh new Java EE 6 Enterprise-Application in Netbeans 7.2. So I have three Projects:
EAR
EJB
WAR
In the EJB-Project, I have created a simple Bean:
package de.aidaorga.test;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
#Stateless
#LocalBean
public class NewSessionBean2343 {
}
In the WAR-Project, I have created a blank beans.xml in the folder "Web Pages\WEB-INF":
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>
And I have also created a simple Servlet:
import de.aidaorga.test.NewSessionBean2343;
import java.io.IOException;
import javax.ejb.EJB;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(name = "NewServlet2343", urlPatterns = {"/NewServlet2343"})
public class NewServlet2343 extends HttpServlet {
#Inject
NewSessionBean2343 newSessionBean2343_1;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}
}
Now, Netbeans shows me a Warning "Unsatisfied dependency: no bean matches the injection point" for the field "newSessionBean2343_1" annotated with "#Inject".
At deploy time, I get the following Excpetion:
Schwerwiegend: Exception while loading the app
Schwerwiegend: Exception while loading the app : WELD-001408 Unsatisfied dependencies for type [NewSessionBean2343] with qualifiers [#Default] at injection point [[field] #Inject NewServlet2343.newSessionBean2343_1]
org.jboss.weld.exceptions.DeploymentException: WELD-001408 Unsatisfied dependencies for type [NewSessionBean2343] with qualifiers [#Default] at injection point [[field] #Inject NewServlet2343.newSessionBean2343_1]
at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:311)
at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:280)
at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:143)
at org.jboss.weld.bootstrap.Validator.validateRIBean(Validator.java:163)
at org.jboss.weld.bootstrap.Validator.validateBeans(Validator.java:382)
at org.jboss.weld.bootstrap.Validator.validateDeployment(Validator.java:367)
at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:380)
at org.glassfish.weld.WeldDeployer.event(WeldDeployer.java:199)
at org.glassfish.kernel.event.EventsImpl.send(EventsImpl.java:128)
at org.glassfish.internal.data.ApplicationInfo.start(ApplicationInfo.java:313)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:461)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:240)
at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:389)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:348)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:363)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1085)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1200(CommandRunnerImpl.java:95)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1291)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1259)
at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:461)
at com.sun.enterprise.v3.admin.AdminAdapter.service(AdminAdapter.java:212)
at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:179)
at com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:117)
at com.sun.enterprise.v3.services.impl.ContainerMapper$Hk2DispatcherCallable.call(ContainerMapper.java:354)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:722)
Why do I get this warning and how do I get rid of it?
Thanks for any help.
Markus
I solved the problem: I've just forgotten the beans.xml in the EJB-Project. One beans.xml in an EAR-Project ist not enough...
First of all this is just an IDE warning - what counts is whether your code compiles.
The code does not look wrong, even though I can't remember that I've ever injected one bean twice. But IMHO that should work.
I reckon that Netbeans is only able to validate #Inject, but not #EJB, this would explain the warning.
Try to deploy it to a server and see what comes out.
I am working on sample application called bookstore where I have used Dependency Injection. Very simple application. I am using JavaEE 6, GlassFish 3.1.2, Static data in a class (no db), Eclipse Juno.
I can provide more info if needed.
Error I get:
WARNING: StandardWrapperValve[com.bookstore.web.BookListServlet]: PWC1406: Servlet.service() for servlet com.bookstore.web.BookListServlet threw exception
java.lang.NullPointerException
at com.bookstore.web.BookListServlet.doGet(BookListServlet.java:29)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
This I know is Dependency is not injected. Class instance is not created to use it. If I remove #Inject and created an instance of a class than the page is loading fine.
Servlet code generating error: See bold comments
package com.bookstore.web;
import java.io.IOException;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.bookstore.BookRepositoryImp;
#WebServlet("/book/")
public class BookListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Inject
private BookRepositoryImp bookRepo;
public BookListServlet() {
super();
}
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException {
**//bookRepo = new BookRepositoryImp(); If uncommect this code and remove #Inject than page working fine**
req.setAttribute("books", bookRepo.listBooks());
String path = "/WEB-INF/pages/book-list.jsp";
getServletContext().getRequestDispatcher(path).forward(req, res);
}
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException {
}
}
Project structure:
Have you tried moving your beans.xml file into the WEB-INF folder where your web.xml lives, maybe for some reason your beans.xml file is not copied properly to the resulting war file.