I am using spring and resteasy integration for exposing some REST based services. I am planning to use interceptors for logging and authentication but facing issues with interceptor invocation.
Controller class (using #Path for rest services)
#Controller
#Path("/v1.0/create")
public class ContollerClass{
#POST
#Path("/artifact")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public String someMethod(SampleVO sampleVO,#Context HttpServletRequest request) {
// Some functionality
}
acctrest-servlet.xml :
<context:component-scan base-package="com.comp.abc.xyz" />
<import resource="classpath:springmvc-resteasy.xml" />
<mvc:interceptors>
<bean class="com.comp.abc.xyz.interceptor.AuthenticationInterceptor" />
</mvc:interceptors>
Interceptor :
public class AuthenticationInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2) throws Exception {
System.out.println("pre handle ************************");
log.info("before handler execution");
String requestID = Long.toString(System.currentTimeMillis());
log.debug("request ID is {} :: ", requestID);
return true;
}
Web.xml
<servlet>
<servlet-name>acctrest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>acctrest</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
Except the interceptor invocation, rest of the flow is working fine.
Related
I work with Spring and I want to call from one Controller to another Controller.
This is my application-context file
<context:annotation-config />
<context:component-scan base-package="com.renfe.cme.mybatis,renfe.informes.resumenjornadas" />
<bean id="resumenMensualJornadasBO" class="renfe.informes.resumenjornadas.ResumenMensualJornadasBO">
</bean>
I call the first Controller from a servlet
ResumenMensualJornadasServlet resumenMensualJornadasServlet = new ResumenMensualJornadasServlet();
resumenMensualJornadasServlet.llamarController(req);
This is ResumenMensualJornadasServlet
#Controller
public class ResumenMensualJornadasServlet
{
#Autowired
private ResumenMensualJornadasBO resumenMensualJornadasBO;
public void llamarController(HttpServletRequest req) throws Exception{
this.resumenMensualJornadasBO.cargarParametrosInforme(req);
}
}
ResumenMensualJornadasBO.java is
#Component
public class ResumenMensualJornadasBO
{
#Autowired
private ResumenMensualJornadasManager resumenMensualJornadasManager;
public void cargarParametrosInforme(HttpServletRequest req) throws Exception
{
String matricula = StringUtils.recuperarParametro(req, "matricula");
String fechaDesde = StringUtils.recuperarParametro(req, "fechadesde");
String fechaHasta = StringUtils.recuperarParametro(req, "fechahasta");
resumenMensualJornadasManager.obtenerDatos(matricula, fechaDesde, fechaHasta);
}
}
I get NullPointerException when I call
this.resumenMensualJornadasBO.cargarParametrosInforme(req);
How can I fix the error in #Autowired?
EDITED
In the web.xml I have
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:com/renfe/cme/recursos/spring/applicationContext-*.xml</param-value>
<description>Spring files location</description>
</context-param>
How can I get the bean from this context?
In my Spring Boot application with packaging type as war, i am configuring Spring MVC. As i understand we dont have to configure Dispatcher Servlet Manually. However, i old style of web.xml i used to configure Dispatcher Servlet and then i used to pass contextClass and contextConfigLocation as follows
<servlet>
<description>
</description>
<display-name>DispatcherServlet</display-name>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<description>contextClass</description>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
<description>contextConfigLocation</description>
<param-name>contextConfigLocation</param-name>
<param-value>com.xxx.yyy.jdorderspringmvcweb.config.SpringMvcConfig</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
I belive this was to indicate that SpringMvcConfig (my custom class with spring mvc configuration) is the configuration class for Spring MVC..
However, In spring boot if Dispatcher Servlet is configured Automatically, how can i pass my custom class to dispatcher Servlet ?
In my Spring Boot application, my SpringMvcConfig class extends from WebMvcConfigurerAdapter and is annotated with #Configuration class
Help Needed...
Right in the configuration class which is annotated by #Configuration you could define your dispatcherServlet and pass init-parameter to it.
#Bean
public ServletRegistrationBean dispatcherServletRegistration() {
ServletRegistrationBean registrationBean = new ServletRegistrationBean(dispatcherServlet());
registrationBean.addInitParameter("contextClass","org.springframework.web.context.support.AnnotationConfigWebApplicationContext");
registrationBean.addInitParameter("contextConfigLocation","com.xxx.yyy.jdorderspringmvcweb.config.SpringMvcConfig");
return registrationBean;
}
Another way would be to create a paramter map and then set parameter for registration bean. This stream shows how to do it.
I think you have to create a config class as follow:
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class MySpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { DemoAppConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
I need to copy the contents of a web.xml to the WebAppInitializer.class (Java Configuration Class). I have copied the YahooFilter Class from web.xml (see code) but I am not sure how to add the init-params pragmatically.
I have pasted the web.xml and snippet of the Java Configuration class below. Can somebody take a look and provide some feedback?
<web-app>
<display-name>sample</display-Aname>
<filter>
<filter-name>YOSFilter</filter-name>
<filter-class>com.yahoo.yos.YahooFilter</filter-class>
<!--
optional param -
underlying oauth client class
possible values:
net.oauth.client.URLConnectionClient (default)
net.oauth.client.httpclient3.HttpClient3
net.oauth.client.httpclient4.HttpClient4
-->
<init-param>
<param-name>oauthConnectionClass</param-name>
<param-value>net.oauth.client.httpclient4.HttpClient4</param-value>
</init-param>
<!--
optional param -
redirect end-user if an access token is not found, set to false if you
are only making two-legged oauth calls e.g. oauth calls without an
access token to retrieve public information
defauts to true
-->
<init-param>
<param-name>redirect</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<!--
The URL where the filter is mapped to will redirect the user to Yahoo for
authorization if an OAuth authorization token has not been obtained for the
user. Should correspond to your callback url
-->
<filter-mapping>
<filter-name>YOSFilter</filter-name>
<url-pattern>/login.jsp</url-pattern>
</filter-mapping>
</web-app>
Java Config Class
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
...
#Override
protected void registerDispatcherServlet(ServletContext servletContext) {
super.registerDispatcherServlet(servletContext);
servletContext.addListener(new HttpSessionEventPublisher());
// servletContext.addListener(new RequestContextListener());
}
#Override
protected Filter[] getServletFilters() {
DelegatingFilterProxy delegatingFilterProxy = new DelegatingFilterProxy();
delegatingFilterProxy.setTargetBeanName("springSecurityFilterChain");
// FilterConfig filterConfig = delegatingFilterProxy.getFilterConfig();
YahooFilter yosFilter = new YahooFilter();
return new Filter[] {delegatingFilterProxy,yosFilter};
}
}
Try overriding onStartup() method and programatically register your filter with ServletContext like this:
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
FilterRegistration yahooFilter = servletContext.addFilter("yahooFilter", new YahooFilter());
yahooFilter.setInitParameter("oauthConnectionClass", "net.oauth.client.httpclient4.HttpClient4");
yahooFilter.setInitParameter("redirect", "true");
}
I'm simply trying to get userdata via controller service interface But I'm always getting
[WARN] 400 - GET /user/%7Bid%7D (127.0.0.1) 1403 bytes
My Controller:
#Controller
#RequestMapping(value ="/user")
public class AdminSpringController {
#RequestMapping( value = "/{id}", method = RequestMethod.GET)
#ResponseStatus(HttpStatus.OK)
public #ResponseBody GWTUser getUser(#PathVariable Integer id) throws NotFoundException {
...
}
}
My Service, it's a restygwt interface:
#Path("/user")
public interface UserAdminRestService extends RestService {
#GET
#Path("/{id}")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public void getUser(Integer id, MethodCallback<GWTUser> callback);
}
My servlet:
<servlet>
<servlet-name>userService</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/servlet/userService-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>userService</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
My servlet.xml
<context:component-scan base-package="com.app.admin.controller" />
<tx:annotation-driven />
<mvc:annotation-driven />
<!--This tag allows for mapping the DispatcherServlet to "/" (all extensions etc) -->
<mvc:default-servlet-handler/>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
</list>
</property>
</bean>
I Already have a method (user/users which returns all users, it's working fine but I think the problem is with my {id} (parameter variable), because it seems that my service or something parses my {id} as you can see at my error /user/%7Bid%7D. Thx for any help.
Missing #PathParam("id") in the service interface was the problem.
public void getUser(#PathParam("id") Integer id, MethodCallback<GWTUser> callback);
And for example UPDATE:
#PUT
#Path("/update")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public void update(GWTUser user, MethodCallback<UserServiceResponse> callback);
you need to set the RequestBody
#RequestMapping( value = "/update", method = RequestMethod.PUT)
#ResponseStatus(HttpStatus.OK)
public void update(#RequestBody GWTUser gwtUser) {
i want to use spring autowiring in servlet so here's my code:
#Configurable
public class ImageServlet extends HttpServlet {
#Autowired
private SystemPropertyDao systemPropertyDao;
#Override
public void init() throws ServletException {
String imagePath = systemPropertyDao.findByID(StaticParam.CONTENT_FOLDER);
}
while the SystemPropertyDao is annotated with #Repository
and my applicationContext.xml:
<context:component-scan base-package="com.basepackage" />
<mvc:annotation-driven />
<context:annotation-config />
<context:spring-configured/>
web.xml:
<servlet>
<servlet-name>imageServlet</servlet-name>
<servlet-class>com.xeno.basepackage.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>imageServlet</servlet-name>
<url-pattern>/myimages/*</url-pattern>
</servlet-mapping>
sometimes the autowiring works and sometimes it doesn't (the reference to the spring bean systemPropertyDao is null), can anyone please tell me if i am missing something?
I followed the solution in the following link, and it works fine:
Access Spring beans from a servlet in JBoss
public class MyServlet extends HttpServlet {
#Autowired
private MyService myService;
public void init(ServletConfig config) {
super.init(config);
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
config.getServletContext());
}
}
Remove the #Configurable annotation from your servlet and add:
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext (this);
at the first line of your init() method.