Handling error 500 by Interceptor in Spring MVC - spring

I have created my Interceptor class and have overridden only the afterCompletion method.
When ever the system throws an error ( 500, 404 ), the system breaks and does not reach afterCompletion method of my interceptor. Is there any way so that the request can reach the afterCompletion method with the exception occured.
Interceptor class
public class ClassName extends HandlerInterceptorAdapter {
#Override
public void afterCompletion(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex) throws Exception {
if (ex != null) {
//do somthing here
}
}
}
interceptor declaration
<mvc:interceptors>
<bean class="x.y.z.ClassName" />
</mvc:interceptors>
Can anyone guide me one this.

I am using SWF + MVC and realized different ways of registering interceptors ,
<bean class="org.springframework.webflow.mvc.servlet.FlowHandlerMapping">
<property name="flowRegistry" ref="DataCollectorFlowRegistry" />
<property name="interceptors">
<list>
<ref bean="localeChangeInterceptor"/>
</list>
</property>
</bean>
This works for me.

Related

Camel #Header annotation not working when using spring ProxyFactory

When I use the camel #Header annotation in an interface, and call the bean (that implements it) directly, the Header value is filled. But when I proxy it with the spring ProxyFactoryBean then the #Header annotated parameter is empty. Probably I'm doing something wrong or am missing part of the configuration.
public interface Foo {
public void execute(#Header("FooHeader") String headerValue);
}
public class FooImpl implements Foo {
public void execute(String headerValue) {
System.out.println(headerValue);
}
}
public class FooInterceptor implements org.aopalliance.intercept.MethodInterceptor {
public Object invoke(final MethodInvocation invocation) throws Throwable {
return invocation.proceed();
}
}
spring context:
<bean id="foo" class="FooImpl"/>
<bean id="fooInterceptor" class="FooInterceptor"/>
<bean id="fooProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="foo"/>
<property name="interfaces">
<list>
<value>Foo</value>
</list>
</property>
<property name="interceptorNames">
<list>
<value>fooInterceptor</value>
</list>
</property>
</bean>
The camel route DSL:
from("foo-queue").to("bean:foo?method=execute");
prints the value of the header, but the route:
from("foo-queue").to("bean:fooProxy?method=execute");
prints null. Seems that in my setup, camel does not "see" the header annotation that's on the interface, that the proxy implements.
So, how can I make camel see the annotation and inject the value of the header as an argument to the method?
ProxyFactoryBean is a spring and not Camel, and as such it does not know about those Camel annotations.
Instead see here how to use Camel Proxy in Spring XML files: http://camel.apache.org/using-camelproxy.html

Blind Sql injection in application developed using spring mvc

I am using Spring MVC for developing my web application.My problem is ,when I have done APPSCAN of my web application,it report BLIND SQL INJECTION in many of parameters in my SPRING MVC form.I am using bean for fetching data from SPRING MVC form and save() function in Spring framework for saving data to database.How I can resolve my ploblem?
My sample code is below..
Login.jsp contains link
<script>
function openUserReg(){
window.open("/ma/UserReg.nic");
}
</script>
<body>
<form:form>
Producer/ Dealer Registration(Public)
</form>
</body>
configuration of UserReg.nic is
<beans>
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="UserReg.nic">UserRegController</prop>
</props>
</property>
</bean>
<bean id="UserRegController" class="nic.mams.web.UserRegController">
<property name="commandName"><value>userReg</value></property>
<property name="commandClass"><value>nic.mams.web.beans.UserRegBean</value></property>
<property name="validator" ref ="UserRegValidator"/>
<property name="userRegService" ref="UserRegService"/>
<property name="pages">
<list>
<value>userRegistration.jsp</value>
<value>successRegistration.jsp</value>
</list>
</property>
</bean>
userRegistration.jsp contains
<form:input path="name" id="name" cssClass="control" maxlength="25" onclick="hidErMsg('er01');hidErMsgInnerHtml('err1');" autocomplete="off"/>
And the controller class contains the code
public class UserRegController extends AbstractWizardFormController{
UserRegService userRegService;
protected Map referenceData(HttpServletRequest req, Object obj, Errors er, int page) throws Exception {.....
return map;
}
protected ModelAndView processFinish(HttpServletRequest req,HttpServletResponse res, Object obj, BindException be) throws Exception {
UserRegBean bean = (UserRegBean)obj;
Applicant app=new Applicant();
...
app.setName(bean.getName());
userRegService.saveApp(app);
}
}
saveApp(app) function in UserRegService contains the code
saveApp(app){
String success = "No";
Session session=getSessionFactory().openSession();
Transaction tx=session.beginTransaction();
try {
getHibernateTemplate().save(app);
tx.commit();
session.close();
success = "Yes";
}
catch (Exception e) {
e.printStackTrace();
tx.rollback();
}
if (success.equals("Yes")){
return getHibernateTemplate().find("SELECT DISTINCT l.applicantLoginId,l.username,a.appServiceId,a.name,a.panNo " +
"FROM ApplicantLogin as l INNER JOIN l.applicants as a " +
"WHERE l.applicantLoginId=? AND l.applicantLoginId=a.applicantLogin AND a.applicantStatus is null " +
"AND a.transferType is null AND a.registrationStatus is not null ",applntlg.getApplicantLoginId());
}
return null;
}
Appscan results this
[17 of 26] Blind SQL Injection
Severity: High
Test Type: Application
Vulnerable URL: UserReg.nic (Parameter: name)
CVE ID(s): N/A
CWE ID(s): 89
Remediation Tasks: Review possible solutions for hazardous character injection
Any one any suggestion please provide me.

Spring 3 #Controller is not being invoked for Get request

I am attempting to use Spring 3' MVC support for annotated controllers in my web application.
In my application-context.xml, I've added the following:
<mvc:annotation-driven />
<context:component-scan base-package="com.abc.def.etc"/>
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
<property name="order" value="1" />
</bean>
My Controller is annotated as follows:
#Controller
#RequestMapping("/optimizerRules")
public class OptimizerRulesController {
private OptimizerRulesService optimizerRulesService;
private static final Log LOG = LogFactory.getLog(OptimizerRulesController.class);
public OptimizerRulesController()
{
LOG.info("Initializing OptimizerRulesController");
}
#RequestMapping(method = RequestMethod.GET)
public ModelAndView getRuleAttributesAndRules(ModelMap model)
{
LOG.info("Entering getRuleAttributesAndRules method");
}
When I start up my application I can see in my logs that the OptimizerRulesController has been initialized. I can also see the following:
Creating instance of bean 'optimizerRulesController'
Initializing OptimizerRulesController
Mapped URL path [/optimizerRules] onto handler 'optimizerRulesController'
However, when I invoke my application using http://localhost:8080/appName/optimizerRules I get a 404 error!
What configuration am I missing here?
Thanks
Spring MVC would normally log that no mapping is found for a particular request at WARN level. Assuming you're not seeing that in your logs and assuming that WARN is enabled, and since you're not seeing your own log statement, it sounds like your request isn't even hitting the Spring MVC DispatcherServlet, which probably means the URL is wrong.
The URL should be http://server:port/war/dispatcherServletMapping/optimizerRules, so your web.xml should tell you the missing path component, if my assumptions are valid.

Spring: SimpleMappingExceptionResolver together with #ExceptionHandler?

I like SimpleMappingExceptionResolver, because in one place i have all exception->view mappings for all controllers in web-app (i suppose that). To customize some exception in specific controller i would like to use #ExceptionHandler, but it doesn't work together - all exceptions are handled by SimpleMappingExceptionResolver. How to make this work together ?
#Controller
public class SomeController {
...
#ExceptionHandler(SomeException.class)
public ModelAndView handleException(Exception ex) {
// ...
}
}
SimpleMappingExceptionResolver:
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="defaultErrorView" value="error"/>
<property name="exceptionMappings">
...
</property>
</bean>
Short answer: p:order
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver" p:order="1" />
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" p:order="2" p:defaultErrorView="uncaughtException"/>
Full story: springsource forum.

How to use #Autowired in a Quartz Job?

i am using quartz with spring
and i want to inject/use another class in the job class
and i don't know how to do it correctly
the xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!-- Scheduler task -->
<bean name="schedulerTask" class="com.mkyong.quartz.SchedulerTask" />
<!-- Scheduler job -->
<bean name="schedulerJob"
class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass" value="com.mkyong.quartz.SchedulerJob" />
<property name="jobDataAsMap">
<map>
<entry key="schedulerTask" value-ref="schedulerTask" />
</map>
</property>
</bean>
<!-- Cron Trigger -->
<bean id="cronTrigger"
class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="schedulerJob" />
<property name="cronExpression" value="0/10 * * * * ?" />
</bean>
<!-- Scheduler -->
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="jobDetails">
<list>
<ref bean="schedulerJob" />
</list>
</property>
<property name="triggers">
<list>
<ref bean="cronTrigger" />
</list>
</property>
</bean>
</beans>
the quartz job:
package com.mkyong.quartz;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
public class SchedulerJob extends QuartzJobBean
{
private SchedulerTask schedulerTask;
public void setSchedulerTask(SchedulerTask schedulerTask) {
this.schedulerTask = schedulerTask;
}
protected void executeInternal(JobExecutionContext context)
throws JobExecutionException {
schedulerTask.printSchedulerMessage();
}
}
the task to be executed:
package com.mkyong.quartz;
public class SchedulerTask {
public void printSchedulerMessage() {
System.out.println("Struts 2 + Spring + Quartz ......");
}
}
i want to inject another DTO class that deals with Database in the task class
to do some database work in the task, how to do that ?
In your solution you are using the spring #Autowired annotation in a class that is not instantiated by Spring. Your solution will still work if you remove the #Autowired annotation because Quartz is setting the property, not Spring.
Quartz will try to set every key within the JobDataMap as a property. E.g. since you have a key "myDao" Quartz will look for a method called "setMyDao" and pass the key's value into that method.
If you want Spring to inject spring beans into your jobs, create a SpringBeanJobFactory and set this into your SchedulerFactoryBean with the jobFactory property within your spring context.
SpringBeanJobFactory javadoc:
Applies scheduler context, job data map and trigger data map entries
as bean property values
Not sure if this is what you want, but you can pass some configuration values to the Quartz job. I believe in your case you could take advantage of the jobDataAsMap property you already set up, e.g.:
<property name="jobDataAsMap">
<map>
<entry key="schedulerTask" value-ref="schedulerTask" />
<entry key="param1" value="com.custom.package.ClassName"/>
</map>
</property>
Then you should be able to access it in your actual Java code in manual way:
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
schedulerTask.printSchedulerMessage();
System.out.println(context.getJobDetail().getJobDataMap().getString("param1"));
}
Or using the magic Spring approach - have the param1 property defined with getter/setter. You could try defining it with java.lang.Class type then and have the done automatically (Spring would do it for you):
private Class<?> param1;
// getter & setter
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
schedulerTask.printSchedulerMessage();
System.out.println("Class injected" + getParam1().getName());
}
I haven't tested it though.
ApplicationContext springContext =
WebApplicationContextUtils.getWebApplicationContext(
ContextLoaderListener.getCurrentWebApplicationContext().getServletContext()
);
Bean bean = (Bean) springContext.getBean("beanName");
bean.method();
As mentioned in inject bean reference into a Quartz job in Spring? you can use spring SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
#Named
public class SampleJob implements Job {
#Inject
private AService aService;
#Override
public void execute(JobExecutionContext context)
throws JobExecutionException {
//Do injection with spring
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
aService.doIt();
}
}
As mentioned it may not wotk on some spring version but I have tested it on 4.2.1.RELEASE which worked fine.
this is my solution:
public class MySpringBeanJobFactory extends
org.springframework.scheduling.quartz.SpringBeanJobFactory implements
ApplicationContextAware {
private ApplicationContext ctx;
#Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.ctx = applicationContext;
}
#Override
protected Object createJobInstance(TriggerFiredBundle bundle)
throws Exception {
Object jobInstance = super.createJobInstance(bundle);
ctx.getAutowireCapableBeanFactory().autowireBean(jobInstance);
return jobInstance;
}
}
then config the class of MySpringBeanJobFactory in the xml:
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="jobFactory">
<bean class="com.xxxx.MySpringBeanJobFactory" />
</property>
<property name="configLocation" value="classpath:quartz.properties" />
<property name="triggers">
<list>
<ref bean="cronTrigger"/>
</list>
</property>
</bean>
Good luck ! :)

Resources