Unable to redirect the url in Spring - java

I wanna implement url encoding like http://www.host.abc/action?view=jobs in my spring web app but unable to get the job done through my strategy, which is
#Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
return "home";
}
#RequestMapping(value = "/home/action?view=jobs", method = RequestMethod.GET)
public String showJobs(Model model) {
//some stuff goes here
return ("/home/action?view=jobs");
}
}
home.jsp is
<c:if test="${param.view == 'jobs' }">
<!-- List of Jobs -->
</c:if>
this give me warning
WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/jobsnetwork/home/action] in DispatcherServlet with name 'springDispatcher'
and finally I added maping to WebApplicationInitializer class as
public class AppInit implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext context) {
XmlWebApplicationContext rootContext =
new XmlWebApplicationContext();
rootContext.setConfigLocation("/WEB-INF/spring/root-context.xml");
context.addListener(new ContextLoaderListener(rootContext));
// Create the dispatcher servlet's Spring application context
XmlWebApplicationContext servletContext =
new XmlWebApplicationContext();
servletContext.setConfigLocation("/WEB-INF/spring/appServlet/servlet-context.xml");
// add the dispatcher servlet and map it to /
ServletRegistration.Dynamic dispatcher =
context.addServlet("springDispatcher", new DispatcherServlet(servletContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
dispatcher.addMapping("/home/action");// added mapping here
}
}
the above stuff is not working

Your mapping should contain the path only ("/jobsnetwork/home/action"), not the request parameters ("?view=jobs"):
#RequestMapping(value = "/jobsnetwork/home/action", method = RequestMethod.GET)
public String showJobs(#RequestParam("view") String view, Model model) {
if (view.equals("jobs")) {
// do stuff if ?view=jobs
} else {
// do stuff if not ?view=jobs
}
}

Just try to redirect:-
#Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
return "home";
}
#RequestMapping(value = "/action", method = RequestMethod.GET)
public String showJobs(#RequestParam("view") String view,Model model) {
//some stuff goes here
return "redirect:/action?view=jobs";
}
}

Related

Spring changed session values

In Spring application, I need to hold user value until I don't remove or destroy.
According to it, I have used the HttpSession in the Controller as follows
#Controller
public class MyController {
#RequestMapping(value = { "/search" }, method = RequestMethod.POST) //this hander called once
public String search(SearchVo aSearchVo, BindingResult result,
ModelMap model,HttpSession httpsession) {
if (result.hasErrors()) {
model.addAttribute("searches", new SearchVo());
return "home";
}
httpSession.setAttribute("searchstring", aSearchVo.getSearchString());
return "caseResult";
}
#SuppressWarnings("unchecked")
#RequestMapping(value = { "/filtersearch" }, method = RequestMethod.POST) //This handler call again and again
public String filterSearch(#ModelAttribute("filter") FilterVo fvo,ModelMap model , HttpSession httpSession){
String searchKeyWorld=httpSession.getAttribute("searchstring");
System.out.println(searchKeyWorld);
searchKeyWorld+=fvo.getFilterWorld();
return "caseResult";
}
}
but in the session variable, the value gets changed automatically as in the last filter; as I haven't set any session variable in filtersearch Handler
You need to use #SessionAttributes for putting variable in http session.
This is a class level annoation.
#Controller
#SessionAttributes("searches")
public class MyController{
#RequestMapping(value = { "/search" }, method = RequestMethod.POST) //this hander called once
public String search(SearchVo aSearchVo, BindingResult result,
ModelMap model,WebRequest webRequest) {
if (result.hasErrors()) {
model.addAttribute("searches", new SearchVo());
return "home";
}
model.addAttribute("searches", new SearchVo());
//For removing anything from session
//webRequest.removeAttribute("searches", WebRequest.SCOPE_SESSION);
return "caseResult";
}
}

This webpage has a redirect loop in Spring mvc

