URL with hash in Spring Mvc - spring-mvc

everyone.
I'm using Spring MVC 4. My App sends activation url to user's email.
Activation url:
www.example.com:8080/myapp/user/activate/$2a$10$Ax2WL93zU3mqjtdxuYlYvuWWyQsPBhkhIfzYHJYk4rdNlAY8qCyC6
But, my App can't find path.
My controller:
#RequestMapping(value = "/user/activate/{hash})
public void activateUser(#PathVariable("hash") String hash) {
userService.activate(hash);
}
What am I doing wrong?
Update:
I've found out that if hash contains dot (".") then throws 404 error.
I've change my url:
www.example.com:8080/myapp/user/activate?code=$2a$10$Ax2WL93zU3mqjtdxuYlYvuWWyQsPBhkhIfzYHJYk4rdNlAY8qCyC6
and my controller:
#RequestMapping(value = "/user/activate)
public void activateUser(#RequestParam("code") String hash) {
userService.activate(hash);
}
It works perfectly.

you are not returning anything from the controller, hence receiving a 404

If you have dot (.) in your path variable value, then you must declare it explicitly in the RequestMapping, as shown below -
#RequestMapping(value = "/download/{attachmentUri:.+}", method = RequestMethod.POST)
#ResponseBody
public ResponseEntity<InputStreamResource> downloadAttachment(#PathVariable("attachmentUri") String attachmentUri,
HttpServletResponse response,
WebRequest webRequest) {
}

Related

Forward request to spring controller

From a servlet , I am forwarding the request to a spring controller like below
RequestDispatcher rd = request.getRequestDispatcher("/myController/test?reqParam=value");
rd.forward(request, response);
In order to pass a parameter to the spring controller , I am passing it as request parameter in the forward URL.
Is there a better way of doing this ?
Instead of passing in request parameter , can I pass as a method parameter to the spring controller during forward ?
This will be called when /myController/test?reqParam=value is requested:
#RequestMapping("/myController/test")
public String myMethod(#RequestParam("reqParam") String reqParamValue) {
return "forward:/someOtherUrl?reqParam="+reqParamValue; //forward request to another controller with the param and value
}
Or you can alternatively do:
#RequestMapping("/myController/test")
public String myMethod(#RequestParam("reqParam") String reqParamValue,
HttpServletRequest request) {
request.setAttribute("reqParam", reqParamValue);
return "forward:/someOtherUrl";
}
you can use path variable such as follow without need to use query string parameter:
#RequestMapping(value="/mapping/parameter/{reqParam}", method=RequestMethod.GET)
public #ResponseBody String byParameter(#PathVariable String reqParam) {
//Perform logic with reqParam
}

Spring RequestMapping: Get path with slashes

