I've known the difference between #Resource annotation and #Autowired annotation recently, but I don't know in what scene #Resource annotation will be used before spring-framework has been invented.
I've search google and stackoverflow for any hints and don't get any reasonable explanation. Then I've tried to create a Java Web Project(use J2EE1.4, jdk1.7, tomcat 7), and create a servlet to mock Spring's autowire behavior by using #Resource annotation, but we encounter a error.
Below the code I use:
public class TestServlet extends HttpServlet {
public void init() throws ServletException {
Student student=new Student("1");
}
public void service(ServletRequest arg0, ServletResponse arg1)
throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("111111111111");
}
}
public class TestServlet2 extends HttpServlet {
#Resource
Student student;
public void service(ServletRequest arg0, ServletResponse arg1)
throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println(student);
}
}
First, I visit the TestServlet to create Student java bean, and then I visit TestServlet2 to inject Student object to student property. But I encounter a error like below:
javax.naming.NamingException: Cannot create resource instance
at org.apache.naming.factory.ResourceEnvFactory.getObjectInstance(ResourceEnvFactory.java:115)
at javax.naming.spi.NamingManager.getObjectInstance(NamingManager.java:321)
at org.apache.naming.NamingContext.lookup(NamingContext.java:848)
at org.apache.naming.NamingContext.lookup(NamingContext.java:159)
at org.apache.naming.NamingContext.lookup(NamingContext.java:836)
at org.apache.naming.NamingContext.lookup(NamingContext.java:173)
at org.apache.catalina.core.DefaultInstanceManager.lookupFieldResource(DefaultInstanceManager.java:538)
at org.apache.catalina.core.DefaultInstanceManager.processAnnotations(DefaultInstanceManager.java:440)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:133)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:114)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1133)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:853)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:135)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2549)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2538)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Thank you very much!#Powerlord Your advice is of great help, and solve my problem perfectly.This is my solution:
I create a file Context.xml in WebRoot/META-INF
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="student" auth="Container"
type="com.test.Student" factory="org.apache.naming.factory.BeanFactory" id="5">
</Resource>
</Context>
public class TestServlet2 extends HttpServlet {
#Resource(name="student")
Student student;
public void service(ServletRequest arg0, ServletResponse arg1)
throws ServletException, IOException {
System.out.println(student.getId());
}
}
Related
I want to secure my REST API (jersey2) based on IP addresses, but without having the trouble of Spring Security and so on. I simply need to whitelist a few IPs that are granted full access rights.
To implement this, I thought of putting the IPs into the application.properties and enforcing the restriction using a Filter. This works perfectly fine, when using an embedded Jetty server, but fails when deploying the application as war on Tomcat.
I tried to read the properties both in the Filter constructor and in the init-method (only the constructor example shown below in the snippet). Nevertheless both lead to a NullPointerException when accessing the class field (String ips), which store the IPs. Also using the Enviroment variable does not seem to help.
Any help is appreciated. Thank you!
#Component("RestAuthFilter")
public class RestAuthFilter implements Filter {
private String ips;
public RestAuthFilter() {
try {
final Properties p;
final InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("application.properties");
p = new Properties();
p.load(input);
ips = p.getProperty("whitelist.rest.ips");
} catch(IOException e) {
ips = "127.0.0.1";
}
}
#Override
public void init(final FilterConfig config) throws ServletException {
}
#Override
public void doFilter(final ServletRequest req, final ServletResponse res,
final FilterChain chain) throws ServletException, IOException {
final List<String> allowedIPs = Arrays.asList(ips.split("[,]"));
if(!allowedIPs.contains(req.getRemoteAddr())) {
((HttpServletResponse) res).setStatus(HttpServletResponse.SC_FORBIDDEN, "Not allowed to use REST API!");
} else {
chain.doFilter(req, res);
}
}
#Override
public void destroy() {
}
}
Stacktrace:
java.lang.NullPointerException: null
at com.example.RestAuthFilter.doFilter(RestAuthFilter.java:44)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.boot.context.web.ErrorPageFilter.doFilter(ErrorPageFilter.java:113)
at org.springframework.boot.context.web.ErrorPageFilter.access$000(ErrorPageFilter.java:59)
at org.springframework.boot.context.web.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.boot.context.web.ErrorPageFilter.doFilter(ErrorPageFilter.java:106)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Since you're using Spring Boot and your setup is pretty standard, I would stick to using PropertySource (via #Value or Environment) to load the IPs from application.properties. Having said that, and noticing your comment about using Environment ...
Concerning to the Environment variable I am refering to
org.springframework.core.env.Environment, which I included using DI,
something like #Autowired Environment env as class member
You can't inject it as a class member and have your initialization in the constructor, you'll run into scoping issue -- the Environment will not be set when the constructor is called. You need to inject the Environment via constructor not as a class member, for example:
#Component("RestAuthFilter")
public class RestAuthFilter implements Filter {
private final List<String> restClientIps;
#Autowired
public RestAuthFilter(Environment env) {
String restClientIpsProperty = env.getRequiredProperty("whitelist.rest.ips");
restClientIps = // parse/split from restClientIpsProperty
}
...
}
I am in the proces of creating simple CRUD program with Spring data rest Spring data rest,
but I have a problem with security configuration (example was taken from here.
I have a WebAppInitializer:
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{JpaRepositoryConfig.class, SecurityConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{CustRepositoryRestMvcConfiguration.class};
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
#Override
protected Filter[] getServletFilters() {
return new Filter[]{ new DelegatingFilterProxy("springSecurityFilterChain")};
}
}
I have a next crud repository:
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.rest.repository.annotation.RestResource;
import org.springframework.security.access.prepost.PreAuthorize;
#PreAuthorize("hasRole('ROLE_USER')")
#RestResource(path = "products", rel = "products")
public interface ProductRepository extends PagingAndSortingRepository<Product, Long> {
#PreAuthorize("hasRole('ROLE_ADMIN')")
#Override
Product save(Product s);
#PreAuthorize("hasRole('ROLE_ADMIN')")
#Override
void delete(Long aLong);
}
I have a next security configuration:
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("greg").password("turnquist").roles("USER").and()
.withUser("ollie").password("gierke").roles("USER", "ADMIN");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic().and()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/products").hasRole("ADMIN")
.antMatchers(HttpMethod.PUT, "/products/**").hasRole("ADMIN")
.antMatchers(HttpMethod.PATCH, "/products/**").hasRole("ADMIN").and()
.csrf().disable();
}
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
I used next version of dependencies:
<java-version>1.7</java-version>
<spring-data-rest-version>1.0.0.RELEASE</spring-data-rest-version>
<spring.version>3.2.2.RELEASE</spring.version>
<org.slf4j-version>1.7.5</org.slf4j-version>
From project configured log4j I am getting these errors:
SEVERE: Error filterStart
org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/admin] startup failed due to previous errors
INFO : org.springframework.web.context.support.AnnotationConfigWebApplicationCon
text - Closing Root WebApplicationContext: startup date [Tue Dec 30 00:09:21 EET
2014]; root of context hierarchy
......
DEBUG: org.springframework.beans.factory.support.DisposableBeanAdapter - Invokin
g destroy() on bean with name 'org.springframework.security.config.annotation.au
thentication.configuration.AuthenticationConfiguration'
DEBUG: org.springframework.beans.factory.support.DefaultListableBeanFactory - Re
trieved dependent beans for bean '(inner bean)': [(inner bean), productRepositor
y]
DEBUG: org.springframework.beans.factory.support.DisposableBeanAdapter - Invokin
g destroy() on bean with name 'securityConfig'
From tomcat 7.0.56 localhost log I also have these errors in the logs:
SEVERE: Exception starting filter delegatingFilterProxy
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'springSecurityFilterChain' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:568)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1102)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:278)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1121)
at org.springframework.web.filter.DelegatingFilterProxy.initDelegate(DelegatingFilterProxy.java:326)
at org.springframework.web.filter.DelegatingFilterProxy.initFilterBean(DelegatingFilterProxy.java:236)
at org.springframework.web.filter.GenericFilterBean.init(GenericFilterBean.java:194)
at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:279)
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:109)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4830)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5510)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:649)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1083)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1879)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
What is causing the errors in these logs?
I originally used #Component for a bean(Student.java) that is being called in a Servlet. I changed #Component to #Named. I used to use following code to get the student bean in the Servlet.
Student student = (Student)applicationContext.getBean("student")
After I changed to #Named, the bean is no longer being detected. I am getting following error messages. Could anyone tell me what is the problem? I placed javax.inject-1.jar file under webapps\student-enrollment\WEB-INF\lib\
Context init...
Logger name for context: student-enrollment
Context logger config file: logback-student-enrollment.xml
Adding logger context: student-enrollment to map for context: student-enrollment
2014-09-10 20:46:19.361 Servlet /student-enrollment threw load() exception
javax.naming.NameNotFoundException: Name student is not bound in this Context
at org.apache.naming.NamingContext.lookup(NamingContext.java:770) ~[catalina-6.0.36.jar:6.0.36]
at org.apache.naming.NamingContext.lookup(NamingContext.java:153) ~[catalina-6.0.36.jar:6.0.36]
at org.apache.catalina.util.DefaultAnnotationProcessor.lookupFieldResource(DefaultAnnotationProcessor.java:276) ~[catalina-6.0.36.jar:6.0.36]
at org.apache.catalina.util.DefaultAnnotationProcessor.processAnnotations(DefaultAnnotationProcessor.java:187) ~[catalina-6.0.36.jar:6.0.36]
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1153) ~[catalina-6.0.36.jar:6.0.36]
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1026) ~[catalina-6.0.36.jar:6.0.36]
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4421) [catalina-6.0.36.jar:6.0.36]
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4734) [catalina-6.0.36.jar:6.0.36]
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057) [catalina-6.0.36.jar:6.0.36]
at org.apache.catalina.core.StandardHost.start(StandardHost.java:840) [catalina-6.0.36.jar:6.0.36]
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057) [catalina-6.0.36.jar:6.0.36]
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463) [catalina-6.0.36.jar:6.0.36]
at org.apache.catalina.startup.Embedded.start(Embedded.java:825) [catalina-6.0.36.jar:6.0.36]
at org.red5.server.tomcat.TomcatLoader.init(TomcatLoader.java:517) [tomcatplugin-1.3.jar:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.6.0_43]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) ~[na:1.6.0_43]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) ~[na:1.6.0_43]
at java.lang.reflect.Method.invoke(Method.java:597) ~[na:1.6.0_43]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeCustomInitMethod(AbstractAutowireCapableBeanFactory.java
:1581) [spring-beans-3.1.1.RELEASE.jar:3.1.1.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1522
) [spring-beans-3.1.1.RELEASE.jar:3.1.1.RELEASE]
EDIT 1
Here is part of my Student.java and StudentEnrollmentServlet class.
#Named(Student.NAMED)
public class Student {
public static final String NAMED = "student";
.......
}
#Named(StudentEnrollmentServlet.NAMED)
public class StudentEnrollmentServlet extends HttpServlet {
public static final String NAMED = "StudentEnrollmentServlet";
#Resource(name = Student.NAMED)
private Student student;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
.......
}
It looks like you will need give the bean a name
#Named("student")
After successfully able to run a WAR through jetty, I am trying to embed jetty server into my web-application. It is a normal java application consisting servlet. I have used exploded WAR directory (WARless).
But I get the following exception.
2014-02-22 16:27:08.271:INFO:oejw.StandardDescriptorProcessor:NO JSP Support for /, did not find org.apache.jasper.servlet.JspServlet
2014-02-22 16:27:08.319:WARN:oejs.Holder:
java.lang.ClassNotFoundException: ClientServlet
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at org.eclipse.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:421)
at org.eclipse.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:383)
at org.eclipse.jetty.util.Loader.loadClass(Loader.java:100)
at org.eclipse.jetty.util.Loader.loadClass(Loader.java:79)
at org.eclipse.jetty.servlet.Holder.doStart(Holder.java:107)
at org.eclipse.jetty.servlet.ServletHolder.doStart(ServletHolder.java:298)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:791)
at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:265)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1242)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:717)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:494)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:95)
at org.eclipse.jetty.server.Server.doStart(Server.java:282)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
at com.jetty.RunJetty.main(RunJetty.java:24)
2014-02-22 16:27:08.321:WARN:/:unavailable
Embedded jetty Server code
package com.jetty;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
public class RunJetty {
public RunJetty() {
}
public static void main(String[] args) {
Server server=new Server(8080);
WebAppContext wac = new WebAppContext();
wac.setResourceBase("C:/Users/User/j2ee/workspace/CLient1");
wac.setDescriptor("C:/Users/User/j2ee/workspace/CLient1/WebContent/WEB-INF/web.xml");
wac.setContextPath("/");
wac.setParentLoaderPriority(true);
server.setHandler(wac);
try {
server.start();
server.join();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Servlet Code
package com.jetty;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.omg.CORBA.RepositoryIdHelper;
public class ClientServlet extends HttpServlet {
private static final long serialVersionUID = 8120079003868426157L;
private String greeting="Hello World";
public ClientServlet(){}
public ClientServlet(String greeting)
{
this.greeting=greeting;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().println("<h1>"+greeting+"</h1>");
}
}
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_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>kajh</display-name>
<servlet>
<description></description>
<display-name>ClientServlet</display-name>
<servlet-name>ClientServlet</servlet-name>
<servlet-class>ClientServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ClientServlet</servlet-name>
<url-pattern>/ClientServlet</url-pattern>
</servlet-mapping>
</web-app>
Additionally, I want to use response.sendRedirect in my servlet. Something like,
public class ClientServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 8120079003868426157L;
private String greeting="Hello World";
public ClientServlet(){}
public ClientServlet(String greeting)
{
this.greeting=greeting;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
response.sendRedirect("http://localhost:8080/CLient1/index.html");
}
}
Please help! I am stuck on this like forever.
Thank you in advance!
Also I am adding the folder structure of my application to have a better understanding
I think the servlet-class should be
<servlet-class>com.jetty.ClientServlet</servlet-class>
Edit: Made it show the codeformat also.
I am getting an NPE when I deploy to Tomcat (this doesn't happen every time, only sometimes when I re-deploy). The error is a NullPointerException when the RemoteServiceServlet tries to loadSerializationPolicy(..). I noticed that the issue was with the servlet.log method call, when the loadSerializationPolicy fails to find the serialization policy file (which seems like another problem? Perhaps its not and the serialization will just skip it, idk), so it tries to log it but falls over with an NPE.
So as explained here: https://github.com/ArcBees/GWTP/issues/289#issuecomment-21675896 the issue is that RemoteServiceServlet cannot find the logger? I tried the proposed solution which was to create a new DispatchServiceImpl in my project that replaces the standard GWTP service implementation and implement ServletConfigAware with a ServletConfig object and overriding getServletConfig() and setServletConfig(...). This did not resolve the issue for me however. This doesn't happen when I use Chrome browser only Firefox and IE (that I have tested). I assume Chrome isn't failing to find the policy file? Or isn't performing an unnecessary check?
java.lang.NullPointerException
at javax.servlet.GenericServlet.getServletName(GenericServlet.java:238)
at javax.servlet.GenericServlet.log(GenericServlet.java:190)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.loadSerializationPolicy(RemoteServiceServlet.java:103)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.doGetSerializationPolicy(RemoteServiceServlet.java:293)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.getSerializationPolicy(RemoteServiceServlet.java:157)
at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamReader.prepareToRead(ServerSerializationStreamReader.java:491)
at com.google.gwt.user.server.rpc.RPC.decodeRequest(RPC.java:240)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:206)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:248)
at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
at com.gwtplatform.dispatch.server.spring.DispatchServiceImpl.handleRequest(DispatchServiceImpl.java:68)
at org.springframework.web.context.support.HttpRequestHandlerServlet.service(HttpRequestHandlerServlet.java:68)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Now this issue doesn't take place in Dev Mode. Only on random occasions that I redeploy to Tomcat. If anyone has any useful advice or have ran into this issue before, I would be really grateful for the help!
Here are some classes that might help with identifying the issue:
DispatchServiceImpl.java (replacing the standard GWTP DispatchServiceImpl)
#Component("dispatch")
public class DispatchServiceImpl extends AbstractDispatchServiceImpl implements HttpRequestHandler,
ServletContextAware, ServletConfigAware {
private static final long serialVersionUID = 136176741488585959L;
private ServletContext servletContext;
private ServletConfig servletConfig;
#Autowired(required = false)
protected String securityCookieName;
#Autowired
public DispatchServiceImpl(final Logger logger, final Dispatch dispatch,
RequestProvider requestProvider) {
super(logger, dispatch, requestProvider);
}
#Override
public String getSecurityCookieName() {
return securityCookieName;
}
public void setSecurityCookieName(String securityCookieName) {
this.securityCookieName = securityCookieName;
}
#Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
#Override
public void setServletContext(ServletContext arg0) {
this.servletContext = arg0;
}
#Override
public ServletContext getServletContext() {
return servletContext;
}
#Override
public void setServletConfig(ServletConfig servletConfig) {
this.servletConfig = servletConfig;
}
#Override
public ServletConfig getServletConfig() {
return servletConfig;
}
}
ServerModule.java
/**
* Module which binds the handlers and configurations.
*/
#Configuration
#Import({
DefaultModule.class,
PropertyModule.class,
ConfigLoader.class
})
#ComponentScan({
"nz.co.doltech.ims",
"nz.co.doltech.ims.framework.extensions.platform.dispatch.server.spring"
})
#ImportResource("classpath:META-INF/properties.xml")
#EnableAspectJAutoProxy
#EnableTransactionManagement
public class ServerModule extends HandlerModule {
... snip ...
}
Well I did the obvious and Overrode getServletName and now it works fine. Strange that ServletConfigAware didn't help with this issue though.