Add student without avatar - spring

I created a project where you can add a student with an avatar and without an avatar. The problem is that when I add a student without an avatar, there is still a tag. How can I remove the tag. Now I will add an image and a couple of classes. I kind of wrote everything correctly, I don’t know where the error might be
#Controller
public class AvatarController {
#Value("${storage.location}")
private String storageLocation;
private StudentService studentService;
#Autowired
private ServletContext servletContext;
// Constructor based Dependency Injection
#Autowired
public AvatarController(StudentService studentService) {
this.studentService = studentService;
}
#GetMapping(value = "/avatar")
public void getAvatar(HttpServletResponse response, #Param("avatar") String avatar) {
if (avatar == null || avatar.isEmpty()) {
return;
}
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
try (FileInputStream input = new FileInputStream(studentService.loadAvatarByFileName(avatar))){
IOUtils.copy(input, response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
#RequestMapping(value = "/image", method = RequestMethod.GET)
public void image(#RequestParam String url, HttpServletResponse response) throws IOException {
InputStream in = new FileInputStream(url);
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
IOUtils.copy(in, response.getOutputStream());
}
}
Student Service Impl
#Service
#Transactional
public class StudentServiceImpl implements StudentService {
#Value("${storage.location}")
private String storageLocation;
private StudentRepository repository;
public StudentServiceImpl() {
}
#Autowired
public StudentServiceImpl(StudentRepository repository) {
super();
this.repository = repository;
}
#Override
public List<Student> getAllStudents() {
List<Student> list = new ArrayList<Student>();
repository.findAll().forEach(e -> list.add(e));
return list;
}
#Override
public Student getStudentById(Long id) {
Student student = repository.findById(id).get();
return student;
}
#Override
public boolean saveStudent(Student student) {
try {
repository.save(student);
return true;
} catch (Exception ex) {
return false;
}
}
#Override
public boolean deleteStudentById(Long id) {
try {
repository.deleteById(id);
return true;
} catch (Exception ex) {
return false;
}
}
#Override
public File loadAvatarByFileName(String filename) {
return new File(storageLocation + "/" + filename);
}
#Override
public File saveAvatarImage(MultipartFile avatarImage) throws IOException {
File newFile = File.createTempFile(
avatarImage.getName(),
"." + avatarImage.getOriginalFilename().split("\\.")[1],
new File(storageLocation));
avatarImage.transferTo(newFile);
return newFile;
}
#Override
public Student updateStudent(String name, String surname, MultipartFile avatar, Student targetStudent)
throws IOException {
if (name != null && !name.equals(targetStudent.getName())) {
targetStudent.setName(name);
}
if (surname != null && !surname.equals(targetStudent.getSurname())) {
targetStudent.setSurname(surname);
}
File newAvatar;
if (!avatar.getOriginalFilename().isEmpty()) {
if (targetStudent.getAvatar() != null) {
Files.deleteIfExists(Paths.get(storageLocation + File.separator + targetStudent.getAvatar()));
}
newAvatar = saveAvatarImage(avatar);
assert newAvatar != null;
targetStudent.setAvatar(newAvatar.getName());
}
boolean isSaved = saveStudent(targetStudent);
if (!isSaved) {
throw new IOException();
}
return targetStudent;
}
}
Student Controller
#Controller
public class StudentController {
#Autowired
private ServletContext servletContext;
// Constructor based Dependency Injection
private StudentService studentService;
public StudentController() {
}
#Autowired
public StudentController(StudentService studentService) {
this.studentService = studentService;
}
#RequestMapping(value = "/allStudents", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView displayAllUser() {
System.out.println("User Page Requested : All Students");
ModelAndView mv = new ModelAndView();
List<Student> studentList = studentService.getAllStudents();
mv.addObject("studentList", studentList);
mv.setViewName("allStudents");
return mv;
}
#Secured("ROLE_ADMIN")
#RequestMapping(value = "/allStudentsAdmin", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView displayAllUsers() {
System.out.println("User Page Requested : All Students");
ModelAndView mv = new ModelAndView();
List<Student> studentList = studentService.getAllStudents();
mv.addObject("studentList", studentList);
mv.setViewName("allStudentsUser");
return mv;
}
#Secured("ROLE_USER")
#RequestMapping(value = "/allStudentsUser", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView displayAllUsers() {
System.out.println("User Page Requested : All Students");
ModelAndView mv = new ModelAndView();
List<Student> studentList = studentService.getAllStudents();
mv.addObject("studentList", studentList);
mv.setViewName("allStudentsUser");
return mv;
}
#RequestMapping(value = "/addStudent", method = RequestMethod.GET)
public ModelAndView displayNewUserForm() {
ModelAndView mv = new ModelAndView("addStudent");
mv.addObject("headerMessage", "Add Student Details");
mv.addObject("student", new Student());
return mv;
}
#PostMapping(value = "/addStudent")
public String saveNewStudent(#RequestParam("name") #NonNull String name,
#RequestParam("surname") #NonNull String surname,
#RequestParam("avatar") MultipartFile file)
throws IOException {
Student student = new Student();
student.setSurname(surname);
student.setName(name);
if (file != null && !file.isEmpty()) {
student.setAvatar(studentService.saveAvatarImage(file).getName());
}
studentService.saveStudent(student);
return "redirect:/allStudents";
}
#GetMapping(value = "/editStudent/{id}")
public ModelAndView displayEditUserForm(#PathVariable Long id) {
ModelAndView mv = new ModelAndView("editStudent");
Student student = studentService.getStudentById(id);
mv.addObject("headerMessage", "Редактирование студента");
mv.addObject("student", student);
return mv;
}
#PostMapping(value = "/editStudent")
public String saveEditedUser(
#RequestParam("id") Long id,
#RequestParam("name") String name,
#RequestParam("surname") String surname,
#RequestParam("avatar") MultipartFile file) {
try {
studentService.updateStudent(name, surname, file, studentService.getStudentById(id));
} catch (FileSystemException ex) {
ex.printStackTrace();
} catch (IOException e) {
return "redirect:/error";
}
return "redirect:/allStudents";
}
#GetMapping(value = "/deleteStudent/{id}")
public ModelAndView deleteUserById(#PathVariable Long id) {
studentService.deleteStudentById(id);
ModelAndView mv = new ModelAndView("redirect:/allStudents");
return mv;
}
}
AllStudent JSP
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<link href="../css/style.css" rel="stylesheet" type="text/css">
<style><%#include file="/css/style.css"%></style>
<title>Все студенты</title>
</head>
<body>
<br>
<br>
<br>
<br>
<div class="it">
<h3>Список всех студентов</h3>
${message}
<br>
<br>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Surname</th>
<th scope="col">Avatar</th>
</tr>
</thead>
<tbody>
<c:forEach var="student" items="${studentList}">
<tr>
<th scope="row">1</th>
<td>${student.name}</td>
<td>${student.surname}</td>
<td><c:choose>
<c:when test="${student.avatar ne null}">
<td>
<img src="${pageContext.request.contextPath}/avatar?avatar=${student.avatar}"
style="max-height: 200px; max-width: 200px;" />
</td>
</c:when>
</c:choose></td>
<td>
<sec:authorize access="hasRole('ADMIN')">
<a href="${pageContext.request.contextPath}/editStudent/${student.id}">
<button type="button" class="btn btn-primary">Edit</button>
</a>
</sec:authorize>
</td>
<td>
<sec:authorize access="hasRole('ADMIN')">
<a href="${pageContext.request.contextPath}/deleteStudent/${student.id}">
<button type="button" class="btn btn-primary">Delete</button>
</a>
</sec:authorize>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</body>
</html>

#user404 answer ok but need some change
<c:choose>
<c:when test="${student.avatar ne null}">
<td>
<img src="${pageContext.request.contextPath}/avatar?avatar=${student.avatar}"
style="max-height: 200px; max-width: 200px;" />
</td>
</c:when>
<c:otherwise>
<td></td>
</c:otherwise>
</c:choose>
despription : When avater is null or empty then add a empty cell on
our html table other wise add image with full src path

You have to check the condition if your student.avatar holds avatar or null and based on that, show your image or not. Coz, that image tag for empty avatar your see because of img tag. You can use if-else condition in jstl or like this.
try this:
<c:choose>
<c:when test="${student.avatar ne null}">
<td>
<img src="${pageContext.request.contextPath}/avatar?avatar=${student.avatar}"
style="max-height: 200px; max-width: 200px;" />
</td>
</c:when>
<c:otherwise>
<td></td>
</c:otherwise>
</c:choose>

Related

How to pass loop paramters from JSP to Spring Controller

I am having a loop on my JSP page and want to pass these values in my Spring Controller. On every click on Retry button in JSP, I need all values in my controller for further processing. The code which I tried so far is:
Any help much appreciated.
JSP File
<table class="gridtable">
<tr>
<th>Queue Name</th>
<th>Retry Attempt</th>
<th>Reason for failure</th>
<th>Action</th>
</tr>
<% int i=0; %>
<c:forEach var="queueRowDetail" items="${queueRowDetailList}">
<tr>
<td>${queueRowDetail.queueName}</td>
<td>${queueRowDetail.attempt}</td>
<td>${queueRowDetail.errorDetails}</td>
<td>
<form:form method="post" action="/retry" id="frmFailure_<%=i%>" modelAttribute="queueRowDetail"/>
<form:hidden path="queueName<%=i %>" value="${queueRowDetail.queueName}"/>
<form:hidden path="attempt<%=i %>" value="${queueRowDetail.attempt}"/>
<form:hidden path="errorDetails<%=i %>" value="${queueRowDetail.errorDetails} "/>
<input type="button" value="Retry" onClick="sendobj(<%=i%>)" />
</form>
</td>
</tr>
<% i++; %>
</c:forEach>
function sendObj()
<script>
function sendobj(i)
{
var x = document.getElementById("frmFailure_"+i);
alert(obj);
alert("frmFailure_"+i);
x.submit();// Form submission
}
</script>
QueueRowDetail Class
package com.gartner.gqueuefailureapi.model;
public class QueueRowDetail {
private String queueName;
private String errorDetails;
private int attempt;
private Object payLoad;
public String getQueueName() {
return queueName;
}
public void setQueueName(String queueName) {
this.queueName = queueName;
}
public String getErrorDetails() {
return errorDetails;
}
public void setErrorDetails(String errorDetails) {
this.errorDetails = errorDetails;
}
public int getAttempt() {
return attempt;
}
public void setAttempt(int attempt) {
this.attempt = attempt;
}
public Object getPayLoad() {
return payLoad;
}
public void setPayLoad(Object payLoad) {
this.payLoad = payLoad;
}
}
InderController.Java
#RequestMapping(value = "/retry", method = RequestMethod.POST)
public String retryMessage( #ModelAttribute("queueRowDetail")QueueRowDetail queueRowDetail, ModelMap model) {
model.addAttribute("queuename", queueRowDetail.getQueueName());
return "success";
}

"Neither BindingResult nor plain target object for bean name 'command' available as request attribute"

I am getting an exception while creating a form using spring forms tag library
"Neither BindingResult nor plain target object for bean name 'command' available as request attribute"
The jsp page is index.jsp
<%# include file="views/static_include.jsp" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login to AVA Corp</title>
</head>
<body>
<form:form method="POST" commandName="user" action="login.jsp">
<table>
<tbody><tr>
<td><form:label path="firstName">Name:</form:label></td>
<td><form:input path="firstName"></form:input></td>
</tr>
<tr>
<td><form:label path="age">Age:</form:label></td>
<td><form:input path="age"></form:input></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit">
</td>
<td></td>
<td></td>
</tr>
</tbody></table>
</form:form>
</body>
</html>
The bean class is:
import java.io.Serializable;
public class Person implements Serializable {
private static final long serialVersionUID = 1949001721422434327L;
private String firstName;
private Integer age;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
The controller class is
#Controller
public class LoginController {
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView initForm(Model model) {
return new ModelAndView("index", "user", new Employee());
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(#ModelAttribute("user") Employee employee, BindingResult result, SessionStatus status){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("user", employee);
return "UserFormSuccess";
}
}
I found that the issue was with the controller method with method type = "get". The value of the request method needs to be the URL mapping of the page on which the form resides e.g. index.jsp in our case so the controller class will be
#Controller
public class LoginController {
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView initForm(Model model) {
return new ModelAndView("index", "user", new Employee());
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(#ModelAttribute("user") Employee employee, BindingResult result, SessionStatus status){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("user", employee);
return "UserFormSuccess";
}
}

CRUD using spring and mybatis

HI hava a problem while creating a CRUD operation in browser
`HTTP Status 500 -
--------------------------------------------------------------------------------
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: org.apache.jasper.JasperException: org.springframework.beans.NotReadablePropertyException: Invalid property 'standard' of bean class [com.raistudies.domain.User]: Bean property 'standard' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:548)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:456)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:389)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:333)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
here I have all part of the spring mvc + mybatis operations file
//controller
package com.raistudies.controllers;
import java.util.List;
import java.util.UUID;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.raistudies.domain.User;
import com.raistudies.persistence.UserService;
import com.raistudies.validator.RegistrationValidator;
#Controller
#RequestMapping(value="/registration")
public class RegistrationController {
private RegistrationValidator validator = null;
private UserService userService = null;
#Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
public RegistrationValidator getValidator() {
return validator;
}
#Autowired
public void setValidator(RegistrationValidator validator) {
this.validator = validator;
}
#RequestMapping(method=RequestMethod.GET)
public String showForm(ModelMap model){
List<User> users = userService.getAllUser();
model.addAttribute("users", users);
User user = new User();
user.setId(UUID.randomUUID().toString());
model.addAttribute("user", user);
return "registration";
}
#RequestMapping(value="/add", method=RequestMethod.POST)
public ModelAndView add(#ModelAttribute(value="user") User user,BindingResult result){
validator.validate(user, result);
ModelAndView mv = new ModelAndView("registration");
if(!result.hasErrors()){
userService.saveUser(user);
user = new User();
user.setId(UUID.randomUUID().toString());
mv.addObject("user", user);
}
mv.addObject("users", userService.getAllUser());
return mv;
}
#RequestMapping(value="/update", method=RequestMethod.POST)
public ModelAndView update(#ModelAttribute(value="user") User user,BindingResult result){
validator.validate(user, result);
ModelAndView mv = new ModelAndView("registration");
if(!result.hasErrors()){
userService.updateUser(user);
user = new User();
user.setId(UUID.randomUUID().toString());
mv.addObject("user", user);
}
mv.addObject("users", userService.getAllUser());
return mv;
}
#RequestMapping(value="/delete", method=RequestMethod.POST)
public ModelAndView delete(#ModelAttribute(value="user") User user,BindingResult result){
validator.validate(user, result);
ModelAndView mv = new ModelAndView("registration");
if(!result.hasErrors()){
userService.deleteUser(user.getId());
user = new User();
user.setId(UUID.randomUUID().toString());
mv.addObject("user", user);
}
mv.addObject("users", userService.getAllUser());
return mv;
}
}
persistance is
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.raistudies.persistence.UserService">
<resultMap id="result" type="user">
<result property="id" column="id"/>
<result property="name" column="name"/>
<result property="studentClass" column="class"/>
<result property="roll" column="roll"/>
<!-- <result property="sex" column="sex"/>-->
</resultMap>
<select id="getAllUser" resultMap="result">
SELECT id,name,class,roll
FROM user;
</select>
<insert id="saveUser" parameterType="user">
INSERT INTO user (id,name,standard,age,sex)
VALUE (#{id},#{name},#{standard},#{age})
</insert>
<update id="updateUser" parameterType="user">
UPDATE user
SET
name = #{name},
standard = #{standard},
age = #{age},
sex = #{sex}
where id = #{id}
</update>
<delete id="deleteUser" parameterType="int">
DELETE FROM user
WHERE id = #{id}
</delete>
</mapper>
I have to do create delete update add operation but it is going to be error just like above while running my project......please help me
after changing the jsp code as per the variable that the java bean class(class containing geter or setter method) has.Then it will solve the problem.
*especially what I mean is you have to change the path in jsp <tr><td>Class : </td><td><form:input path="standard" /></td></tr>*as per the bean variable
previous jsp file (at error time)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%# page session="true" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Hello World with Spring 3 MVC</title>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
<script type="text/javascript" src='<c:url value="/resources/common.js"/>'></script>
<script type="text/javascript" src='<c:url value="/resources/registration.js"/>'></script>
<script type="text/javascript">
var projectUrl = '<c:url value="/"/>';
if(projectUrl.indexOf(";", 0) != -1){
projectUrl = projectUrl.substring(0, projectUrl.indexOf(";", 0));
}
</script>
</head>
<body>
<fieldset>
<legend>Registration Form</legend>
<center>
<form:form commandName="user" action="/SpringMVCMyBatisCRUDExample/app/registration/add" name="userForm">
<form:hidden path="id"/>
<table>
<tr><td colspan="2" align="left"><form:errors path="*" cssStyle="color : red;"/></td></tr>
<tr><td>Name : </td><td><form:input path="name" /></td></tr>
<tr><td>Class : </td><td><form:input path="standard" /></td></tr>
<tr><td>RollNo: </td><td><form:input path="roll" /></td></tr>
<tr><td colspan="2"><input type="submit" value="Save Changes"/>
<input type="reset" name="newUser" value="New User" onclick="setAddForm();" disabled="disabled"/>
<input type="submit" name="deleteUser" value="Delete User" onclick="setDeleteForm();" disabled="disabled"/></td></tr>
</table>
</form:form>
</center>
</fieldset>
<c:if test="${!empty users}">
<br />
<center>
<table width="90%">
<tr style="background-color: gray;">
<th>Name</th>
<th>Class</th>
<th>RollNo</th>
</tr>
<c:forEach items="${users}" var="user">
<tr style="background-color: silver;" id="${user.id}" onclick="setUpdateForm('${user.id}');">
<td><c:out value="${user.name}"/></td>
<td><c:out value="${user.studentClass}"/></td>
<td><c:out value="${user.roll}"/></td>
</tr>
</c:forEach>
</table>
</center>
<br />
</c:if>
</body>
my java bean class
package com.raistudies.domain;
import java.io.Serializable;
public class User implements Serializable{
private static final long serialVersionUID = 3647233284813657927L;
private String id;
private String name = null;
private String studentClass = null;
private String roll;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStudentClass() {
return studentClass;
}
public void setStudentClass(String studentClass) {
this.studentClass = studentClass;
}
public String getRoll() {
return roll;
}
public void setRoll(String roll) {
this.roll = roll;
}
#Override
public String toString() {
return "User [name=" + name + ", class="+ studentClass+ ", roll=" + roll + "]";
}
}
previously I had standard variable in java bean class(model class) but I have to change it to studentClass so not to be error we must change the jsp path that is
<tr><td>Class : </td><td><form:input path="standard" /></td></tr>.......
to
<tr><td>Class : </td><td><form:input path="studentClass" /></td></tr>

spring MVC database display

I have created a mySQL table: student.studentInfo with:-
Int id autofill PK,
String name,
int age,
String email.
User fills up a StudentRegForm and The values of name, age and email are shown on a RegisteredStudent jsp.
I want to display contents [data elements] of the mySQL table on a jsp page.
My StudentDaoImpl:
public class StudentDaoImpl implements StudentDao {
DataSource datasource;
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource datasource) {
this.datasource = datasource;
this.jdbcTemplate = new JdbcTemplate(datasource);
}
#Override
public List<Student> getStudentList() {
List<Student> studentList = new ArrayList<Student>();
String sql = "select * from student.studentInfo";
JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource);
studentList = jdbcTemplate.query(sql, new StudentMapper());
return studentList;
}
}
The above StudentMapper method is:
public class StudentMapper implements RowMapper<Student>{
#Override
public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
Student student = new Student();
student.setId( rs.getInt("id"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));
student.setEmail(rs.getString("email"));
return student;
}
}
View Resolver is set on MvcConfiguration and DataSource props are declared as #Bean:
#Configuration
#ComponentScan(basePackages = "com.anand")
#EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations(
"/resources/");
}
#Bean
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/student");
dataSource.setUsername("root");
dataSource.setPassword("root");
return dataSource;
}
}
Students fill up this Studentform.jsp:
<form action="StudentAddSuccess.htm" method=post>
${formHeading}
<p>
id <input type="text" name="id" />
</p>
<p>
Name <input type="text" name="name"/>
</p>
<p>
Age <input type="text" name="age" />
</p>
<p>
Email <input type="text" name="email" />
</p>
<p>
<input type="submit" name="submit" value="save">
</p>
</form>
Controller class is:
#Controller
public class StudentController {
#Autowired
StudentDao stdDao;
#RequestMapping(value = "/studentForm.htm", method = RequestMethod.GET)
public ModelAndView sendStudentForm() {
ModelAndView mav = new ModelAndView("studentForm");
mav.addObject("formHeading", "Student Registration Form");
mav.setViewName("studentForm");
System.out.println("student Form");
return mav;
}
//**********************************************************
#RequestMapping(value = "RegdSuccess", method = RequestMethod.POST)
public ModelAndView addStudent(#ModelAttribute("student1") Student student1) {
ModelAndView mav = new ModelAndView();
//mav.addObject("studentId", "id is:-" + student1.getId());
mav.addObject("studentName", " name is:- " + student1.getName());
mav.addObject("studentAge", " age is:-" + student1.getAge());
mav.addObject("studentEmail", "student email is:-" + student1.getEmail());
// mav.addObject("student", "student list is"+ student1);
System.out.println(" hello from RegdSuccess");
mav.setViewName("RegdSuccess");
return mav;
}
//********************************************************************
#RequestMapping( value = "RegdStudent", method = RequestMethod.GET)
public ModelAndView showStudent(#ModelAttribute("std")Student std) throws IOException{
ModelAndView mav = new ModelAndView();
List<Student> listStudent= stdDao.getStudentList();
mav.addObject("msg", "hello from Regd jsp");
//mav.addObject("listStudent", listStudent);
mav.addObject("msg",""+listStudent);
System.out.println(" hello from Regd Students controller"+std.getName());
mav.setViewName("RegdStudent");
return mav;
}
StudentDao is:
public interface StudentDao {
// create
public void createStudent(Student student);
// read
public Student getStudent(Integer id);
// Update
public void updateStudent(Student student);
// delete
public void deleteStudent(Integer id);
// List
public List<Student> getStudentList();
// save
public void save(Student student);
}
And StudentImplDao is:
public class StudentDaoImpl implements StudentDao {
StudentDaoImpl StudentDao;
DataSource datasource;
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource datasource) {
this.datasource = datasource;
this.jdbcTemplate = new JdbcTemplate(datasource);
}
public void doExecute() {
String sql = "SELECT * FROM STUDENT.StudentInfo";
SqlRowSet srs = jdbcTemplate.queryForRowSet(sql);
int rowCount = 0;
while (srs.next()) {
System.out.println(srs.getString("id") + "-"
+ srs.getString("name") + "-" + srs.getString("age") + "-"
+ srs.getString("email"));
}
rowCount++;
System.out.println("Number of records" + rowCount);
}
// -------------List----------------------------------------
#Override
public List<Student> getStudentList() {
List<Student> studentList = new ArrayList<Student>();
String sql = "select * from student.studentInfo";
JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource);
studentList = jdbcTemplate.query(sql, new StudentMapper());
return studentList;
}
// other remaining methods of StudentDao go here for the implementations
//………………………………
}
I can input name, age, email on the Studentform.jsp and those inputs are displayed on RegdSuccess.jsp, but my RegdStudent.jsp page is not displaying list records from my database as I want it to. RegdStudent.jsp is:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<head>
<title>Regd. Students</title>
</head>
<body>
hello from Regd Students jsp
<form:form>
<table>
<c:forEach items="${msg}" var="employee">
<tr>
<td><c:out value="${employee.id}" /></td>
<td><c:out value="${employee.name}" /></td>
<td><c:out value="${employee.age}" /></td>
<td><c:out value="${employee.email}" /></td>
</tr>
</c:forEach>
</table>
</form:form>
</body>
</html>
I would like to have this JSP age show all the records from the mysql database.
By doing
mav.addObject("msg",""+listStudent);
you're coercing the listStudent List to a string, making it impossible to iterate over it later in your JSP. If you change the line to:
mav.addObject("msg", listStudent);
the ${msg} object will be an iterable list.
It seems that you have no idea what works and what doesn't in your application since you dumped code for all layers. You should familiarise yourself with your IDE's debugger and learn to follow request's path to see what's going on. Narrowing down the problem drastically reduces time needed to find and fix bugs.

Spring Framework <form:errors/> tag not showing errors

I know there are many similar questions here, but none of them solved my problem.
I'm using Spring 4.0.3 and Hibernate Validator 5.1.0.
The problem occurs when I try to omit the path attribute of the <form:errors/> tag, so:
<form:errors path="contato.nome" /> works
<form:errors path="*" /> works
<form:errors /> doesn't work
I don't know why it happens. Spring javadocs (org.springframework.web.servlet.tags.form.ErrorsTag) says it should work like that:
Field only - set path to the field name (or path)
Object errors only - omit path
All errors - set path to *
Can you help me, please?
The interested code is in the 'edicao.jsp' and in the method 'confirmarEdicao' of the ContatoController.java. Sorry if my english is bad.
ContatoController.java
#Controller
#RequestMapping("/contatos")
public class ContatoController {
#Autowired
private ContatoService contatoService;
#Autowired
private MessageSource messageSource;
#RequestMapping(value = "/confirmarEdicao", method = RequestMethod.POST)
public String confirmarEdicao(#Valid Contato contato, BindingResult bindingResult) {
if(bindingResult.hasErrors()) {
return "contatos/edicao";
}
contatoService.save(contato);
return "redirect:/contatos";
}
#RequestMapping(method = RequestMethod.GET)
public ModelAndView form(HttpServletRequest request) {
String message = messageSource.getMessage("teste", null, new Locale("pt", "BR"));
System.out.println(message);
return new ModelAndView("contatos/listagem")
.addObject("contatos", contatoService.list());
}
#RequestMapping("/remover/{id}")
public String remover(Contato contato) {
contatoService.delete(contato);
return "redirect:/contatos";
}
#RequestMapping("/editar/{id}")
public ModelAndView formEdicao(Contato contato) {
contato = contatoService.find(contato.getId());
return new ModelAndView("contatos/edicao")
.addObject(contato);
}
#RequestMapping(value = "/cadastrar")
public String formCadastro() {
return "contatos/cadastro";
}
#RequestMapping(value = "/confirmarCadastro", method = RequestMethod.POST)
public String confirmarCadastro(#Valid Contato contato, BindingResult bindingResult,
RedirectAttributes redirectAttributes) {
if (bindingResult.hasFieldErrors()) {
return "contatos/cadastro";
}
contatoService.save(contato);
redirectAttributes.addFlashAttribute("mensagem", "Contato cadastrado com sucesso.");
return "redirect:/contatos";
}
#ResponseBody
#RequestMapping(value = "/pesquisar/{nome}", method = RequestMethod.GET,
produces="application/json")
public List<Contato> pesquisar(#PathVariable String nome) {
return contatoService.findByName(nome);
}
}
edicao.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" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Editar contato</title>
</head>
<body>
<c:set var="context">${pageContext.request.contextPath}</c:set>
<script type="text/javascript">var context = "${context}";</script>
<script src="${context}/resources/js/jquery-2.1.0.min.js"></script>
<script src="${context}/resources/js/contatos/edicao.js"></script>
<form:form commandName="contato" action="${context}/contatos/confirmarEdicao" method="post">
<form:errors/>
<table>
<form:hidden path="id"/>
<tr>
<td>Nome:</td>
<td><form:input path="nome" /></td>
</tr>
<tr>
<td>Telefone:</td>
<td><form:input path="telefone"/></td>
</tr>
<tr>
<td><input type="button" value="Voltar" id="btn_voltar"/><input type="submit" value="Salvar"/></td>
</tr>
</table>
</form:form>
</body>
</html>
Contato.java
package com.handson.model;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
public class Contato {
private Long id;
#Size(min = 3, message = "Nome deve ter no mínimo 3 caracteres")
#NotEmpty(message = "O nome deve ser preenchido")
private String nome;
private String telefone;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public Contato withId(Long id) {
setId(id);
return this;
}
public Contato withTelefone(String telefone) {
setTelefone(telefone);
return this;
}
public Contato withNome(String nome) {
setNome(nome);
return this;
}
#Override
public String toString() {
return "Contato [id=" + id + ", nome=" + nome + ", telefone="
+ telefone + "]";
}
}
There are some keywords which should be defined:
path - EL-like path to an object or to a field of an object (e.g. foo, foo.bar or foo.bar.baz)
nested path - current path context stored as nestedPath request attribute (new paths are relative to this path)
object error - error connected with object itself (e.g. path is equal to foo)
field error - error connected with object field (e.g. path is foo.bar)
The tag <form:form commandName="foo"> defines nested path as nestedPath=foo. When you write <form:errors path="bar"> it tries to find errors defined for path foo.bar.
Lets say that you have errors connected with foo (object error), foo.bar and foo.bar.baz (nested field error). What this means:
if you enter <form:errors>, only errors bound to foo path are displayed => 1 message
if you enter <form:errors path="bar">, only errors bound to foo.bar path are displayed => 1 message
if you enter <form:errors path="*">, errors bound to foo and its child paths are displayed => 3 messages
if you enter <form:errors path="bar.*">, only child errors for foo.bar are diplayed => 1 message
if you enter <form:errors path="bar*">, errors bound to foo.bar and its child paths are diplayed => 2 messages
Checking on Errors class JavaDoc might give you additional insight.

Resources