Is there a way to get the first part of the url path, before /c:
Thats it: /Category1/Subcategory1.1/Subcategory1.1.1/c/{categoryCode:.*}
#Controller
#RequestMapping(value = "/**/c")
public class CategoryPageController {
#RequestMapping(value = "/{categoryCode:.*}", method = RequestMethod.GET)
public ModelAndView viewCategory(#PathVariable String categoryCode,
final HttpServletRequest request) {
String categoryPath = ...
I tried to use AntPathMatcher (extractPathWithinPattern) but I'm not able to define the correct pattern.
inject the request object by simply adding the the HttpServletRequest to the method signature, and
then access the Request Url by calling getRequestURL().
(oh and auto converting answers to comments, stackoverflow jumps the shark)

Not able to access SpringContext after integrate Atmosphere framework with spring MVC

As I mentioned in the title that After integrating Atmosphere framework with Spring MVC, I want to access current LoggedIn User by the help of SecurityContext(Or Authentication), But gives me null when I send the ajax request from the JSP page(client side).
Is there any problem with my code or some other problem. Below are my MyController.java and JSP files
MyController.Java
#Controller
public class MyController {
#Autowired
PartyManagementService partyManagementService;
#RequestMapping(value = "/websockets", method = RequestMethod.POST)
#ResponseBody
public String post(final AtmosphereResource event, #RequestBody String message)
throws JsonGenerationException, JsonMappingException, IOException {
User user = (User)SecurityContextHolder.getContext().
getAuthentication().getPrincipal();
String username = user.getUsername();
Person person = partyManagementService.getPersonFromUsername(username);
logger.info("Received message to broadcast: {}", message);
final int noClients = event.getBroadcaster().getAtmosphereResources().size();
event.getBroadcaster().broadcast(message);
return " message successfully send ";
}
}
home.jsp
In my home jsp, I provide ajax request which pushes the message to the server.

How to send data to a redirected URL spring mvc

I have an URL which redirects to another URL when called. I would like to pass some data along with the redirection.
For example I have this method:
#RequestMapping("efetuaEnvioEmail")
public String efetuaEnvioEmail(HttpServletResponse response) throws IOException {
System.out.println("efetuaEnvioEmail");
return "redirect:inicio";
}
Which redirects to this one:
#RequestMapping("inicio")
public String Inicio(HttpServletRequest request) throws IOException {
return "Inicio";
}
I would like to pass some data informing that everything went fine on the first method.
I have tried some methods of HttpServletRequest and HttpServletResponse but I couldn't have anything.
Use RedirectAttributes to pass any data between handler methods:
#RequestMapping("efetuaEnvioEmail")
public String efetuaEnvioEmail(RedirectAttributes rattrs) {
rattrs.addAttribute("string", "this will be converted into string, if not already");
rattrs.addFlashAttribute("pojo", "this can be POJO as it will be stored on session during the redirect");
return "redirect:inicio";
}
#RequestMapping("inicio")
public String Inicio(#ModelAttribute("pojo") String pojo) {
System.out.println(pojo);
return "Inicio";
}

Spring-MVC 3.1: Forwarding A Request From One Controller Function To Another

I'm using Spring 3.1. I have a controller function that takes in a command object ( a data holder ) submitted via a FORM and does some processing :
#RequestMapping(value = "/results", method = RequestMethod.POST)
public String toResultsScreen(#ModelAttribute("ssdh") SearchScreenDataHolder ssdh,
BindingResult bindingResult,
ModelMap model,
HttpSession session) {
if (bindingResult.hasErrors()) {
logger.debug("Error returning to /search screen");
return "search";
}
netView = "results";
// do stuff
return nextView;
} // end function
Some user would like to programmatically make GET links to obtain information from our site and I would like to set up another handler that would handle that request. It would create a new installation of that the command object ( ssdh ) and populate it with the parameters sent via the GET request. Then it would pass it on to the handler above. Something like this:
#RequestMapping(value = "/pubresult")
public String toPublicResultsScreen(ModelMap model,
HttpSession session,
#RequestParam (required=true) String LNAME,
#RequestParam (required=false)String FNAME){
Search search = new Search(usertype);
// Capture the search parameters sent by HTTP
ssdh.setLast_name(LNAME);
ssdh.setFirst_name(FNAME);
// To Do: "forward this data holder, ssdh to the controller function quoted first
return nextView;
} // end function
My question is how can I forward my command/data holder object to the first controller function such that I don't have to alter the code to the first controller function in any way?
You can use RedirectAttributes object which was introduced in Spring MVC 3.1 and populate it with data you want to keep for redirection. It called PRG (POST/Redirect/GET) pattern.
#RequestMapping(value="/saveUserDetails.action", method=RequestMethod.POST)
public String greetingsAction(#Validated User user,RedirectAttributes redirectAttributes){
//setting attributes
redirectAttributes.addFlashAttribute("firstName", user.getFirstName());
redirectAttributes.addFlashAttribute("lastName", user.getLastName())
return "redirect:success.html";
}
I wrote some technical article regarding how to use it. I believe it will give you more details:
http://www.tikalk.com/java/redirectattributes-new-feature-spring-mvc-31
You should be able to set the ssdh in a ModelAttribute and simply forward it back, this way, the RequestDispatcher should be able to map it back to the /results handler:
#RequestMapping(value = "/pubresult")
public String toPublicResultsScreen(ModelMap model,
HttpSession session,
#RequestParam (required=true) String LNAME,
#RequestParam (required=false)String FNAME, Model model){
Search search = new Search(usertype);
// Capture the search parameters sent by HTTP
ssdh.setLast_name(LNAME);
ssdh.setFirst_name(FNAME);
model.addAttribute("ssdh", ssdh);
return "forward:/results";
}
Use
org.springframework.web.servlet.view.RedirectView
class from spring package to redirect to different page in spring MVC controller. The Baeldung blog page has more details
Sample code:
#RequestMapping(value = "/", method = RequestMethod.GET)
public RedirectView mainMethod() {
return new RedirectView("/login");
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView mainLogin() {
ModelAndView model = new ModelAndView("login");
return model;
}

Resources