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.
Related
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";
}
}
I am new at webservices and currently able to run my query by calling https://localhost/application/service/v1.0/contacts/account={accountId}
I want to make my url look like https://localhost/application/service/v1.0/contacts?account={accountId}
May I know How to achieve this not using QueryParam ? I am working in spring mvc
#Controller
public class ContactListResponseController extends BaseWebServiceController
{
public static final String PATH = "/v" + VERSION + "/contacts/account={accountId}";
#Autowired
private ContactService contactService;
#RequestMapping(value = PATH, method = RequestMethod.GET)
#ResponseBody
public ContactListResponseBean doGetMyAssignedAccounts (#PathVariable String accountId,
HttpServletRequest request,
HttpSession session,
HttpServletResponse response,
#ModelAttribute(User.USER_REQUEST_VAR) User user)
throws Exception
{
List<ContactSummaryWebServiceBean> contactList = contactService.getContactsListForCallPointWebService(accountId);
ContactListResponseBean result = new ContactListResponseBean(contactList);
return result;
}
}
It is a simple thing, try this:
#Controller
public class ContactListResponseController extends BaseWebServiceController
{
public static final String PATH = "/v" + VERSION + "/contacts";
#Autowired
private ContactService contactService;
#RequestMapping(value = PATH, method = RequestMethod.GET)
#ResponseBody
public ContactListResponseBean doGetMyAssignedAccounts (#RequestParam("account") String accountId,
HttpServletRequest request,
HttpSession session,
HttpServletResponse response,
#ModelAttribute(User.USER_REQUEST_VAR) User user)
throws Exception
{
List<ContactSummaryWebServiceBean> contactList = contactService.getContactsListForCallPointWebService(accountId);
ContactListResponseBean result = new ContactListResponseBean(contactList);
return result;
}
}
This sample.
#RequestMapping("/pets/{petId}")
public void findPet(#PathVariable String ownerId, #PathVariable String petId, Model model) {
// implementation omitted
}
Your code.
#Controller
public class ContactListResponseController extends BaseWebServiceController
{
public static final String PATH = "/v" + VERSION + "/contacts/{accountId}";
#Autowired
private ContactService contactService;
#RequestMapping(value = PATH, method = RequestMethod.GET)
#ResponseBody
public ContactListResponseBean doGetMyAssignedAccounts (#PathVariable String accountId,
HttpServletRequest request,
HttpSession session,
HttpServletResponse response,
#ModelAttribute(User.USER_REQUEST_VAR) User user)
throws Exception
{
List<ContactSummaryWebServiceBean> contactList = contactService.getContactsListForCallPointWebService(accountId);
ContactListResponseBean result = new ContactListResponseBean(contactList);
return result;
}
}
Ajax url = "/v" + VERSION + "/contacts/" + accountId,
:D
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";
}
}
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";
}
}
Currently i am using paging on my page which uses MultiActionController which displays a jsp page perfectly , on the same page now i want to validate a simple textfield (input/form:input) also want to retrieve name and id from a dropdown(Select option) once a link is clicked. Simple !!
Two questions
Can i use a class implements Validator? and inject it same way as simpleformcontroller in config or some other way within the controller? How? example please?
Can i use java bean in jsp -> i always get error of binding, how to indicated controller to use this bean? i have have passed as argument to my method add and also tried overriding newCommandObject
Controller.java
public ModelAndView add(HttpServletRequest request, HttpServletResponse response, Person person) throws Exception {
return new ModelAndView("userpage");
}
#Override
protected Object newCommandObject(Class clazz)
throws Exception {
return new Person();
}
I will do something like below in Spring version > 2.5
#Controller
public class YourController
{
protected final Log logger = LogFactory.getLog(getClass());
private final String yourInputJsp = "yourInputJsp";
private final String yourInputJspSuccess = "yourInputJspSuccess";
private YourService yourService;
#Autowired
#Qualifier("yourFormValidator")
private YourFormValidator validator;
#RequestMapping(value = "/yourRequest.htm", method = RequestMethod.GET)
public String referenceData(ModelMap model, HttpServletRequest request) throws Exception
{
yourService = new YourServiceImpl(ContextHandler.getWebAppContext(request));
YourFormData yourFormData = new YourFormData();
model.addAttribute("yourFormData", yourFormData);
return yourInputJsp;
}
#InitBinder()
public void initBinder(WebDataBinder binder) throws Exception {
binder.registerCustomEditor(String.class, new StringMultipartFileEditor());
}
#RequestMapping(value="/yourRequest.htm", method = RequestMethod.POST)
public String process(#ModelAttribute("yourFormData") YourFormData yourFormData, BindingResult result, SessionStatus status, HttpServletRequest request)
{
String mav = yourInputJsp;
validator.validate(yourFormData, result);
if(!result.hasErrors())
{
//Some business logic
mav = "redirect:yourInputJspSuccess.htm";
status.setComplete();
}
return mav;
}
}