Restrict method on MultiActionController action - java

I have a MultiActionController with an action that I would only like to be reachable if the POST method is used.
public class MyController extends MultiActionController {
public ModelAndView myAction(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
// I don't want to hit this code unless POST was used
}
}
Is there a way to achieve this through annotations or am I stuck checking request.getMethod() ?

Use:
#RequestMapping(value={"action1","action2","action3"},
method = RequestMethod.POST)

Related

Changing httpservletrequest to restcontroller in Spring

I have a servlet class which has a method "process", over ridden from HttpServlet
#override
protected void process(HttpServletRequest request, HttpServletResponse response) {
InputStream in = null;
OutputStream out = null;
String inXml = null;
//some more code..
}
It is reading whatever is coming into the servlet.
How can I rewrite this as rest controller in spring??
Just code it as:
#RestController
public ReturnType process(HttpServletRequest request, HttpServletResponse response {
//...
}
and check this part of the Spring MVC documentation as well:
#RequestMapping handler methods have a flexible signature and can choose from a range of supported controller method arguments and return values.
Note, that:
whatever you return from your Rest-Controller turns into HTTP Response Body;
you can define #RestController on the class level.

Spring #RequestMapping

I have a question with Spring MVC RequestMapping annotation. need your help.
I have created one IPSLcontroller and i want that IPSLcontroller to handle all request url.i have created two method in this controller.
1)handleLogoutRequest :- this method should invoke on below url.
2)handleRequest :- this method should invoke on all request url otherthan logout.
http://localhost:9086/webapp/login
or
http://localhost:9086/webapp/add
or
http://localhost:9086/webapp/remove
here is my sample code. but it's not working as expected.
#Controller
public class IPSLController {
#RequestMapping(value={"/logout/*"},method = RequestMethod.POST)
protected void handleLogoutRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
System.out
.println("........................IPSLController logout request.......................................");
}
#RequestMapping(method = RequestMethod.POST,value={"/*"})
protected void handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
System.out
.println("........................IPSLController all request Post.......................................");
}
}
You should use a general Prefix for every controller you use, so you can differ between them better. Also you donĀ“t need any "/" for calls like this.
#Controller
#RequestMapping("ispl")
public class IPSLController {
#RequestMapping(value={"logout"},method = RequestMethod.POST)
protected void handleLogoutRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
System.out
.println("........................IPSLController logout request.......................................");
}
#RequestMapping(method = RequestMethod.POST,value={"hello"})
protected void handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
System.out
.println("........................IPSLController all request Post.......................................");
}
}
If you now want to call them over a ServletRequest or with a restService or something similar you should declare them like this
#GET
#Path("ispl/logout")
public void Method (HttpServletResponse ...)
Well it is working the way it should. You have a mapping for /* and for /logout/*. So when you post to /logout it invokes the method for /*. I suspect that if you post to /logout/something it would invoke your logout handler.
If you want it to work, you cannot have a wildcard mapping for the second method. At least use /something/* so that spring can make a correct decision on mappings.

Spring 3 HandlerInterceptor passing information to Controller

I've setup a Spring HandlerInterceptor to add an attribute to the HttpServletRequest to be able to read it from the Controller, sadly this does not seem to work which seems strange to me. Am I doing things wrong? Any idea how to transmit the data from the Interceptor to the Controller?
Here is the simplified code of the two impacted classes
public class RequestInterceptor implements HandlerInterceptor {
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
request.setAttribute("my-role", "superman");
}
[...]
}
#RestController
#RequestMapping("Test")
public class TestController {
public final Logger logger = LoggerFactory.getLogger(getClass());
#RequestMapping(value = "something")
public void something(HttpServletRequest request) {
logger.info(request.getAttribute("my-role"));
}
[...]
}
The request.getAttribute("my-role") returns null... but does return the excepted value if I read it in the postHandle of the HandlerInterceptor, I feel like I'm missing something...
EDIT : I found out that going thru the session with "request.getSession().setAttribute" works as a charm, still i do not understand why the request itself does not work in this use case.
Can you try with session instead of request like below.
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
...
HttpSession session = request.getSession();
session.setAttribute("attributeName", objectYouWantToPassToHandler);
....
}
In your handler handleRequest method:
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
....
HttpSession session = request.getSession();
objectYouWantToPassToHandler objectYouWantToPassToHandler = session.getAttribute("attributeName");
....
}

Include login methods

I got an entity User and i want every method of every controller to have the access to the logged user without typing anything like :
model.addAttribute(userDao.getuser(principal.getUsername()));
You can implement a simple HandlerInterceptorAdapter that will add the user instance to the model after a handler is invoked.
class UserAddingHandlerInterceptor extends HandlerInterceptorAdapter {
// Autowire dependencies...
private static final String ATTRIBUTE = "user";
#Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler,
ModelAndView modelAndView) throws Exception {
if (modelAndView != null && !modelAndView.getModelMap().hasAttribute(ATTRIBUTE) {
modelAndView.addObject(ATTRIBUTE, userDao.getuser(principal.getUsername()));
}
}
}

How to read request parameter values Using HandlerInterceptor in spring?

I'm using HandlerInterceptor to trigger all the events/actions happens in my applications and save it to audit table. In table I'm saving the information like servername, session, parameters etc..
So using HandlerInterceptor how can I read all those parameters values and the pathvariable values what I'm passing in my controller.
Here is my code :
public class AuditInterceptor implements HandlerInterceptor {
#Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
LOG.debug("URL path"+request.getRequestURI());
return true;
}
#Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
LOG.debug("URL PATH :"+request.getRequestURI());
}
}
My controller class enter code here::
public class ABCDController {
#RequestMapping(value="categories",method=RequestMethod.GET)
#ResponseBody
public List<Category> getCategoryList(#RequestParam String divisions){
return service.getCategoryList(divisions);
}
}
So how can I read the parameter name and values using HandlerInterceptor's HttpServletRequest request object.
The Servlet API provides a way to read the Request Parameters. For example,
ServletRequest.getParameterMap() returns a map of key-values of the request parameters.
However, for Path variables and values, I don't know if Spring MVC offers a simplified way of doing it, but using Servlet API again, you can read the URI using HttpServletRequest.getRequestURI(). You'll have to have your own logic to split it up into appropriate Path parameters.
You should be able to get the variables and its values as a map using the following,
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
final Map<String, String> variableValueMap = (Map<String, String>) request
.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
variableValueMap.forEach((k,v)->System.out.println("Key:"+k+"->"+"Value : "+v));
return true;
}

Categories