OK this has to be an easy one for someone who is experienced but I am just not seeing it. Trying to return a value from the controller back to the screen. All I ever get is "${user.email}" to show up in my input field.
<input type="email" class="form-control" name="email" disabled=true value=${user.email}>
My java controller below. Debugging it i verified values are all there and nothing is missing as the "credentials" object are coming from another screen. The screen renders fine to the "loggedIn" screen but the input field(above) as it passes the "exists" check. Why wont the email render on the input field?
#Controller
public class HomeController {
#RequestMapping(value = "/loggedIn", method = RequestMethod.POST)
public ModelAndView loggedIn(Credentials credentials, Model model) {
ModelAndView mv = new ModelAndView();
ScraperMqSQL aDb = new ScraperMqSQL();
boolean exists = false;
try {
User aUser = new User();
aUser.setUSer(credentials.getUserName());
aUser.setEmail(credentials.getUserName());
aUser.setPassWord(credentials.getPassWord());
mv.addObject("user", aUser);
model.addAttribute("user", aUser);
exists = aDb.doesUserExist(aUser);
} catch (SQLException e) {
e.printStackTrace();
}
if(exists) {
mv.setViewName("loggedIn");
}else {
mv.setViewName("notify");
}
return mv;
}
}
It might be possible because you are using this.
aUser.setEmail(credentials.getUserName());
You should set email here.
Since Thymeleaf is built in such a way that you can view and edit the HTML templates as plain HTML, you must identify to the Thymeleaf engine when you want it to perform replacement. In this case, value (as most HTML tags) is simply used as-is. If you want Thymeleaf to insert a dynamic value, use th:value or data-th-value.
Related
My objective is to pass model attributes from controller to JSP page during a redirect and avoid the attribute being displayed in URL. The source code below is validating login from datastore using java data objects.
Controller:
#Controller
public class LoginController {
int count;
PersistenceManager pm = PMF.get().getPersistenceManager();
//Instance of data class
User user;
ModelAndView modelAndView=new ModelAndView();
#RequestMapping(value="/Login",method = RequestMethod.POST)
public ModelAndView loginValidate(HttpServletRequest req){
//Getting login values
String uname=req.getParameter("nameLogin");
String pswd1=req.getParameter("pswdLogin");
count=0;
user=new User();
//Generating Query
Query q = pm.newQuery(User.class);
q.setFilter("userName == userNameParam");
q.declareParameters("String userNameParam");
try{
List<User> results = (List<User>) q.execute(uname);
for (User u: results) {
String userName=u.getUserName();
if(userName.equals(uname)){
System.out.println(u.getPassword());
if(u.getPassword().equals(pswd1)){
count=count+1;
modelAndView.setViewName("redirect:welcome");
modelAndView.addObject("USERNAME",uname);
return modelAndView;
}
//rest of the logic
}
JSP:
<h1>Welcome ${USERNAME} </h1>
My current URL is /welcome?USERNAME=robin
My goal is to display it as /welcome
Also, my page is supposed to display "Welcome robin" whereas it displays only Welcome.
RedirectAttributes only work with RedirectView, please follow the same
#RequestMapping(value="/Login",method = RequestMethod.POST)
public RedirectView loginValidate(HttpServletRequest req, RedirectAttributes redir){
...
redirectView= new RedirectView("/foo",true);
redir.addFlashAttribute("USERNAME",uname);
return redirectView;
}
Those flash attributes are passed via the session (and are destroyed immediately after being used - see Spring Reference Manual for details). This has two interests :
they are not visible in URL
you are not restricted to String, but may pass arbitrary objects.
You need to be careful here because I think what are you trying to do is not supported for a good reason. The "redirect" directive will issue a GET request to your controller. The GET request should only retrieve existing state using request parameters, this is the method contract. That GET request should not rely on a previous interaction or on any object stored some where in the session as a result of it. GET request is designed to retrieve existing (persisted) state. Your original (POST) request should have persisted everything you need for you GET request to retrieve a state.
RedirectAttributes are not designed to support you in this case, and even if you managed to correctly use it it will only work once and then they will be destroyed. If you then refresh the browser you will get an application error because it cannot find your attributes anymore.
I have just joined a company that using Spring Framework. I am used to using ASP.NET and for some reason I can't seem to get my controller to find the view.
It is using a redirect and selecting the name of a company to see what customers each company has(Yes ID would be better and in most places this company uses ID). However, for some reason, at their highest level, they left it to text.
The File Structure goes
Vendor
VendorLandingPage
EmployerList
Controller
#RequestMapping(value = "{vendorName}/EmployerList", method = RequestMethod.POST)
public String VendorLandingPage(#PathVariable("vendorName") String vendorName, Map<String, Object> model)
{
try{
List<Customer> CustomerList = CustomerRepository.getCustomerList(vendorName);
model.put("CustomerList", CustomerList);
}
catch(Exception ex)
{
//Throw error..could not contact database
//
}
//Owner owner = new Owner();
//model.put("FileObject", owner);
return "redirect:Vendor/EmployerList";
}
View Button Section
<td>
<spring:url value="{vendorName}/EmployerList.html" var="viewUrl">
<spring:param name="vendorName" value="${vendor.vendorName}"/>
</spring:url>
View Employer List
</td>
I have been using ModelAndView as the object type in my controller to handle method to do data binding with front-end html form.Such as this:
#RequestMapping(value = "/postSth", method = RequestMethod.POST)
public ModelAndView postSomething(#RequestParam("name") String name){
ModelAndView model = new ModelAndView("displayPage");
model.addObject("name", name);
return model;
}
This method will allow me to bind the name and I can display the name to the displayPage.jsp after the POST method. displayPage is the JSP page name and by using the InternalResourceViewResolver from Spring framework.
Lately I have been using jQuery ajax function to pass the data to my controller, and I am working on method looks like this:
#RequestMapping(headers = "Content-Type=application/json", value = "/postSth", method = RequestMethod.POST)
#ResponseStatus(value = HttpStatus.OK)
public ModelAndView postSomething(#RequestBody String name){
ModelAndView model = new ModelAndView("displayPage");
model.addObject("name", name);
return model;
}
I noticed I can successfully grabbing the JSON string with this controller, but this method will not redirect my webpage to the displayPage and the data binding with .addObject no longer work.
Why it does not work? How do I change it to still allow me to direct to the displayPage.jsp? I understand I can do the redirect with javascript at front-end, but it is not what I want to do.
I understand your requirement as you trigger an ajax call but instead of loading the output of data to current jsp you need to populate it in new jsp.
I have had the similar requirement, I used jquery load() to implement it. It worked fine in my case. Basically its like a 3 step process;
Trigger Ajax call to the controller to get the required data to be loaded on new jsp.
use load() once required data is available to load the new jsp in current page.(you can use some div to load it, if you want to completely replace current page then empty the contents of current page and laod with new jsp)
Write javascript/jquery codes to manipulate the dom in new JSP which we rendered on previous step.
Below is the snippet of how it can be done.
#RequestMapping(headers = "Content-Type=application/json", value = "/postSth", method = RequestMethod.POST)
#ResponseStatus(value = HttpStatus.OK)
public String postSomething(#RequestBody String name){
return model;
}
<div id='currentContent'>
<!--Existing content -->
</div>
var ajaxResult = '';
$.ajax({
type : POST,
url: "postSth",
async:false}).then(function(data){
//DIV ID here would be the ID which you need to have in your page to append the HTML content.
//if you want to completely reload the page then use the id where your current contents are displayed
//Inside your somenewjsp.jsp you can write your jquery codes to access the variable ajaxResult on document ready
ajaxResult = data;
$('#currentContent').load('/somenewjsp.jsp');
});
});
Please share your results on this approach.
Hiii Guys, I am working on a project which is using Spring MVC and Hibernate framework. My problem is that I am working on a Form and in the form a Option Box working. I want to change a text field value on change of option box value.
I already Try this :-
<script type="text/javascript" >
$(document).ready(function(){
$("#venderid").change(function(){
$.getJSON("getVenderById.htm", {venderId: $(this).val()},
function(vender){
var data = JSON.parse(vender);
var mail = data.email;
$("#mail").html(mail);
}
);
});
});
</script>
Vender.java
public class Vender {
private Integer venderid;
private String vendername;
private String email;
private String contact;
//Setters and getters
}
Controller:-
#RequestMapping(value = "/getVenderById.htm")
#ResponseBody
public ModelAndView getVender(#RequestParam("venderId") int vId){
ModelAndView mav = new ModelAndView();
mav.addObject("vender", venderDAO.findById(vId));
System.out.println("=========Ajax Calling============");
return mav;
}
Every thing is working fine but how to filled the textbox of e-mail according vender id . Is there any mistake in Callback function , or how to utilize the value of vender object. And one more thing on Apache server console window ========Ajax Calling======= printing means data is coming from the database. But how do i utilize it please help . And thanks in advance.
In you ajax callback handler you are expecting vendor, whereas you are sending MAV in your controller. Try doing this in your controller.
#RequestMapping(value = "/getVenderById.htm")
#ResponseBody
public Vender getVender(#RequestParam("venderId") int vId){
return venderDAO.findById(vId);
}
I would like to add to minion's answer you need to remove .htm as you are expecting JSON in response.
And it's a better practice to use ContentNegotiatingViewResolver and set JSON response as default.
Here is a link Content Negotiation using Views at spring.io
Please debug or console.log the vender value in the callback like this:
function(vender){
console.log(vender);
var data = JSON.parse(vender);
var mail = data.email;
$("#mail").html(mail);
}
Then copy the value here
I am writing Web application and trying to integrate Spring Web MVC 3.0 framework. I want to validate input field from XHTML page. The form (what holds one input field) submitted, but then the page is redirected. If you explicitly redirect to the same form (registration.htm) the value entered in the input field disappears, what is not al right. I want the value stay in the input field.
This is my controller:
#Controller
public class UserNameController
{
#InitBinder()
protected void initBinder(WebDataBinder binder) {
binder.setValidator(new UserNameValidator());
}
#RequestMapping(value="userName.htm",method=RequestMethod.POST)
public ModelAndView userName(#Valid #RequestParam("uName") String uName)
{ System.out.println("__________________________ "+ uName);
return new ModelAndView("registration");
}
public class UserNameValidator implements Validator
{
public boolean supports(Class<?> clazz)
{
return User.class.isAssignableFrom(clazz);
}
public void validate(Object target, Errors errors)
{
System.out.println("=======================");
User user = (User) target;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "uName", "field.required", "Required field");
if(!errors.hasFieldErrors("uName"))
{
// if(user.existUser() == true)
// {
//}
}
}
}
}
Validation does not work either. What is the way to get back on the form what would keep entered value?
Best regards
What is the way to get back on the form what would keep entered value?
Do redirect only when you successfully register user, and just return him to registration page when validation fails.
See also: Problems passing form feedback between controllers to re-display a form error message
I figured out myself. The main thing what was missing is value="${user}" snippet of code in XHTML code. Likewise I needed model.addAttribute("user", user); I wasted a lot of time on this......