Spring MVC error validation error - java

index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<body>
<div align="center" style="margin-top:100px;">
<font face="verdana" size="2">
${welcomeMessage} <BR><BR>
${result}
<form:form action="${pageContext.request.contextPath}/login.html" method="POST" modelAttribute="loginForm">
<table>
<tr>
<td colspan="2" align="center">Spring MVC Form Demo - Login</td>
</tr>
<tr>
<td>User Name</td>
<td><form:input path="username" /> <form:errors path="username"></form:errors></td>
</tr>
<tr>
<td>Password</td>
<td><form:password path="password" /> <form:errors path="password"></form:errors></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Login" style="background-color:white;" /></td>
</tr>
</table>
</form:form>
Register if not already registered
</font>
</div>
</body>
</html>
HelloController.java
package java4s;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.annotation.Scope;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import java4s.model.Login;
#Controller
public class LoginSuccessController {
#Autowired
EmployeeService emp_service;
#RequestMapping(value = "/login", method=RequestMethod.POST)
public ModelAndView loginvalidateForm(ModelMap model, #ModelAttribute("loginForm") Login login, BindingResult result, HttpSession session) {
if(result.hasErrors()){
model.addAttribute("result", "All Fields are neccessary");
return new ModelAndView("index",model);
}
if(emp_service.validateLogin(login.getUsername(), login.getPassword()))
{
List<Employee> user_info = emp_service.getUserinfo(login.getUsername());
session.setAttribute("session_username", login.getUsername()); //Add value to session variable
model.addAttribute("result", "Login Success");
model.addAttribute("user_info", user_info);
return new ModelAndView("LoginSuccess",model);
}
else
{
model.addAttribute("result", "Login Failure");
return new ModelAndView("index",model);
}
}
}
Login.java
package java4s.model;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Login {
#NotNull
#Size(min = 3, max = 20)
private String username;
#NotNull
#Size(min = 3, max = 20)
private String password;
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
}
I am trying to put validation on the login fields when they are empty, but errors are not showing on the index page the the login fields are empty. What is the problem in the code?

You have to add the annotation #Valid ( see the spring doc for more details) :
public ModelAndView loginvalidateForm(ModelMap model, #Valid #ModelAttribute("loginForm") Login login, BindingResult result, HttpSession session) {
....
}

Don't forget to enable “mvc:annotation-driven” to make Spring MVC supports #Valid annotation.
Add the following tag to your application context XML file.
<mvc:annotation-driven />

Related

unable to link resource with controller class by using PathVariable technique in spring mvc

