I have a problem,my web app have a passcode form, user will give a Passcode string and app will riderict user to questions page for a spesific event. my controller will find this even by this passcode. i tried with this way but my passcode field is always null.
<form method="get" th:action="#{/findEvent(passcode=${passcode})}">
Passcode:<br>
<input type="text" th:name="${passcode}"><br>
<div>
<button type="submit">Find</button>
</div>
</form>
#GetMapping(value = "/findEvent")
public String resetPassword(#RequestParam(value="passcode",required=false) String passcode) {
if(passcode==null)
return "passcode";
Event event=eventService.findByPassCode(passcode);
List<Question> questions=questionService.findQuestionsByPasscode(passcode);
return "questions";
}
#RequestMapping(value = "/findEvent", method = RequestMethod.POST)
public String findEvent(#RequestParam("passcode") String passcode) {
Event event=eventService.findByPassCode(passcode);
List<Question> questions=questionService.findQuestionsByPasscode(passcode);
return "questions";
}
Same problem with mine
Request parameter with thymeleaf
How can i achieve this ?? can you help me
Use name="passcode" instead
<input type="text" name="passcode" value="1234" />
Since its the same as the object name, just use
#RequestParam String passcode
Related
I have some input fields in my jsp page,l want to know is it possible for values passed in those fields to be passed as URL.
I tried using #RequestParam and #PathVariable on same variable to try to retrive it and put it as URI but it didnt work
This is my jsp page form:
<body>
<form action="welcome/" method="post">
<input type="text" name="name" value="">
<input type="submit" value="go">
</form>
</body>
And this is my Controller handler method:
#PostMapping(value = "/welcome/{name}")
public String welcomeAgain(#PathVariable #RequestParam("name")String name){
return "welcome";
}
Just use #PathVariable("name") annotation. Exclude the #RequestParam annotation from your function.
I hope it helps.
To get the value passed in URL you can use #PathVariable normally with GET request.
http://localhost:8080/user/101
#RequestParam normally used with POST request for accessing the query parameter values
http://localhost:8080/user/101?param1=10¶m2=20
#PostMapping(value = "/welcome/{name}")
public String welcomeAgain(#PathVariable("name") String name){
return "welcome " + name;
}
Hello guys i have a question regarding what is mentioned in the title. Is it possible to stay on the same page and submit . I found something with javascript but it is not working for me because i m using thymleaf and spring boot. Or i just don't know how to adapt it to my case.
thymeleaf code:
<form th:action="#{/tweets/tweet}" th:object="${tweet}" method="post">
<div class="row">
<div class="col">
<input type="text" th:field="*{content}" class="form-control" placeholder="What's happening? Tell us!">
</div>
<div class="col">
<input class="form-control" type="submit" value="Submit" />
</div>
</div>
</form>
the controller class:
#Controller
#RequestMapping("tweets")
#Slf4j
public class TweetController {
private TweetService tweetService;
public TweetController(TweetService tweetService) {
this.tweetService = tweetService;
}
#PostMapping("/tweet")
#ResponseStatus(CREATED)
public Tweet tweet(#Valid #ModelAttribute("tweet") Tweet tweet, Principal
principal, BindingResult result) {
if(result.hasErrors()){
//do somethign
}
if (!tweet.getContent().equals(null) && !tweet.getContent().equals("") && !tweet.getContent().isEmpty()) {
tweetService.createTweet(tweet.getContent(), principal);
}
}
#GetMapping("/")
public String goToIndex(Model model){
model.addAttribute("tweet",new Tweet());
return "overview";
}
And i have server.context-path=/api
I have one more additional question to this topic. When i wanted to redirect it to another page i was getting a blank page. Not an error not an exception just a blank page. Any help ? I m new to this.
Yes, this is possible using ajax. I would recommend doing it using jQuery though. So, if you would like to submit your form and stay in the same page, you could do the following.
HTML
<form id="tweet-form" th:action="#{/tweets/tweet}" th:object="${tweet}" method="post">
<div class="row">
<div class="col">
<input type="text" th:field="*{content}" class="form-control" placeholder="What's happening? Tell us!">
</div>
<div class="col">
<input id="submit-form" class="form-control" type="button" value="Submit" />
</div>
</div>
</form>
Changes:
Added an id to the form.
Added an id to your input.
Change submit input's type for button.
jQuery
$('#submit-form').on('click', function() {
var form = $('#tweet-form');
$.ajax({
url: form.attr('action'),
data: form.serialize(),
type: post,
success: function(result) {
// Do something with the response.
// Might want to check for errors here.
}, error: function(error) {
// Here you can handle exceptions thrown by the server or your controller.
}
})
}
Controller
#PostMapping("/tweet")
#ResponseStatus(CREATED)
public Tweet tweet(#Valid #ModelAttribute("tweet") Tweet tweet, Principal
principal, BindingResult result) {
if(result.hasErrors()){
// Throw an exception or send a null Tweet.
}
if (!tweet.getContent().equals(null) && !tweet.getContent().equals("") && !tweet.getContent().isEmpty()) {
tweetService.createTweet(tweet.getContent(), principal);
}
// You are returning a Tweet, so you must return something.
return tweet;
}
Your controller pretty much stay the same. Just remember to return something.
Your example doesn't show what the tweet() method returns. It should return a Tweet object but doesn't have any return value. What are you attempting to do with that return value? If you're not handling it with Javascript someway, then get rid of #ResponseStatus(CREATED) and return a either a Model or a String pointing to your html file, like so:
#PostMapping("/tweet")
public String tweet(#Valid #ModelAttribute("tweet") Tweet tweet, Principal
principal, BindingResult result) {
if(result.hasErrors()){
//do somethign
}
if (!tweet.getContent().equals(null) && !tweet.getContent().equals("") && !tweet.getContent().isEmpty()) {
tweetService.createTweet(tweet.getContent(), principal);
}
return "redirect:/name-of-html-file";
}
reference
If you want thymeleaf to handle the tweet and the HttpStatus you could instead return something along the lines of
ModelAndView model = new ModelAndView("your-view");
model.addAttribute(tweet);
model.setStatus(HttpStatus.CREATED);
return model;
I have currently built a controller for my index page which is also a login page.
With the controller, I'm mapping the jsp if the login credentials of the user matches and if it doesn't I want to redirect to the index page with message "Sorry Username, Password error."
Here's the code:
Controller
if(uname.equals(inf.getUsername())&&pwd.equals(inf.getPassword())&&dept.equals(inf.getDept()))
{
req.getSession().setAttribute("uname",inf.getName());
return new ModelAndView("employeeLoginResult", "message", message1);
}
else if(uname.equals(inf2.getUsername())&&pwd.equals(inf2.getPassword())&&dept.equals(inf2.getDept()))
{
req.getSession().setAttribute("uname",inf2.getName());
return new ModelAndView("adminLoginResult", "message", message2);
}
else
{
return new ModelAndView("redirect:/index.jsp","message","Sorry");
}
The index page
<b><span class="heading">LOGIN USER</span></b>
<div class="container">
<form action="login.html" method="Post">
<div class="form_style">
<input type="text" name="username" placeholder="Enter Username"/>
<input type="password" name="pwd" placeholder="Enter password"/>
<select name="dept">
<option>IT</option>
<option>Admin</option>
<option>HR</option>
<option>Marketing</option>
</select>
<input type="Submit" value="submit">
<span class='disp'>${message}</span>
</div>
</form>
</div>
The redirect works but the message get appended in the Url like this:
I just want to print "Sorry username password error" on the index file with ${message}
My question:
Is it possible to use ModelAndView with RedirectView or if it isn't are there any other solution to send redirect to my index page with using ModelAndView?
Any suggestions or opinions are appreciated.
Thanks for the same.
"The redirect works but the message get appended in the Url " this is the expected behaviour of normal redirection attributes.
You can use flash attributes to redirect by not revealing the URL in the browser.
For example refer below code :
#RequestMapping(value = "/accounts", method = RequestMethod.POST)
public String handle(Account account, BindingResult result, RedirectAttributes redirectAttrs) {
if (result.hasErrors()) {
return "accounts/new";
}
// Save account ...
redirectAttrs.addAttribute("id", account.getId()).addFlashAttribute("message", "Account created!");
return "redirect:/accounts/{id}";
}
Refer this : https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/mvc/support/RedirectAttributes.html
Can you add a class like MyConfig
#EnableWebMvc
#Configuration
public class MyConfig {
#Autowired
private RequestMappingHandlerAdapter requestMappingHandlerAdapter;
#PostConstruct
public void init() {
requestMappingHandlerAdapter.setIgnoreDefaultModelOnRedirect(true);
}
}
I am still relatively new to springMVC, I currently have some code, that will take an input from a <form:input> on a jsp page, and create different lists depending on the input(providing I enter the correct String). I would like to transition this into a button instead, so I could have four buttons that will return a different String, for example "one", "two", "three" and "four". That way there is no typing needed from the user.
I see that there is a <form:button> available but I do not know how I could return the String value from this. Also I have looked into angularJS and seen that you can call a function onClick. But again, I don't know what the implementation would have to be to tie it into my Controller. I am just not really sure how I can implement this. Any help would be appreciated.
This is what I have being implemented at the moment :
<form:form commandName="input">
<label>Enter Value</label>
<form:input path="listType" class="inputbox" />
<br>
<input type="submit" class="button" value="Enter" />
</form:form>
This takes the input and stores it in an object :
#Controller
#SessionAttributes("input")
public class EventController {
#RequestMapping(value = "/event", method= RequestMethod.GET)
public String displayEvent (Model model) {
AccessInput userInput = new AccessInput();
model.addAttribute("input", userInput);
System.out.println("finished get method");
return "event";
}
#RequestMapping(value = "/event", method= RequestMethod.POST)
public String processEvent(#ModelAttribute("input")AccessInput userInput) {
System.out.println(userInput.getListType()); //just so I know what value it has
return "redirect:results.html";
}
This is the controller that creates my list based on the string that I pass through to the object
#RestController
#SessionAttributes("input")
public class ReportController {
#RequestMapping(value="/events")
public List<Appliance> getEvents(#ModelAttribute("input")AccessInput userInput) {
List<Appliance> events = new ArrayList<>();
events = ProcessChoice.ofList(userInput.getListType());
System.out.println(userInput.getListType());
return events;
}
}
Edit:
Just to note I have resolved this, I followed the example given by Vipin Dubey, I had to change my controller. I removed the POST method and added in a #RequestParam as a parameter, and redirected the buttons on the event.jsp to "results.html?input=one" then took this value and added it to my model to store it in the session.
#Controller
#SessionAttributes("URLparam")
public class ResultController {
#RequestMapping(value = "/results.html", method = RequestMethod.GET)
public String buttonSelect(Model model, #RequestParam("input")String input) {
model.addAttribute("URLparam", input);
System.out.println(input);
return "result";
}
}
You have two options :
1. Short and recommended way :
Use a link and style it as a button and you can directly call your controller
<a class="btn" href="/events?input=one">One</a>
<a class="btn" href="/events?input=two">two</a>
<a class="btn" href="/events?input=three">three</a>
<a class="btn" href="/events?input=four">four</a>
2. Use jQuery or JavaScript to submit the form based on clicked button using a hidden input field in your form
<!-- Buttons with classes -->
<div id="target">
<button class="one">One</button>
<button class="two">two</button>
<button class="three">three</button>
<button class="four">four</button>
</div>
<!-- Your form -->
<form:form commandName="input" id="myForm">
<input type="hidden" name="inputbox" id="inputbox" value=""/>
</form:form>
// You will have to do this for each of the button which is not a recommended way
$( ".one" ).click(function() {
$('input[name="inputbox"]').val("one");
//var a = $('input[name="inputbox"]').val();
//alert(a);
$( "#myForm" ).submit();
});
#ModelAttribute annotation(Spring) allows for html to create an object.
For example there is a class
class Vasya{
int id;
String name;
//set get
}
and html form
<form action='path'>
<input type='text' name = 'id'/>
<input type='text' name = 'name'/>
<input type='submit'/>
</form>
#controller method:
#RequestMapping("/path")
public String processSkill( #ModelAttribute Vasya vasya) {...}
here it works.
Question:
how can I write html form using *checkbox*es for id and name that my controller method works?
Dont understand how to pass id using checkbox, but you can pass checkbox value that way:
#RequestMapping(value = "/test", method = RequestMethod.POST)
public String form(#RequestParam(required = false) Integer check) {
if(check != null) { // if checkbox is not selected it is null
System.out.println(check);
}
return "your-view";
}
jsp:
<form action="${home}/test" method="POST">
<input type="checkbox" value="1" name="check" />
<input type="submit" />
</form>