I have created some form with spring mvc Framework but I am facing Problem when clicking the submit button, the studentName is not being bound with the other data in the AdmissionSuccess.jsp file. I do not know what I am doing wrong in the StudentNameEditor class. The setAsText method is being called but the value of studentName is not being rendered in the AdmissionSuccess.jsp.
How can I get it to work?
StudentAdmissionController
package com.stack;
import java.sql.Date;
import java.text.SimpleDateFormat;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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;
#Controller
public class StudentAdmissionController {
#InitBinder
public void iniBinder(WebDataBinder binder){
//binder.setDisallowedFields(new String[] {"studentMobile"});
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
binder.registerCustomEditor(Date.class, "studentDOB", new CustomDateEditor(dateFormat, false));
//add to handle a specific data.
binder.registerCustomEditor(String.class,"studentName", new StudentNameEditor());
}
#RequestMapping(value = "/admission.html", method = RequestMethod.GET)
public ModelAndView getAdmissionForm() {
ModelAndView model = new ModelAndView("AdmissionForm");
return model;
}
// Aded
// This method is being called by every request.
#ModelAttribute
public void addingCommonObjects(Model model1) {
model1.addAttribute("headerMessage", "University of Lübeck, Germany ");
}
#RequestMapping(value = "/submitAdmissionForm.html", method = RequestMethod.POST)
public ModelAndView submitAdmissionForm(#ModelAttribute("student1") Student student1, BindingResult result) {
if (result.hasErrors()) {
ModelAndView model = new ModelAndView("AdmissionForm");
return model;
}
ModelAndView model = new ModelAndView("AdmissionSuccess");
return model;
}
}
StudentNameEditor class
package com.stack;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.beans.PropertyChangeListener;
import java.beans.PropertyEditor;
public class StudentNameEditor implements PropertyEditor {
/*
* (non-Javadoc) when you will submit the admission form, Spring mvc will run
* serAsText function this class before performing data binding task for
* studentName property of student.
*/
#Override
public void setAsText(String studentName) throws IllegalArgumentException {
if(studentName.contains("Mr.") || studentName.contains("Ms.")){
setValue(studentName);
}else{
studentName = "Ms." + studentName;
setValue(studentName);
}
}
#Override
public void addPropertyChangeListener(PropertyChangeListener listener) {
// TODO Auto-generated method stub
}
#Override
public String getAsText() {
// TODO Auto-generated method stub
return null;
}
#Override
public Component getCustomEditor() {
// TODO Auto-generated method stub
return null;
}
#Override
public String getJavaInitializationString() {
// TODO Auto-generated method stub
return null;
}
#Override
public String[] getTags() {
// TODO Auto-generated method stub
return null;
}
#Override
public Object getValue() {
// TODO Auto-generated method stub
return null;
}
#Override
public boolean isPaintable() {
// TODO Auto-generated method stub
return false;
}
#Override
public void paintValue(Graphics gfx, Rectangle box) {
// TODO Auto-generated method stub
}
#Override
public void removePropertyChangeListener(PropertyChangeListener listener) {
// TODO Auto-generated method stub
}
#Override
public void setValue(Object value) {
// TODO Auto-generated method stub
}
#Override
public boolean supportsCustomEditor() {
// TODO Auto-generated method stub
return false;
}
}
AdmissionForm.jsp
<!-- Added -->
<%#taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<body>
<h1>${headerMessage}</h1>
<h1>Student admission form for Engineeering courses</h1>
<!-- Added -->
<form:errors path="student1.*" />
<form action="/FirstSpringMVCProject/submitAdmissionForm.html"
method="post">
<table>
<tr>
<td>Student's Name:</td>
<td><input type="text" name="studentName" /></td>
</tr>
<tr>
<td>Student's Hobby:</td>
<td><input type="text" name="studentHobby" /></td>
</tr>
<tr>
<td>Student's Mobile:</td>
<td><input type="text" name="studentMobile" /></td>
</tr>
<tr>
<td>Student's DOB:</td>
<td><input type="text" name="studentDOB" /></td>
</tr>
<tr>
<td>Student's Skill set:</td>
<td><select name="studentSkills" multiple>
<option value="Java Core">Java Core</option>
<option value="Spring Core">Spring Core</option>
<option value="Spring MVC">Spring MVC</option>
</select></td>
</tr>
</table>
<table>
<tr>
<td>Student's Address:</td>
</tr>
<tr>
<td>county: <input type="text" name="studentAddress.country" />
</td>
<td>city: <input type="text" name="studentAddress.city" />
</td>
<td>street: <input type="text" name="studentAddress.street" />
</td>
<td>pincode: <input type="text" name="studentAddress.pincode" />
</td>
</tr>
</table>
<input type="submit" value="Submit this form by clicking here" />
</form>
</body>
</html>
AdmissionSuccess.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<h1>${headerMessage}</h1>
<h3>STUDENT ADMISSION FROM ENGINEERING COURSES</h3>
<h2>Detials submitted by you::</h2>
<table>
<tr>
<td>Student Name:</td>
<td>${student1.studentName}</td>
</tr>
<tr>
<td>Student Hobby:</td>
<td>${student1.studentHobby}</td>
</tr>
<tr>
<td>Student Mobile:</td>
<td>${student1.studentMobile}</td>
</tr>
<tr>
<td>Student DOB:</td>
<td>${student1.studentDOB}</td>
</tr>
<tr>
<td>Student skills:</td>
<td>${student1.studentSkills}</td>
</tr>
<tr>
<td>Student Adress:</td>
<td>${student1.studentAddress.country}
${student1.studentAddress.city}
${student1.studentAddress.street}
${student1.studentAddress.pincode}</td>
</tr>
</table>
<body>
</body>
</html>
so I had StudentNameEditor implements PropertyEditor and it must be StudentNameEditor extends PropertyEditorSupport. With the code below it works fine.
package com.stack;
import java.beans.PropertyEditorSupport;
public class StudentNameEditor extends PropertyEditorSupport {
/*
* (non-Javadoc) when you will submit the admission form, Spring mvc will run
* serAsText function this class before performing data binding task for
* studentName property of student.
*/
#Override
public void setAsText(String studentName) throws IllegalArgumentException {
if(studentName.contains("Mr.") || studentName.contains("Ms.")){
setValue(studentName);
}else{
studentName = "Ms." + studentName;
setValue(studentName);
}
}
}
Related
I am working on a hibernate project using apache.tomcat in netbeans in which I am creating an application with a user login (employee ID and password) that allows baseball field employees (from mysql database) to request passes to use the field. Users should be able to 1) choose an event for reservation (date & time) from a drop down menu, 2) input their group size, group name, and employee department(drop-down) and 3) manage the reservations on file specific to their employee ID.
I can access the login screen, but nothing happens when I enter employee credentials. I am not sent to the memberscreen.jsp upon entering a correct login, and I do not get the errors I set up for invalid logins. I have been at this for hours and I can not seem to find where I went wrong.
Note: The project requires that I use hibernate
I have tried googling ways to fix this but I have come up short, I think my problem may be too specific. I am getting no errors and the build is successful, but not functional.
logonservlet.java
package servlets;
import business.Employee;
import business.EmployeeDB;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LogonServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String msg = "", empid = "";
long pattempt;
String URL = "/Logon.jsp";
Employee e;
try {
empid = request.getParameter("empid").trim();
e = EmployeeDB.getEmployee(empid);
if (e == null) {
msg = "No member record found<br>";
} else {
pattempt = Long.parseLong(request.getParameter("password"));
e.setPassattempt((int) pattempt);
if (!e.isAuthenticated()) {
msg = "Member found but not authenticated<br>";
} else {
msg = "member authenticated<br>";
URL = "/MemberScreen.jsp";
}
request.getSession().setAttribute("e", e);
}
} catch (Exception x) {
msg = "Servlet exception: " + x.getMessage();
}
request.setAttribute("msg", msg);
RequestDispatcher disp =
getServletContext().getRequestDispatcher(URL);
disp.forward(request,response);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods.
Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Logon.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Field Pass</title>
</head>
<body>
<h1>Welcome</h1>
<p>Please Enter your id and password:</p>
<form action="Logon" method="post">
<table>
<tr>
<td>User ID:</td>
<td><input type="text" name="userid" id="userid"
value="${empty user.userID ? cookie.memid.value : user.userID }" />
</td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" id="password">
</td>
</tr>
</table>
<br>
<input type="submit" value="Log in">
</form>
<br>
</body>
</html>
employee.java
package business;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.Transient;
import org.hibernate.annotations.NamedQuery;
#Entity
#Table(name="Employee")
#NamedQuery(name="dbget_Employee", query="from EMPLOYEE where EMP_ID = :EMP_ID")
public class Employee {
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
#Id
#Column(name="EMP_ID")
private int emp_id;
#Column(name="LAST_NAME")
private String last_name;
#Column(name="FIRST_NAME")
private String first_name;
#Column(name="MIDDLE_INITIAL")
private String middle_initial;
#Column(name="HIRE_DATE")
#Temporal(javax.persistence.TemporalType.DATE)
private Date hire_date;
#Column(name="DEPT_ID")
private int dept_id;
#Column(name="PASSWORD")
private int password;
#Column(name="ADMIN")
private String admin;
#Transient
private int passattempt;
#Transient
private String msg;
public Employee() {
emp_id = 0;
last_name= "";
first_name = "";
middle_initial = "";
hire_date = null;
dept_id = 0;
password = 0;
admin = "";
}
public int getEmp_id() {
return emp_id;
}
public void setEmp_id(int emp_id) {
this.emp_id = emp_id;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getMiddle_initial() {
return middle_initial;
}
public void setMiddle_initial(String middle_initial) {
this.middle_initial = middle_initial;
}
public Date getHire_date() {
return hire_date;
}
public void setHire_date(Date hire_date) {
this.hire_date = hire_date;
}
public int getDept_id() {
return dept_id;
}
public void setDept_id(int dept_id) {
this.dept_id = dept_id;
}
public int getPassword() {
return password;
}
public void setPassword(int password) {
this.password = password;
}
public String getAdmin() {
return admin;
}
public void setAdmin(String admin) {
this.admin = admin;
}
public int getPassattempt() {
return passattempt;
}
public void setPassattempt(int passattempt) {
this.passattempt = passattempt;
}
public boolean isAuthenticated() {
if (this.password > 0) {
if (this.password == this.getPassattempt()) {
return true;
} else {
setMsg("Member not authenticated");
}
}
return false;
}
}
employeeDB.java
package business;
import javax.persistence.NoResultException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
/**
*
* #author noah
*/
public class EmployeeDB {
public static Employee getEmployee(int emp_id) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = null;
Employee e = null;
try {
String qS ="from Employee e where e.emp_id = :emp_id";
session = sessionFactory.openSession();
Query q = session.createQuery(qS);
q.setParameter("emp_id", emp_id);
e = (Employee)q.uniqueResult();
} catch (NoResultException ex) {
return null;
} finally {
session.close();
}
return e;
}
public static Employee getEmployee(String empid) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of
generated methods, choose Tools | Templates.
}
}
memberScreen.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Member Welcome</title>
<style>
table.member-details{
border-collapse: collapse;
}
table.member-details td, table.member-details th{
padding: 6px;
border: 1px solid #999;
}
</style>
</head>
<c:if test="${!e.authenticated}">
<script type="text/javascript">
window.location = "/ClubDB";
</script>
</c:if>
<c:if test="${e.authenticated}">
<body>
<h1>Club member Data</h1>
<form id="memupdate" action="MemberUpdate" method="post">
<table class="member-details">
<tr>uu
<td>Member ID:</td>
<td><input type="text" id="memid" name="memid"
value="${e.empid}" readonly="true"></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" id="lastname" name="lastname"
value="${e.lastname}" ></td>
</tr>
<tr>
<td>First Name:</td>
<td><input type="text" id="firstname" name="firstname"
value="${e.firstname}" ></td>
</tr>
<tr>
<td>Middle Nm:</td>
<td><input type="text" id="middlename" name="middlename"
value="${e.middlename}" ></td>
</tr>
<tr>
<td>Status:</td>
<td><input type="text" id="status" name="status"
value="${m.status}" readonly="true" ></td>
<tr>
<tr>
<td>Member Date:</td>
<td><input type="text" id="memdt" name="memdt"
value="${m.memdtS}" readonly="true" ></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" id="psswd" name="psswd"
value="${m.password}" size="22"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Update Member data"></td>
</tr>
</table>
</form>
<br>
${msg}
<hr>
<br>View Transaction History From:<br>
<form action="ShowPurchases" method="post" >
<table>
<tr>
<td>Month:</td><td><input type="text" name="month"
id="month" value=""></td>
<td>Day:</td><td><input type="text" name="day"
id="day" value=""></td>
<td>Year:</td><td><input type="text" name="year"
id="year" value=""></td>
</tr>
</table><br>
<input type="submit" value="View Transactions">
</form> <br>
<br><br>
Back to the Login Screen
</body>
</c:if>
</html>
hibernate xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-
iiapp_3_1.xsd">
<servlet>
<servlet-name>LogonServlet</servlet-name>
<servlet-class>servlets.LogonServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogonServlet</servlet-name>
<url-pattern>/Logon</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>Logon.jsp</welcome-file>
</welcome-file-list>
im doing a web and upon testing it i encountered this , Request Sent by the Client was syntactically incorrect. i dont know which is the one giving the error, but to say, i have a model class that is artist.java. My jsp pages are artist,jsp and artistview.jsp. and it is being controlled by the artistcontroller.java. I am getting this error when i edit a an artist from my artistview.jsp. it is then directed to the edit portion of artist.jsp. after editing the details filling all details again, and i press edit artist, i get the error. i have a hunch that it is coming from the uploadprofilepic method, but cant figure it out. hope you could help me on this. thanks in advance.
here are my codes.
artist.java (my model class)
package com.artistlabprod.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
#Entity
#Table(name="ARTIST")
public class Artist {
#Id
#Column(name="ID")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#Column(name="ARTISTNAME")
private String artistName;
#Column(name="SURNAME")
private String surname;
#Column(name="TALENT")
private String talent;
#Column(name="AGE")
private int age;
#Column(name="HEIGHT")
private String height;
#Column(name="WEIGHT")
private String weight;
#Column(name="HAIRCOLOR")
private String hairColor;
#Column(name="EYECOLOR")
private String eyeColor;
#Column(name="ETHNICITY")
private String ethnicity;
#Column(name="EXPERIENCE")
private String experience;
#Column(name="PHOTO")
private String photo;
#Column(name="TWITTER")
private String twitter;
#Column(name="FACEBOOK")
private String facebook;
#Column(name="INSTAGRAM")
private String instagram;
public Artist() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getArtistName() {
return artistName;
}
public void setArtistName(String artistName) {
this.artistName = artistName;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getTalent() {
return talent;
}
public void setTalent(String talent) {
this.talent = talent;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getHairColor() {
return hairColor;
}
public void setHairColor(String hairColor) {
this.hairColor = hairColor;
}
public String getEyeColor() {
return eyeColor;
}
public void setEyeColor(String eyeColor) {
this.eyeColor = eyeColor;
}
public String getEthnicity() {
return ethnicity;
}
public void setEthnicity(String ethnicity) {
this.ethnicity = ethnicity;
}
public String getExperience() {
return experience;
}
public void setExperience(String experience) {
this.experience = experience;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getTwitter() {
return twitter;
}
public void setTwitter(String twitter) {
this.twitter = twitter;
}
public String getFacebook() {
return facebook;
}
public void setFacebook(String facebook) {
this.facebook = facebook;
}
public String getInstagram() {
return instagram;
}
public void setInstagram(String instagram) {
this.instagram = instagram;
}
}
artistcontroller.java
package com.artistlabprod.controller;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.artistlabprod.model.Artist;
import com.artistlabprod.service.ArtistService;
#Controller
public class ArtistController {
private ArtistService artistService;
public ArtistService getArtistService() {
return artistService;
}
#Autowired(required=true)
#Qualifier(value="artistService")
public void setArtistService(ArtistService ps){
this.artistService = ps;
}
#RequestMapping("/")
public String home(Model model) {
model.addAttribute("listArtists", this.artistService.listArtists());
return "home";
}
#RequestMapping(value = "/index", method = RequestMethod.GET)
public ModelAndView getHome() {
ModelAndView modelandview = new ModelAndView ("index");
return modelandview;
}
#RequestMapping(value = "/aboutus", method = RequestMethod.GET)
public ModelAndView getAboutus() {
ModelAndView modelandview = new ModelAndView ("aboutus");
return modelandview;
}
#RequestMapping(value = "/contactus", method = RequestMethod.GET)
public ModelAndView getContactus() {
ModelAndView modelandview = new ModelAndView ("contactus");
return modelandview;
}
#RequestMapping(value = "/artists", method = RequestMethod.GET)
public String listArtists(Model model) {
model.addAttribute("artist", new Artist());
model.addAttribute("listArtists", this.artistService.listArtists());
return "artist";
}
#RequestMapping(value = "/artistview", method = RequestMethod.GET)
public String listofArtists(Model model) {
model.addAttribute("listArtists", this.artistService.listArtists());
return "artistview";
}
#RequestMapping(value= "/artist/add", method = RequestMethod.POST)
public String addArtist(){
return "redirect:/artistview";
}
#RequestMapping("/remove/{id}")
public String removeArtist(#PathVariable("id") int id){
this.artistService.removeArtist(id);
return "redirect:/artists";
}
#RequestMapping("/edit/{id}")
public String editArtist(#PathVariable("id") int id, Model model) {
model.addAttribute("artist", this.artistService.getArtistById(id));
model.addAttribute("listArtists", this.artistService.listArtists());
return "artist";
}
#RequestMapping(value = "/uploadProfilePic", method = RequestMethod.POST)
public String uploadBackground(#ModelAttribute("artist") Artist p, #RequestParam("file") MultipartFile file, Model model) {
String name="";
if(p.getId() == 0){
//add a new inventory item
this.artistService.addArtist(p);
p.setPhoto("photo-"+ p.getId() + ".jpg");
this.artistService.updateArtist(p);
name = p.getPhoto();
}else{
//update an existing inventory item
this.artistService.updateArtist(p);
}
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
// Creating the directory to store file
String rootPath = "C:" + File.separator + "Users"
+ File.separator + "User Folder"
+ File.separator + "Documents"
+ File.separator + "appdevupitdc"
+ File.separator + "workspace"
+ File.separator + ".metadata"
+ File.separator + ".plugins"
+ File.separator + "org.eclipse.wst.server.core"
+ File.separator + "tmp1"
+ File.separator + "webapps"
+ File.separator + "img"
+ File.separator + "artistphotos";
File dir = new File(rootPath);
if (!dir.exists())
dir.mkdirs();
// Create the file on server
File serverFile = new File(dir.getAbsolutePath()
+ File.separator + name);
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
//return listofArtists(model);
return addArtist();
} catch (Exception e) {
return "You failed to upload " + name + " => " + e.getMessage();
}
} else {
return "You failed to upload " + name
+ " because the file was empty.";
}
}
}
artist.jsp
<div class="container">
<div class="row">
<c:url var="addAction" value="/artist/add"></c:url>
<form:form action="uploadProfilePic" commandName="artist" enctype="multipart/form-data">
<table class="table table-hover table-responsive table-striped" >
<c:if test="${!empty artist.artistName}">
<tr>
<td><form:label path="id">
<spring:message text="ID" />
</form:label></td>
<td><form:input path="id" readonly="true" size="8"
disabled="true" /> <form:hidden path="id" /></td>
</tr>
</c:if>
<tr>
<td><form:label path="artistName">
<spring:message text="Name" />
</form:label></td>
<td><form:input size="35" path="artistName" /> </td>
</tr>
<tr>
<td><form:label path="surname">
<spring:message text="Surname" />
</form:label></td>
<td><form:input size="35" path="surname" /></td>
</tr>
<tr>
<td><form:label path="talent">
<spring:message text="Talent" />
</form:label></td>
<td><form:input size="35" path="talent" /></td>
</tr>
<tr>
<td><form:label path="age">
<spring:message text="Age" />
</form:label></td>
<td><form:input path="age" /></td>
</tr>
<tr>
<td><form:label path="height">
<spring:message text="Height" />
</form:label></td>
<td><form:input path="height" /></td>
</tr>
<tr>
<td><form:label path="weight">
<spring:message text="Weight" />
</form:label></td>
<td><form:input path="weight" /></td>
</tr>
<tr>
<td><form:label path="hairColor">
<spring:message text="Hair Color" />
</form:label></td>
<td><form:input size="35" path="hairColor" /></td>
</tr>
<tr>
<td><form:label path="eyeColor">
<spring:message text="Eye Color" />
</form:label></td>
<td><form:input size="35" path="eyeColor" /></td>
</tr>
<tr>
<td><form:label path="ethnicity">
<spring:message text="Ethnicity" />
</form:label></td>
<td><form:input size="35" path="ethnicity" /></td>
</tr>
<tr>
<td><form:label path="photo">
<spring:message text="Photo" />
</form:label></td>
<td><form:input type="file" name="file" path="" /></td>
</tr>
<tr>
<td><form:label path="experience">
<spring:message text="Experience" />
</form:label></td>
<td><form:textarea rows="10" cols="75" path="experience" /></td>
</tr>
<tr>
<td><form:label path="twitter">
<spring:message text="Twitter Link" />
</form:label></td>
<td><form:input size="35" path="twitter" /></td>
</tr>
<tr>
<td><form:label path="facebook">
<spring:message text="Facebook Link" />
</form:label></td>
<td><form:input size="35" path="facebook" /></td>
</tr>
<tr>
<td><form:label path="instagram">
<spring:message text="Instagram Link" />
</form:label></td>
<td><form:input size="35" path="instagram" /></td>
</tr>
<tr>
<td colspan="2"><c:if test="${!empty artist.artistName}">
<input type="submit" class="btn btn-success"value="<spring:message text="Edit Artist"/>" />
</c:if> <c:if test="${empty artist.artistName}">
<input type="submit" class="btn btn-primary" value="<spring:message text="Add Artist"/>" />
</c:if></td>
<td></td>
</tr>
<tr>
<td>
<a class="btn btn-info" href="<c:url value='/artistview' />"><i class="fa fa-list-ul fa-lg"></i> View List</a>
</td>
<td></td>
</tr>
<!-- for bottom line of table -->
<tr>
<td>
</td>
<td></td>
</tr>
</table>
</form:form>
</div>
artistview.jsp
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<h2 class="section-heading">Artist List</h2>
<h3 class="section-subheading text-muted">Lorem ipsum dolor sit amet consectetur.</h3>
</div>
</div>
<c:if test="${!empty listArtists}">
<table class="table table-hover table-responsive table-striped">
<tr>
<th>Profile Picture</th>
<th>First Name</th>
<th>Last Name</th>
<th>Talent</th>
<th>Age</th>
<th>Height</th>
<th>Weight</th>
<th>Hair Color</th>
<th>Eye Color</th>
<th>Ethnicity</th>
<th>Experience</th>
<th>Twitter Link</th>
<th>Facebook Link</th>
<th>Instagram Link</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<c:forEach items="${listArtists}" var="artist">
<tr>
<!-- <td><div style= "height: 200px; width: 200px"><img style="height: 100%; width:100%" src="photo?id=${artist.id}"/> </div>-->
<td> <img class="img-responsive" style="height: 100%; width:100%" src="/img/artistphotos/${artist.photo}" alt="" /> </td>
<td>${artist.artistName}</td>
<td>${artist.surname}</td>
<td>${artist.talent}</td>
<td>${artist.age}</td>
<td>${artist.height}</td>
<td>${artist.weight}</td>
<td>${artist.hairColor}</td>
<td>${artist.eyeColor}</td>
<td>${artist.ethnicity}</td>
<td>${artist.experience}</td>
<td>${artist.twitter}</td>
<td>${artist.facebook}</td>
<td>${artist.instagram}</td>
<td><a class="btn btn-success" href="<c:url value='/edit/${artist.id}' />"><i class="fa fa-pencil fa-lg"></i> Edit</a></td>
<td><a class="btn btn-danger" href="<c:url value='/remove/${artist.id}' />"><i class="fa fa-trash-o fa-lg"></i> Delete</a></td>
</tr>
</c:forEach>
</table>
</c:if>
there is no error showing in the console of eclipse, but
here is the error im receiving from the browser:
HTTP Status 400 -
type Status report
message
description The request sent by the client was syntactically incorrect.
Apache Tomcat/8.0.21
also the url on top displays this:
http://localhost:8080/artistweb/edit/uploadProfilePic
You are missing
(HttpServletResponse response, HttpServletRequest request)
in your method calls?
public String uploadBackground(#ModelAttribute("artist") Artist p, #RequestParam("file") MultipartFile file, Model model, HttpServletResponse response, HttpServletRequest request)
add in dispatcher-servlet.xml
<!-- setting maximum upload size -->
<beans:property name="maxUploadSize" value="10000000000000" />
</beans:bean>
I had tried from servlet set value by setattribute and it have to iterate in jsp by getattribute by setter and getter method without EL and JSTl but am getting this error .kindly help on this i searched in google but i cant found.
java.lang.NullPointerException
org.apache.jsp.Home_jsp._jspService(Home_jsp.java:138)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
here serlvet code
package servlet2;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.TreeSet;
import javafx.css.PseudoClass;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import servlet.Dao;
import jdbc.jdbcconnection;
/**
* Servlet implementation class Homepage
*/
//#WebServlet(asyncSupported = true, urlPatterns = { "/Homepage" })
public class Homepage extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Homepage() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// TODO Auto-generated method stub
System.out.println("inside==========>");
String name=request.getParameter("name");
String password=request.getParameter("password");
String phone=request.getParameter("Phone");
String Deptmart=request.getParameter("Dep");
String gender=request.getParameter("gender");
String country=request.getParameter("country");
Dao d=new Dao();
try
{
jdbcconnection jc=new jdbcconnection();
Connection con=jc.getconnection();
String sql="insert into homepage(name,password,phone,Dept,gender,Country) values(?,?,?,?,?,?)";
PreparedStatement ps=con.prepareStatement(sql);
ps.setString(1, name);
ps.setString(2, password);
ps.setString(3, phone);
ps.setString(4, Deptmart);
ps.setString(5, gender);
ps.setString(6, country);
System.out.println("ps=========>"+ps);
ps.execute();
con.commit();
String select="select * from homepage";
PreparedStatement ps1=con.prepareStatement(select);
ResultSet rs=ps.executeQuery();
ArrayList t=new ArrayList();
while(rs.next())
{
d.setid(rs.getInt(1));
d.setName(rs.getString(2));
d.setPassword(rs.getString(3));
d.setPhone(rs.getInt(4));
d.setDeptmart(rs.getString(5));
d.setGender(rs.getString(6));
d.setCountry(rs.getString(7));
t.add(d);
}
request.setAttribute("users",t);
RequestDispatcher rs1=request.getRequestDispatcher("/Home.jsp");
rs1.forward(request, response);
}
catch (SQLException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Jsp page:
<%#page import="servlet.Dao,java.util.*" %>
<!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>Insert title here</title>
</head>
<body>
<form action="Homepage" method="get">
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="name" id="name"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="text" name="password" id="password"></td>
<tr>
<td>Phone:</td>
<td><input type="text" name="Phone" id="Phone">
</tr>
</td>
<tr>
<td>Department:</td>
<td><select id="Dep" name="Dep">
<option value="it">IT</option>
<option value="finace">Finace</option>
<option value="market">Marketing</option>
</select></td>
</tr>
<tr>
<td>Gender:</td>
<td><input type="radio" name="gender" id="gender" Value="Male">Male
<input type="radio" name="gender" id="gender" Value="Female">Female</td>
</tr>
<tr>
<td>Country:</td>
<td><input type="checkbox" name="country" id="country"
Value="India">India <input type="checkbox" name="country"
id="country" Value="Other">Other</td>
</tr>
<br>
<tr>
<td><input type="submit" name="Add" Value="ADD" ></td>
<td><input type="button" name="Clear" Value="CLEAR"></td>
</tr>
</table>
</form>
<table border="1">
<tr><td>Id</td><td>name</td>
<td>Password</td>
<td>Phone</td>
<td>Deptmart</td>
<td>Gender</td>
<td>country</td>
<td>Edit</td>
<td>Delete</td>
</tr>
<%
try
{
List<Dao> al1 = (List) request.getAttribute("users");
// System.out.println(al1); // prints null
for(Dao user : al1) {
%>
<tr>
<td><%=user.getid() %></td>
<td><%=user.getName() %></td>
<td><%=user.getPassword() %></td>
<td><%=user.getPhone() %></td>
<td><%=user.getDeptmart() %></td>
<td><%=user.getGender() %></td>
<td><%=user.getCountry() %></td>
<td></td>
<td></td>
</tr>
<%} }
catch(Exception e)
{
e.printStackTrace();
}
%>
</table>
</body>
</html>
web.xml
<servlet>
<servlet-name>Homepage</servlet-name>
<servlet-class>servlet2.Homepage</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Homepage</servlet-name>
<url-pattern>/Homepage</url-pattern>
</servlet-mapping>
I have a screen which contains dojo sx:div. The action class who manage the loading of the div is different that the principal. but when i click on my link i would like refresh the sx:div with parameter input in the main form. How can I do that ?
JSP File :
<%# taglib prefix="s" uri="/struts-tags"%>
<%# taglib prefix="sx" uri="/struts-dojo-tags"%>
<script language="javascript">
function refreshDiv() {
var td = element.parentNode;
document.getElementById('idSubFamily').value = td.getAttribute('id');
dojo.event.topic.publish("/listQuestionTopic", "0", "1");
}
</script>
<table class="board" width="100%">
<tr class="titre">
<td class="titleFamily" width="30%" height="32"><s:property
value="getText('resultat.sous_famille.question.label')" /></td>
<s:if test="%{displayWeight}">
<td class="titleFamily" width="30%" height="32"><s:property
value="getText('question.weight.label')" /></td>
</s:if>
</tr>
<s:if test="%{subFamilyItem.size != 0}">
<s:iterator value="subFamilyItem" status="rowstatus">
<s:if test="#rowstatus.odd == true">
<s:set name="trClass" value="%{'even'}"></s:set>
</s:if>
<s:else>
<s:set name="trClass" value="%{'odd'}"></s:set>
</s:else>
<tr class="<s:property value="#trClass"/>">
<td class="family_<s:property value="#trClass"/>"><s:a
cssClass="board" onclick="refreshDiv()">
<s:property value="%{getText(traductionCode)}" />
</s:a></td>
<s:if test="%{displayWeight}">
<td class="family_<s:property value="#trClass"/>"><s:property
value="%{weight}" /></td>
</s:if>
</tr>
</s:iterator>
</s:if>
</table>
<sx:div id="listQuestions" href="Question.do" formId="idFormQuestion"
listenTopics="/listQuestionTopic" theme="ajax" preload="false">
<s:hidden id="idFamily" name="idFamilySelected"></s:hidden>
</sx:div>
PrinciaplAction class :
package com.omb.controller;
import java.util.ArrayList;
import java.util.List;
import com.omb.ui.SubFamilyItem;
import com.opensymphony.xwork2.ActionSupport;
public class PrincipalAction extends ActionSupport {
private List<SubFamilyItem> subFamilyItem = new ArrayList<SubFamilyItem>();
#Override
public String execute() throws Exception {
subFamilyItem.add(new Item("1", "Family 1"));
subFamilyItem.add(new Item("2", "Family 2"));
return SUCCESS;
}
public List<Item> getSubFamilyItem() {
return this.subFamilyItem;
}
public void setSubFamilyItem(List<Item> subFamilyItem) {
this.subFamilyItem = subFamilyItem;
}
}
DivAction class :
package com.omb.controller;
import com.opensymphony.xwork2.ActionSupport;
public class DivAction extends ActionSupport {
Service myService;
// From the principal screen
Long idFamilySelected;
/**
*
* #see com.opensymphony.xwork2.ActionSupport#execute()
*/
public String execute() {
MyObject object = myService.findObject(idFamilySelected);
return SUCCESS;
}
public String getMyService() {
return this.subFamilySelected;
}
public void setMyService(Service myService) {
this.myService = myService;
}
public String getidFamilySelected() {
return this.idFamilySelected;
}
public void setidFamilySelected(Service idFamilySelected) {
this.idFamilySelected = idFamilySelected;
}
}
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>