I'm struggling with this strange behavior of This webpage has a redirect loop, I have a link in home page
<a href='<spring:url value="/url?view=offers" />'>offers</a>
and my controller is
#Controller
public class OfferController {
#Autowired
private OfferService offerService;
#RequestMapping(value = "/url", method = RequestMethod.GET)
public String showOffers(#RequestParam("view") String view, Model model) {
model.addAttribute("offers", offerService.findAll());
return "redirect:/url?view=offers";
}
}
this above code is causing the issue, what is wrong with above code.
You have an /url URL mapping, and then after access /url, the code redirect it to /url?view=offers. That is the reason you get a redirect loop.
Maybe this is your purpose:
#Controller
public class OfferController {
#Autowired
private OfferService offerService;
#RequestMapping(value = "/url", method = RequestMethod.GET)
public String showOffers(#RequestParam(value = "view", defaultValue = "offers") String view, Model model) {
model.addAttribute("offers", offerService.findAll());
return "url";
}
}

Unable to redirect from one controller to another controller-Spring MVC

I am new to spring MVC and facing some error.
I have two controllers as below
1) LoginController.java
#Controller
#RequestMapping("/log")
public class LoginController {
#Autowired
private LoginService service;
#RequestMapping(value="login.spring",method=RequestMethod.GET)
public ModelAndView prepareLoginForm()
{
System.out.println("In get");
return new ModelAndView("Login", "login", new Login());
}
#RequestMapping(value="login.spring",method=RequestMethod.POST)
public ModelAndView processLogin(#ModelAttribute("login") Login login,BindingResult result)
{
int i=service.validateLogin(login);
if(i==0){
return new ModelAndView("redirect:login.spring");
}
ModelAndView view=new ModelAndView("redirect:Customer/Searchform.spring");
return view;
}
}
2) CustomerController.java
#Controller
#RequestMapping("/Customer")
public class CustomerController {
#Autowired
private CustomerService customerService;
#RequestMapping(value="Searchform.spring",method=RequestMethod.GET)
public ModelAndView prepareCustomer()
{
System.out.println("In customer controller");
CustomerSearchForm customerSearchForm=new CustomerSearchForm();
return new ModelAndView("CustomerSearch","customerSearchForm",customerSearchForm);
}
#RequestMapping(value="Search.spring",method=RequestMethod.POST)
public ModelAndView searchCustomer(#ModelAttribute("customer") CustomerSearchForm customerSearchForm,BindingResult result)
{
int i=customerService.serachCustomer(customerSearchForm);
if(i==1)
return new ModelAndView("Holdings");
return new ModelAndView("redirect:Customer");
}
}
So after successful login I am trying to redirect to CustomerController but in
browser url i can see that request url is
http://localhost:8080/Online_Fund_Trading/log/Customer/Searchform.spring.
As log gets added before Customer/Searchform.spring I am getting 404-The requested resource is not available error.
What changes are required to have request url as http://localhost:8080/Online_Fund_Trading/Customer/Searchform.spring.
A simple slash / is required
ModelAndView view=new ModelAndView("redirect:/Customer/Searchform.spring");
Otherwise the path will be considered relative to the path of the request you are currently handling.

Restrict Spring page view into POST only

My Spring controller looks like this:
#Controller
#RequestMapping(value = "calc")
public class CalcController {
protected final Log logger = LogFactory.getLog(getClass());
#Autowired
private MyService myService;
#RequestMapping(method = RequestMethod.GET)
public String showCalcPage(
#ModelAttribute("myModel") MyModel myModel,
Model model, HttpServletRequest request) {
// assemble page
return "calc";
}
#RequestMapping(method = RequestMethod.POST)
public String showResultsPage(
#ModelAttribute("myModel") MyModel myModel,
BindingResult result, Model model,
final RedirectAttributes redirectAttributes,
HttpServletRequest request) {
myService.evaluate(myModel);
redirectAttributes.addFlashAttribute("myModel", myModel);
model.addAttribute("myModel", myModel);
return "redirect:calc/results";
}
#RequestMapping(value = "/results")
public String showResultsPage(ModelMap model,
#ModelAttribute("myModel") final MyModel myModel,
final BindingResult bindingResult) {
// assemble page
return "results";
}
}
I have a mapping of the URL calc with both GET and POST and another for calc/results.
This works perfectly for me but whenever I try to access calc/results directly, the page still renders.
Hence I did a POST restriction to its RequestMethod like:
#RequestMapping(value = "/results", method = RequestMethod.POST)
public String showResultsPage(ModelMap model,
#ModelAttribute("myModel") final MyModel myModel,
final BindingResult bindingResult) {
// assemble page
return "results";
}
This eliminated the direct viewing of the mapping by throwing a 405 but when I submit my form from calc, the error still persists.
How do I merge these two situations that I have?
I actually just want two controllers like the one below to implement POST and page restriction but it's not working in my part (I diagnosed it to the different mapping of jsp).
#Controller
#RequestMapping(value = "calc")
public class CalcController {
protected final Log logger = LogFactory.getLog(getClass());
#Autowired
private MyService myService;
#RequestMapping(method = RequestMethod.GET)
public String showCalcPage(
#ModelAttribute("myModel") MyModel myModel,
Model model, HttpServletRequest request) {
// assemble page
return "calc";
}
#RequestMapping(value = "/results", method = RequestMethod.POST)
public String showResultsPage(
#ModelAttribute("myModel") MyModel myModel,
BindingResult result, Model model,
final RedirectAttributes redirectAttributes,
HttpServletRequest request) {
// assemble page
myService.evaluate(myModel);
model.addAttribute("myModel", myModel);
return "redirect:results";
}
}
I finally implemented both POST restriction and successful viewing of the calc/results page (but without redirect since it causes a "redirect loop" according to my Tomcat server).
Here is the final controller:
#Controller
public class CalcController {
protected final Log logger = LogFactory.getLog(getClass());
#Autowired
private MyService myService;
#RequestMapping(value = "calc", method = RequestMethod.GET)
public String showCalcPage(
#ModelAttribute("myModel") MyModel myModel,
Model model, HttpServletRequest request) {
// assemble page
return "calc";
}
#RequestMapping(value = "calc/results")
public String showResultsPage(
#ModelAttribute("myModel") MyModel myModel,
ModelMap model, final BindingResult bindingResult,
HttpServletRequest request) {
// assemble page
// apply BindingResult validation in da fyoochoor
myService.evaluate(myModel);
model.addAttribute("myModel", myModel);
return "results";
}
}
Visiting calc/results directly now throws an HTTP 500 and that will keep it secured. Just make sure to declare a page for this exception in your web.xml for aesthetics upon deployment.

defining default url for controller spring mvc3

I am new to spring mvc3 development and was facing a minor issue (which I was didn't face with ASP.Net MVC3). I want to know the process of defining a default (or landing) URL for a controller.
I have an accounts controller where I do all account management related stuff. So all my urls are mapped to this controller. I want to know that how can I map my "/accounts" url request to hit openAccountsDashboard method?
Code -
.... imports...
#Controller
#RequestMapping(value = "/accounts/*")
public class AccountController {
#RequestMapping( value = "/", method = RequestMethod.GET)
public ModelAndView openAccountsDashboard(HttpServletRequest request) {
.....
return new ModelAndView("accounts/landing");
}
#RequestMapping( value = "/change-password", method = RequestMethod.GET)
public ModelAndView openPasswordChangePage(HttpServletRequest request) {
.....
return new ModelAndView("accounts/passwordChange");
}
... other actions...
}
Any help would be great!
Thanks
Try something like this:
.... imports...
#Controller
#RequestMapping(value = "/accounts/")
public class AccountController {
#RequestMapping( value = "", method = RequestMethod.GET)
public ModelAndView openAccountsDashboard(HttpServletRequest request) {
.....
return new ModelAndView("accounts/landing");
}
#RequestMapping( value = "/change-password", method = RequestMethod.GET)
public ModelAndView openPasswordChangePage(HttpServletRequest request) {
.....
return new ModelAndView("accounts/passwordChange");
}
... other actions...
}
Then you can use url like this:
http://localhost:8080/yourwebapp/accounts/
to hit openAccountsDashboard method.
Regards,
Arek

Categories

Resources