It is simple page redirection example.When i click on it's button redirect page, it,s not working.It shows page not found.
final.jsp
<body>
<h2>Redirected Page</h2>
</body>
HelloController.java
#Controller
public class HelloController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String index(Model m) {
return "index";
}
#RequestMapping(value = "/redirect", method = RequestMethod.GET)
public String redirect() {
return "redirect:finalPage";
}
#RequestMapping(value = "/finalPage", method = RequestMethod.GET)
public String finalPage(Model m) {
return "final";
}
index.jsp
<body>
<h2>Spring Page Redirection</h2>
<p>Click below button to redirect the result to new page</p>
<form:form method="GET" action="/finalPage">
<table>
<tr>
<td>
<input type="submit" value="Redirect Page"/>
</td>
</tr>
</table>
</form:form>
</body>
web.xml
The returned redirect string is wrong, try: "redirect:/finalPage"
Missed / in redirect:finalpage. It should be something like this
#RequestMapping(value = "/redirect", method = RequestMethod.GET)
public String redirect() {
return "redirect:/finalPage";
}
But from where you are calling /redirect ?
Please also have a look here. Basically, you need to have a UrlBasedViewResolver subclass in your project and have the final view in there, if it's not in root.
Related
It can properly redirect away from
localhost/gwtech/trangchu
to
localhost/gwtech/search/example
But on this
localhost/gwtech/san-pham/example
it go to
localhost/gwtech/san-pham/search
but I want it like
localhost/gwtech/search/example
and show HTTP Status 405 – Method Not Allowed
My code:
<form method="post" action="search" modelAttribute="search" name="search" onsubmit="return validateSearch()">
<div class="form-group">
<input type="text" id="txtsearch" path="tensanpham" name="search-field" value="" placeholder="Nhập tên sẩn phẩm...."/>
<button type="submit"><h1>Find</h1><span class="icon fa fa-search"></span></button>
</div>
</form>
Controller
#Autowired
public HomeServiceImpl homeService;
#Autowired
private ProductServiceImpl productService;
#RequestMapping(value = {"/", "/trangchu"})
public ModelAndView home(HttpSession session) {
session.removeAttribute("LoginInfo2");
ModelAndView mv = new ModelAndView("users/index");
mv.addObject("slides", homeService.GetDataSlides());
mv.addObject("loaisp", homeService.GetLoaiSPs());
mv.addObject("nsx", homeService.GetNSXs());
mv.addObject("allsp", homeService.GetSPAlls());
mv.setViewName("users/index");
return mv;
}
#RequestMapping(value = "/search")
public void search(HttpServletRequest request,HttpServletResponse resp, #ModelAttribute("search") String search) throws IOException {
String searchfield = request.getParameter("search-field");
resp.sendRedirect("/gwtech/search/"+searchfield);
}
#Autowired
private DeProductServiceImpl deproductService;
#RequestMapping(value = {"/san-pham","/san-pham/{masp}"}, method = RequestMethod.GET)
public ModelAndView deproduct(HttpSession session,#PathVariable String masp) {
ModelAndView mv = new ModelAndView("users/detail-product");
mv.addObject("loaisp", homeService.GetLoaiSPs());
mv.addObject("nsx", homeService.GetNSXs());
mv.addObject("spbysp", deproductService.GetSPBySP(masp));
mv.addObject("allsp", homeService.GetSPAlls());
mv.setViewName("users/detail-product");
return mv;
}
When I used Search on trangchu it run very well but on san-pham it go to localhost/gwtech/san-pham/search and show HTTP Status 405 – Method Not Allowed
Try out this:
#RequestMapping(value = "/search","/san-pham/search")
public void search(HttpServletRequest request,HttpServletResponse resp, #ModelAttribute("search") String search) throws IOException {
String searchfield = request.getParameter("search-field");
resp.sendRedirect("/gwtech/search/"+searchfield);
}
I hope this will work.
You are getting this issue because you are calling the wrong URL in your form action.
<form method="post" action="search" modelAttribute="search" name="search" onsubmit="return validateSearch()">
the action="search" will add search in the current URL i.e localhost/gwtech/san-pham/search
So change your form action as below
<form method="post" action="search" modelAttribute="/search" name="search" onsubmit="return validateSearch()">
It will work now. Let me know if any doubt.
initially it is http://localhost:8080/HomeBankingSystem/login after submitting the form url coming as http://localhost:8080/signup
this is my controller
#Controller
public class HomeBankingController {
#RequestMapping(value="/login",method=RequestMethod.GET)
public String login(){
System.out.println("###########################");
return "login";
}
#RequestMapping(value="/signup",method=RequestMethod.POST)
public #ResponseBody String signup(){
System.out.println("value################33");
return "success";
}
You are missing your context path,
Into your login button add the next:
Login
[EDIT]:
Here the answer to be more readable:
<form action="${pageContext.request.contextPath}/login" method="POST">
<button type="submit" class="button button-block"/>Get Started</button>
</form>
I am trying to get a value from thymeleaf input into my java class.
Simple script from thymeleaf
<h1>Form</h1>
<form action="#" th:action="#{/index}" th:object="${emails}" method="post">
<p>Enter Emails: <input type="text" th:field="*{email}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
How would I be able to retrieve emails into my java class?
Controller
#Controller
#RequestMapping(method = RequestMethod.GET)
public class IndexController {
#RequestMapping(value = "/index", method = RequestMethod.GET)
public ModelAndView getdata() throws IOException {
ModelAndView model = new ModelAndView("index");
model.addObject("emails", new MailModel());
return model;
}
#PostMapping("/index")
public String emailSubmit(#ModelAttribute MailModel emails) {
System.out.println(emails.getEmail());
return "index";
}
Error Message
Ambiguous handler methods mapped for HTTP path 'http://localhost:8080/': {public org.springframework.web.servlet.ModelAndView com.spring.web.controller.IndexController.getdata() throws java.io.IOException, public java.lang.String com.spring.web.controller.IndexController.emailSumbit(com.spring.web.model.MailModel)}
My Application is created with Springboot, Java, and Thymeleaf. What am I doing wrong? Is it possible that ModelandView does not work with PostMapping? I also followed https://spring.io/guides/gs/handling-form-submission/ and I got that sample working, but when I tried to follow the logic and implement into my project. It did not work.
Before declaring your controller, you are setting the RequestMethod to GET everywhere. On the methods you are setting them again, which is ambigous.
Remove the #RequestMapping(method = RequestMethod.GET) in line 2. This should fix the mentioned problem.
I had written a code for the passing the parameter but in the login page it is not displaying the parameter can anyone help me?My home page code as shown below
<h1>
<form:form action="./loginPage" method="GET" >
<input type ="text" value="abc" id="name">
<input type ="submit" value ="Login">
</form:form>
</h1>
my controller page:
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Model model) {
return "home";
}
#RequestMapping(value = "/loginPage", method = RequestMethod.GET)
public String redirect(#ModelAttribute("name")String name,BindingResult result,Model model) {
model.addAttribute(name);
if(result.hasErrors()){
return "home";
}else{
model.addAttribute("name",name);
return "loginPage";
}
}
My login page to display the parameter:
<h1>
Welcome to login Page
</h1>
<p>The value is:${name}</p>
When collecting input, there are a couple of ways to go, I'll go over two options here:
You can use a command object and bind that as an attribute in which case you would have something like this:
public class LoginForm {
#NotNull(message="Name is required")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
In your controller you would:
#RequestMapping(value="/login", method= { RequestMethod.POST } )
public String redirect(#ModelAttribute("LoginForm") #Valid LoginForm loginForm, BindingResult bindingResult, Model model) {
if(bindingResult.hasErrors()){
return "home";
}
model.addAttribute("name", loginForm.getName());
return "loginPage";
}
In your JSP (with bootstrap classes) something like this, where you bind the form object to the form element which allows you to then bind the attribute "name" to the input field.
<form:form method="post"
commandName="loginForm"
action="/login"
role="form">
<form:errors path="name" id="name-errors" element="div" cssClass="alert alert-danger" />
<form:input path="name" cssClass="form-control" placeholder="Your name" />
<input type="submit" value="Submit" class="btn btn-primary" />
</form:form>
You can use request parameter binding to just pluck a field from a query string or form. However the downside is you can't use build in form validation and you want to redraw a form after an error you'll need to pass all the parameters back to repopulate it manually.I
#RequestMapping(value = "/loginPage", method = RequestMethod.GET)
public String redirect(#RequestParam(value="name", required=false) String name, Model model) {
if(name == null || name.length() == 0) {
return "home";
}
model.addAttribute("name",name);
return "loginPage";
}
For what it looks like your trying to do I'd recommend you use the command object binding approach. Also if you are using spring MVC for authentication, you should take a look at spring security. While the configuration can be a little frustrating it does provide a standard way to handle authentication and authorization.
http://docs.spring.io/autorepo/docs/spring-security/3.2.x/guides/hellomvc.html
I think that Model is request scoped. You will have to use Sessions
I have an issue with form processing using Thymeleaf and Spring-MVC.
This is my view:
<html xmlns:th="http://www.thymeleaf.org">
<head>
</head>
<body>
<div class="container" id="containerFragment" th:fragment="containerFragment">
<form
action="#"
th:action="#{/search}"
th:object="${searchInfo}"
method="post" >
<fieldset id="search-query">
<input
type="text"
name="search"
value=""
id="search"
placeholder="Search for user"
required="required"
th:value="*{searchQuery}" />
<input
type="submit"
value="Search"
name="submit"
class="submit"/>
</fieldset>
</form>
</div>
</body>
</html>
this is my controller:
/** Search form */
#RequestMapping(value = "/search", method = RequestMethod.GET)
public String search(Model model) {
model.addAttribute("searchInfo", new SearchForm());
return "search";
}
/** Search form */
#RequestMapping(value = "/search", method = RequestMethod.POST)
public ModelAndView search(BindingResult result,
#Valid #ModelAttribute("searchInfo") SearchForm searchForm) {
String login = searchForm.getSearchQuery();
User user = userService.findUserByLogin(login);
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("search-results");
modelAndView.addObject("user", user);
return modelAndView;
}
and the search form is:
public class SearchForm {
String searchQuery;
public String getSearchQuery() {
return searchQuery;
}
public void setSearchQuery(String searchQuery) {
this.searchQuery = searchQuery;
}
#Override
public String toString() {
return "SearchForm [searchQuery=" + searchQuery + "]";
}
}
The issue is that login is null at this point of controller:
String login = searchForm.getSearchQuery();
It looks like a new SearchForm object created for POST method, but there are already one, which was created at GET step and should contains the search query.
I can't understand such behaviour.
Spring should map HTML form attributes to your model: SearchForm.
Spring MVC build accordions with request parameters and your model object properties and set matching properties into your model Object before pass object into your controller method.
You named HTML property(and request parameter name automatically) as id="search". But SearchForm hasn't such property. Instead it has searchQuery property. So after Spring MVC unable to set searchQuery value into your SearchForm it pass model with null attribute.
Please Change th:value="{searchQuery}" to th:field="{searchQuery}".
I hope it'll work.
It worked for me:
FormTestController.java
#Controller
public class FormTestController {
#RequestMapping(value = "/form-test-1.jhtml", method = RequestMethod.GET)
public String formTest1(#ModelAttribute("form1") Form1TestVO form1TestVO, Model model){
System.out.println("You've submited: " + form1TestVO.getName())
model.addAttribute("form1", new Form1TestVO("Form 1 test"));
return "form-test-1";
}
}
form-test-1.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.thymeleaf.org" >
<head>
<title>Form test 1</title>
</head>
<body >
<form th:object="${form1}" th:action="#{/form-test-1.jhtml}" >
<input th:field="*{name}" />
<button>Send</button>
</form>
</body>
</html>
Form1TestVO
public class Form1TestVO {
private String name;
public Form1TestVO() {
}
public Form1TestVO(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Reference