this is my index page:
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<h1>Employee List</h1>
<table border="2" width="70%" cellpadding="2">
<tr><th>Name</th><th>Address</th>
<th>City</th><th>Cars</th></tr>
<c:forEach var="emp" items="${list}">
<tr>
<td>${emp.name }</td>
<td>${emp.address }</td>
<td>${emp.city }</td>
<td>${emp.cars}</td>
<td>Edit
<td>Delete
</tr></c:forEach>
</table>
Add New Employee"
problem is when i click on other link than it works fine but when i click on editemp or deleteemp link,than it shows me error:The requested resource is not available
This is my controller class:
package first;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class EmpController {
#Autowired
EmployeeDao dao;
#RequestMapping("/empform")
public ModelAndView showForm()
{
return new ModelAndView("empform","command",new Employee());
}
#RequestMapping(value="/save",method=RequestMethod.POST)
public ModelAndView save(#ModelAttribute("emp") Employee employee)
{
dao.saveEmployee(employee);
return new ModelAndView("redirect:/viewemp");
}
#RequestMapping("/viewemp")
public ModelAndView viewemp()
{
List<Employee> list=dao.getAllEmployee();
return new ModelAndView("viewemp","list",list);
}
#RequestMapping(value="/editemp/{name}",method=RequestMethod.GET)
public ModelAndView edit(#PathVariable String name)
{
Employee e=dao.getbyName(name);
return new ModelAndView("empeditform","command",e);
}
#RequestMapping(value="/saveedit",method=RequestMethod.POST)
public ModelAndView saveedit(#ModelAttribute("emp")Employee employee)
{
dao.updateEmployee(employee);
return new ModelAndView("redirect:/viewemp");
}
#RequestMapping(value="/deleteemp/{name}",method=RequestMethod.GET)
public ModelAndView delete(#PathVariable String name)
{
dao.delete(name);
return new ModelAndView("redirect:/viewemp");
}
}
Please tell me,why it is unable to map with controller method specified in controller class.....thanks in advance
One thing to try for your links to to update them to use the context path:
<td>Edit
<td>Delete
This post has a few other ways that you can specify your routes in a jsp page:
[How to use relative paths without including the context root name?
Also, for the controller routes to be registered, you will need to set component scan to look for any annotations:
<context:component-scan base-package="namespace to controller class" />

Date fields coming null from view, not manipulating them at all

so I am working in a Spring MVC project where I have this class with a few Date fields and I am creating a CRUD for it. Problem is, I read an instance of the class from the database and then send it to the view for editing, and although I am not manipulating any of the Date fields, only the strings, when I collect the object using a post form, the Date fields come as null even though they came from the database with a value and I sent them to the view with that value.
The class:
package com.sophos.mat.beans;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import org.hibernate.validator.constraints.Length;
#Entity
#Table(name="T_PROYECTOS")
public class Proyecto implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#Column(name="IN_PROYECTO")
#GeneratedValue(strategy=GenerationType.AUTO, generator="SECUENCIA_IN_PROYECTO")
#SequenceGenerator(name="SECUENCIA_IN_PROYECTO", sequenceName="SECUENCIA_IN_PROYECTO", allocationSize=1, initialValue= 1)
private long id;
#Column(name="VC_NOMBRE")
#Length(max = 50, message = "El campo no puede exceder los 50 caracteres")
private String nombre;
#Column(name="VC_DESCRIPCION")
#Length(max = 200, message = "El campo no puede exceder los 200 caracteres")
private String descripcion;
#Column(name="VC_CODIGO_SOPHOS")
#Length(max = 20, message = "El campo no puede exceder los 20 caracteres")
private String codigoSophos;
#Column(name="DT_FECHACREACION")
private Date fechaCreacion;
#Column(name="VC_USUARIOACTUALIZACION")
private String usuarioActualizacion;
#Column(name="DT_FECHAACTUALIZACION")
private Date fechaActualizacion;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public String getCodigoSophos() {
return codigoSophos;
}
public void setCodigoSophos(String codigoSophos) {
this.codigoSophos = codigoSophos;
}
public Date getFechaCreacion() {
return fechaCreacion;
}
public void setFechaCreacion(Date fechaCreacion) {
this.fechaCreacion = fechaCreacion;
}
public String getUsuarioActualizacion() {
return usuarioActualizacion;
}
public void setUsuarioActualizacion(String usuarioActualizacion) {
this.usuarioActualizacion = usuarioActualizacion;
}
public Date getFechaActualizacion() {
return fechaActualizacion;
}
public void setFechaActualizacion(Date fechaActualizacion) {
this.fechaActualizacion = fechaActualizacion;
}
}
The controller:
package com.sophos.mat.controller;
import java.util.Date;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.sophos.mat.beans.Proyecto;
import com.sophos.mat.services.IProyectoService;
#Controller
public class ProyectoController {
#Autowired
private IProyectoService proyectoService;
#RequestMapping(value = "/editarproyecto/{id}", method = RequestMethod.GET)
public String editarProyectoGet(ModelMap model, #PathVariable long id){
try {
Proyecto proyectoData = proyectoService.buscarProyectoPorId(id);
model.put("proyectoData", proyectoData);
return "editarproyecto";
} catch (Exception e) {
e.printStackTrace();
return "redirect:/proyectos";
}
}
#RequestMapping(value="/editarproyecto/{id}", method = RequestMethod.POST)
public String editarProyectoPost(ModelMap model, #PathVariable long id, #ModelAttribute("proyectoData")#Valid Proyecto proyectoData, BindingResult result){
if(result.hasErrors()){
return "editarproyecto";
}
try{
proyectoData.setFechaActualizacion(new Date());
proyectoService.actualizarProyecto(proyectoData);
return "redirect:/proyectos";
}catch(Exception e){
e.printStackTrace();
return "redirect:/proyectos";
}
}
public IProyectoService getProyectoService() {
return proyectoService;
}
public void setProyectoService(IProyectoService proyectoService) {
this.proyectoService = proyectoService;
}
}
And the view: editarproyecto.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%# taglib uri= "http://www.springframework.org/tags/form" prefix="form" %>
<html>
<head>
<title>>Nuevo Proyecto</title>
<style>
.error { color: red; }
</style>
</head>
<body>
<h1>Nuevo Proyecto</h1>
<form:form method="post" modelAttribute="proyectoData">
<table >
<tr>
<td align="right">
Nombre proyecto:
</td>
<td>
<form:input path="nombre"/>
</td>
<td>
<form:errors path="nombre" cssClass="error"/>
</td>
</tr>
<tr>
<td align="right">
Descripción
</td>
<td>
<form:input path="descripcion"/>
</td>
<td>
<form:errors path="descripcion" cssClass="error"/>
</td>
</tr>
<tr>
<td align="right">
Cód. Sophos
</td>
<td>
<form:input path="codigoSophos"/>
</td>
<td>
<form:errors path="codigoSophos" cssClass="error"/>
</td>
</tr>
<tr>
<td align="right">
Usuario que actualiza
</td>
<td>
<form:input path="usuarioActualizacion"/>
</td>
<td>
<form:errors path="usuarioActualizacion" cssClass="error"/>
</td>
</tr>
</table>
<br>
<input type="submit" value="Guardar">
</form:form>
Proyectos
</body>
</html>
When processing POST, I get an exception from hibernate telling me that I'm trying to update to NULL the column 'DT_FECHACREACION' corresponding to the class field 'fechaCreacion'. As a temporary fix, I had to add in the POST method a query to the database to reset 'fechaCreacion' back to its previous value which I don't want to change and then update the entity with the rest of the captured values. That works but is ugly af and adds extra and unwanted overhead. My database is Oracle 11g. Thanks in advance folks!
PD: Very newbie spring developer, am in my internship and trying my best to get a full contract when the internship is over :D so any help will be much appreciated.
When you call the service you have to control which fields you return to the view.
Proyecto proyectoData = proyectoService.buscarProyectoPorId(id);
You can omit fields your DAO is returning with #JsonIgnore annotation.
....
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity
#Table(name="T_PROYECTOS")
public class Proyecto implements Serializable{
...
#JsonIgnore
public Date getFechaCreacion() {
return fechaCreacion;
}
....
}

Spring Boot JSP Resolution Error

So I've been playing around with Spring Boot and it's going fairly well. However, I've found myself in a weird situation and need help with it. All of my request mapping works with exception to one, for which I'm getting a 404.
My project structure is:
+Project Name
-src/main/java - Code
-src/main/resources - Resources
-src/main/webapp/views - Jsp Pages
Important java code:
Application.java
package com.demo.faisal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import com.demo.faisal.model.Task;
import com.demo.faisal.service.TaskService;
#Configuration
#ComponentScan()
//#EnableAutoConfiguration
#EnableAutoConfiguration(exclude = {ErrorMvcAutoConfiguration.class})
public class Application {
private static final Logger log = LoggerFactory.getLogger(Application.class);
public static void main(String args[]) {
SpringApplication.run(Application.class, args);
}
#Bean
public CommandLineRunner demo(TaskService taskService) {
return (args) -> {
// save a couple of customers
taskService.addTask(new Task("Learn Java"));
taskService.addTask(new Task("Learn Hibernate"));
taskService.addTask(new Task("Learn Spring"));
taskService.addTask(new Task("Learn SpringBoot"));
// fetch all tasks
log.info("Finding all tasks with getTasks():");
log.info("-------------------------------");
for (Task task : taskService.getAllTasks()) {
log.info(task.toString());
}
log.info("");
// fetch an individual customer by ID
Task task = taskService.findTask(1L);
log.info("Task found with findTask(1L):");
log.info("--------------------------------");
log.info(task.toString());
log.info("");
// fetch an individual customer by ID
task.setDescription("Learn Java Done");
log.info("Updated task description to: " + task.getDescription());
taskService.updateTask(task);
log.info("");
// Updated task
task = taskService.findTask(1L);
log.info("Updated Task (1L):");
log.info("--------------------------------");
log.info(task.toString());
log.info("");
};
}
}
Model:
package com.demo.faisal.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
//#Table(name = "${table_name})
public class Task {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String description;
public Task() {}
public Task(String description) {
this.description = description;
}
public Long getId() {
return id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return String.format("Task[id=%d, description='%s']", id, description);
}
}
Repository:
package com.demo.faisal.model;
import org.springframework.data.repository.CrudRepository;
public interface TaskRepository extends CrudRepository<Task, Long> {
}
Service:
package com.demo.faisal.service;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.demo.faisal.model.Task;
import com.demo.faisal.model.TaskRepository;
#Service
public class TaskServiceImpl implements TaskService {
#Autowired
private TaskRepository taskRepository;
#Override
#Transactional
public void addTask(Task task) {
taskRepository.save(task);
}
#Override
#Transactional
public void deleteTask(Long id) {
Task task = taskRepository.findOne(id);
taskRepository.delete(task);
}
#Override
#Transactional
public void updateTask(Task task) {
Task retrieved = taskRepository.findOne(task.getId());
retrieved.setDescription(task.getDescription());
taskRepository.save(retrieved);
}
#Override
#Transactional
public Task findTask(Long id) {
return taskRepository.findOne(id);
}
#Override
#Transactional
public List<Task> getAllTasks() {
return (List<Task>) taskRepository.findAll();
}
}
MVC Config File (Replacement for web.xml):
package com.demo.faisal.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("WEB-INF/pages/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("/index");
}
}
Controller:
package com.demo.faisal.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.demo.faisal.model.Task;
import com.demo.faisal.service.TaskService;
#Controller
public class TaskController {
#Autowired
private TaskService taskService;
#RequestMapping(value = "/tasks", method = RequestMethod.GET)
public ModelAndView getTasks() {
ModelAndView mav = new ModelAndView();
mav.setViewName("tasks");
List<Task> tasks = taskService.getAllTasks();
mav.addObject("tasks", tasks);
return mav;
}
#RequestMapping("/taskform")
public ModelAndView showform() {
return new ModelAndView("taskform","task",new Task());
}
#RequestMapping(value="/save",method = RequestMethod.POST)
public ModelAndView save(#ModelAttribute("task") Task task) {
taskService.addTask(task);;
return new ModelAndView("redirect:/tasks");//will redirect to viewemp request mapping
}
#RequestMapping(value="/delete_task/{id}",method = RequestMethod.GET)
public ModelAndView delete(#PathVariable long id) {
taskService.deleteTask(id);;
return new ModelAndView("redirect:/tasks");//will redirect to viewemp request mapping
}
#RequestMapping(value="/edit_task/{id}")
public ModelAndView update(#PathVariable long id) {
Task task = taskService.findTask(id);
System.out.println("Returning taskeditform jsp with task: " + task.toString());
return new ModelAndView("taskeditform","task",task);
}
#RequestMapping(value="/editsave",method = RequestMethod.POST)
public ModelAndView editsave(#ModelAttribute("task") Task task) {
taskService.updateTask(task);
return new ModelAndView("redirect:/tasks");//will redirect to viewemp request mapping
}
}
VIEW:
taskform.jsp
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Add New Task</h1>
<form:form method="post" action="save" commandName="task">
<table>
<tr>
<td>Task Description :</td>
<td><form:input path="description" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Update" /></td>
</tr>
</table>
</form:form>
taskeditform.jsp
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Edit Task</h1>
<form:form method="post" action="/editsave" commandName="task">
<table>
<tr>
<td>Id</td>
<td><form:hidden path="id" /></td>
</tr>
<tr>
<td>Task Description :</td>
<td><form:input path="desciption" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Update" /></td>
</tr>
</table>
</form:form>
tasks.jsp
<%# page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Tasks List</h1>
<c:set var="contextPath" value="${pageContext.request.contextPath}" />
<table border="2" width="70%" cellpadding="2">
<tr>
<th>Id</th>
<th>Description</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<c:forEach var="task" items="${tasks}">
<tr>
<td>${task.id}</td>
<td>${task.description}</td>
<td>Edit</td>
<td>Delete</td>
</tr>
</c:forEach>
</table>
<br />
Add New Task
From my controller, all of my RequestMappings work fine, except /edit_task/{id}.
Everytime I call this url, I hit the breakpoint and can see it returning a new ModelAndView with the view pointing to taskeditform.jsp
However, I get a 404 error saying it cannot find the view. The error message is below:
type Status report
message /edit_task/WEB-INF/pages/taskeditform.jsp
description The requested resource is not available.
What I don't understand is the URL it's looking for : /edit_task/WEB-INF/pages/taskeditform.jsp. It looks like it is using the request mapping url and appending the view to it.
Can someone please point out what's going on here?
Thanks.

Retrive object from controller class to jsp file [duplicate]

This question already has answers here:
Using for loop inside of a JSP
(2 answers)
Closed 6 years ago.
I'm developing an ecommerce store using spring mvc. Suddenly I need to user some information in the jsp file (view) from controller class. In controller class I create a ModelAndView object and use addAttribute to use objext in my jsp file. Then I got stuck. I can not use the object in jsp file.
Hi this is my user class
//package com.ecommerce.demo
package com.ecommerce.demo;
import javax.persistence.*;
#Entity
#Table(name="USER")
public class User {
#Id
private String userName;
private String userPassword;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
}
and this is my controller class
package com.ecommerce.controller;
import java.io.IOException;
import java.util.List;
import javax.websocket.Session;
import org.hibernate.*;
import org.hibernate.cfg.*;
import org.json.JSONArray;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.ecommerce.demo.User;
#Controller
#RequestMapping(value="mainPageController")
public class MainPageController {
#RequestMapping(value="/mainPage.html")
public ModelAndView getLogInForm(#ModelAttribute("user") User userInput, BindingResult result) throws IOException {
List<User> userDatabase = null;
userDatabase = session.createQuery("from User").list();
session.beginTransaction();
session.close();
ModelAndView model = new ModelAndView("MainPage");
model.addObject("userNameAndPasswordList", userDatabase);
return model;
}
}
Now how can I print userName and userPassword in my mainPage.jsp file?
<%# page import="com.ecommerce.demo.User" %>
<%
Usinf java code(i.e for loop)
I need to print all userName and userPassword of user class here.
%>
You should write your mainPage.jsp like this and avoid the java code in it:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<table>
<c:forEach items="${userNameAndPasswordList}" var="user">
<tr>
<td>${user.userName}</td>
<td>${user.userPassword}</td>
</tr>
</c:forEach>
</table>
Use JSTL to print the result in your JSP file.
In this case you need to use foreach tag in JSTL
Here, your result is in object userNameAndPasswordList
Using $ syntax you can access the data of your object.
<c:forEach items="${userNameAndPasswordList}" var="userdetails">
<c:out value="${userdetails.userName}" />
<c:out value="${userdetails.userPassword}"/>
</c:forEach>
Use below code to fetch and print the data.
import JSTL tag in jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<table>
<c:if test="${userNameAndPasswordList!= null}">
<c:forEach items="${userNameAndPasswordList}" var="user">
<tr>
<td><c:out value="${user.userName}" /></td>
<td><c:out value="${user.userPassword}" /></td>
</tr>
</c:forEach>
</c:if>
</table>

Bring jsp form page after previous submit (java spring)

New to spring (and HTML/forms etc for that matter) and been stuck on this problem for long time.
So I want to have a front page where you enter a username. Then click submit, and takes you to a dashboard (ultimately, there will be a page with a list of connected users, a load of submit buttons to send predefined messages out - using qpid jms).
The front page is fine, but I click submit and I get an error (java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'dashboardModel' available as request attribute)
This only happens if I have a form:form in dashboard.jsp. I literally have no idea how to fix this and have tried everything I can find. My code is simple, and is just modified from a tutorial, so here it is:
login.jsp
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Login Page:</h2>
<form:form modelAttribute="loginModel" method="POST"
action="/HelloWeb/dashboard">
<table>
<tr>
<td><form:label path="username">Name</form:label></td>
<td><form:input path="username" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
Login.java
package com.tutorialspoint;
public class Login {
private String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
LoginController.java
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
#Controller
public class LoginController {
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login() {
return new ModelAndView("login", "loginModel", new Login());
}
#RequestMapping(value = "/loggedIn", method = RequestMethod.POST) //never actually used
public String loggedIn(#ModelAttribute("Login") Login login, ModelMap model) {
model.addAttribute("username", login.getUsername());
return "dashboard";
}
}
dashboard.jsp
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>DASHBOARD</title>
</head>
<body>
<table>
<tr>
<td>Dashboard</td>
<td>DASHBOARD</td>
</tr>
<tr>
<td>Username</td>
<td>${username}</td>
</tr>
<tr>
<td>variable</td>
<td>${variable}</td>
</tr>
</table>
<form:form modelAttribute="dashboardModel" method="POST"
action="/HelloWeb/dashboard">
<table>
<tr>
<td><form:label path="variable">Name</form:label></td>
<td><form:input path="variable" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
Dashboard.java
package com.tutorialspoint;
public class Dashboard {
private String variable;
public String getVariable() {
return variable;
}
public void setVariable(String variable) {
this.variable = variable;
}
}
DashboardController.java
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
#Controller
public class DashboardController {
#RequestMapping(value = "/dashboard", method = RequestMethod.GET)
public ModelAndView dashboard() {
return new ModelAndView("dashboard", "dashboardModel", new Dashboard());
}
#RequestMapping(value = "/dashboard", method = RequestMethod.POST)
public String addVariable(#ModelAttribute("SpringWeb") Dashboard dashboard,
ModelMap model) {
model.addAttribute("variable", dashboard.getVariable());
return "dashboard";
}
}
Thanks for your time.
I think the problem is here:
<form:form modelAttribute="loginModel" method="POST" action="/HelloWeb/dashboard">
^^^^^^^^^^
and here:
#RequestMapping(value = "/loggedIn", method = RequestMethod.POST) //never actually used
public String loggedIn(#ModelAttribute("Login") Login login, ModelMap model) {
^^^^^
The modelAttribute value on form:form element and the #ModelAttribute argument should be the same.
I mean:
#RequestMapping(value = "/loggedIn", method = RequestMethod.POST) //never actually used
public String loggedIn(#ModelAttribute("loginModel") Login login, ModelMap model) {
^^^^^^^^^^
Edit:
Also, the form part should be like this:
<form:form modelAttribute="dashboardModel" method="POST" action="/loggedIn.htm">
<table>
<tr>
<td>Name</td>
<td><form:input path="username" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>

Categories

Resources