have HTTP error "Unable to compile class for JSP" - maven

I am working in a JSP project. While runnning the project using Netbeans with Tomcat 7.0.68 server, I got the following exception,
HTTP Status 500 - Unable to compile class for JSP:
HTTP Status 500 - Unable to compile class for JSP:
**type** Exception report
**message** Unable to compile class for JSP:
**description** The server encountered an internal error that prevented it from fulfilling this request.
**exception**
org.apache.jasper.JasperException: Unable to compile class for JSP:
An error occurred at line: [14] in the generated java file: [C:\apache-tomcat-7.0.68\work\Catalina\localhost\Rites1\org\apache\jsp\Register_jsp.java]
The import com.sun.corba.se.spi.presentation.rmi.StubAdapter.request cannot be resolved
An error occurred at line: [14] in the generated java file: [C:\apache-tomcat-7.0.68\work\Catalina\localhost\Rites1\org\apache\jsp\Register_jsp.java]
Syntax error on token "(", . expected
An error occurred at line: [16] in the generated java file: [C:\apache-tomcat-7.0.68\work\Catalina\localhost\Rites1\org\apache\jsp\Register_jsp.java]
The import String cannot be resolved
An error occurred at line: [17] in the generated java file: [C:\apache-tomcat-7.0.68\work\Catalina\localhost\Rites1\org\apache\jsp\Register_jsp.java]
Syntax error on tokens, Name expected instead
**Stacktrace**:
org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:103)
org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:366)
org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:490)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:379)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:354)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:341)
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:662)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:364)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.68 logs.
Apache Tomcat/7.0.68
I'm building a registration form in a file called Register.jsp in a maven project using netbeans
<%#page import="com.sun.corba.se.spi.presentation.rmi.StubAdapter.request(
Object, String, boolean)"%>
<%#page import="java.lang.ClassNotFoundException"%>
<%#page import="java.io.FileNotFoundException"%>
<%#page import="java.io.InputStream"%>
<%#page import="java.io.FileInputStream"%>
<%#page import="java.io.File"%>
<%#page import="javax.swing.JComboBox"%>
<%#page import="javax.swing.JTextField"%>
<%#page import="javax.swing.JRadioButton"%>
<%#page import="java.sql.*" %>
<%#page import="java.util.Date" %>
<% Class.forName("com.mysql.jdbc.Driver");%>
<%#page contentType="text/html" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" ></meta>
<link rel="stylesheet" type="text/css" href="CSS/RitesCSS.css"/>
<link rel="stylesheet" type="text/css" href="CSS/Resize.css" media="screen and (max-widht:1000px)"/>
<link rel="stylesheet" type="text/css" href="CSS/Menu.css"/>
<link rel="stylesheet" type="text/css" href="CSS/Layout.css"/>
<style type="text/css">
body{
margin-bottom: 0px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
}
</style>
<title>Register Now</title>
</head>
<body>
<%!
public class Followers {
String URL = "jdbc:mysql://localhost:3306/rites";
String USERNAME = "myusername";
String PASSWORD = "mypass";
Connection connection = null;
PreparedStatement insertUsers = null;
ResultSet resultSet = null;
public Followers() {
try {
connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
insertUsers = connection.prepareStatement(
"INSERT INTO followers (HajjID,UserName,ID,Phone,Country,Passport,Language,Gender,Photo,Password,State,DOB,adress)"
+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?);"
);
} catch (SQLException e) {
e.printStackTrace();
}
}
public int setFollowers(String HajjID, String UserName, String ID, String Phone, String country, String PassportNo, String Language, String rdoGender, String img, String txtPassword, String States, String DoB, String txtarAddress) {
int result = 0;
FileInputStream fis = null;
File Photo = new File("");
img = fis.toString();
try {
insertUsers.setString(1, HajjID);
insertUsers.setString(2, UserName);
insertUsers.setString(3, ID);
insertUsers.setString(4, Phone);
insertUsers.setString(5, country);
insertUsers.setString(6, PassportNo);
insertUsers.setString(7, Language);
insertUsers.setString(8, rdoGender);
try {
fis = new FileInputStream(Photo);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
insertUsers.setString(9, img);
insertUsers.setString(10, txtPassword);
insertUsers.setString(11, States);
insertUsers.setString(12, DoB);
insertUsers.setString(13, txtarAddress);
result = insertUsers.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
}
%>
<%
int result = 0;
if (request.getParameter("submit") != null) {
String Type = new String();
String HajjID = new String();
String UserName = new String();
String ID = new String();
String Phone = new String();
String country = new String();
String PassportNo = new String();
String Language = new String();
String rdoGender = new String();
String Photo = new String();
String txtPassword = new String();
String States = new String();
String DoB = new String();
String txtarAddress = new String();
if (request.getParameter("Type").toString() != null) {
Type = request.getParameter("Type").toString();
}
if (request.getParameter("HajjID").toString() != null) {
HajjID = request.getParameter("HajjID").toString();
}
if (request.getParameter("ID").toString() != null) {
ID = request.getParameter("ID").toString();
}
if (request.getParameter("Phone").toString() != null) {
Phone = request.getParameter("Phone").toString();
}
if (request.getParameter("country").toString() != null) {
country = request.getParameter("country").toString();
}
if (request.getParameter("PassportNo").toString() != null) {
PassportNo = request.getParameter("PassportNo").toString();
}
if (request.getParameter("Language").toString() != null) {
Language = request.getParameter("Language").toString();
}
if (request.getParameter("rdoGender").toString() != null) {
rdoGender = request.getParameter("rdoGender").toString();
}
if (request.getParameter("Photo").toString() != null) {
Photo = request.getParameter("Photo").toString();
}
if (request.getParameter("txtPassword").toString() != null) {
txtPassword = request.getParameter("txtPassword").toString();
}
if (request.getParameter("States").toString() != null) {
States = request.getParameter("States").toString();
}
if (request.getParameter("DoB").toString() != null) {
DoB = request.getParameter("DoB").toString();
}
if (request.getParameter("txtarAddress").toString() != null) {
txtarAddress = request.getParameter("txtarAddress").toString();
}
Followers users = new Followers();
result = users.setFollowers(HajjID, UserName, ID, Phone, country, PassportNo, Language, rdoGender, Photo, txtPassword, States, DoB, txtarAddress);
}
%>
<form id="form1" runat="server" action="register.php" method="POST">
<div id="contaner">
<div id="header">
<img src="logo.jpg" align="left"></img>
<h1> Rites</h1>
<li>Register now</li>
</div>
<div id="menu">
<ul>
<li>Home</li>
<li>About</li>
<li>Rites</li>
<li>Contact us</li>
<li>Login</li>
</ul>
</div>
<div id="mainbody">
<div id="pageHeading"> <v>Registeration</v></div>
<div id="bodyLeft">
</div>
<div id="bodyRight"><h5>
<form name="registration" action="RegServlet" method="post" id="registerForm">
<table id="table1">
<tr>
<td>User name</td>
<td><input type="text" name="UserName" id="txt" class='StyleTxtField'/></td>
</tr>
<tr>
<td>ID</td>
<td><input type="text" name="ID" id="txt" class='StyleTxtField'/></td>
</tr>
<tr>
<td>Phone</td>
<td><input type="text" name="Phone" id="txt" class='StyleTxtField'/></td>
</tr>
<tr>
<td>Country</td>
<td><select name="country" id="txt" class='StyleSelectFiled'>
<option value="">Country...</option>
<option value="Afganistan">Afghanistan</option>
<option value="Albania">Albania</option>
<option value="Algeria">Algeria</option>
</select></td>
</tr>
<tr>
<td>Date of Birth</td>
<td>
<input type="date" name="DoB" id="txt" class='StyleTxtField'/>
</td>
</tr>
<tr>
<td>Address</td>
<td>
<textarea name="txtarAddress" id="txt" class='StyleTxtField'></textarea>
</td>
</tr>
<tr>
<td>Type</td>
<td><input type="radio" name="Type" id="Leader" value="Leader" ><label for="Leader">Leader</label>
<input type="radio" name="Type" id="Follower" value="Follower" onsubmit="setFollowers"><label for="Follower">Follower</label></td>
</tr>
<tr>
<td></td>
<input type="hidden" name="hidden" value="<%= result%>" />
<td><br><button type="reset" id="btm"><m>Reset</m></button>
<button type="submit" id="btm"><m>Register</m></button></td>
</tr>
</table><br>
</form></h5>
<SCRIPT language="JavaScript">
<!--
function dusplayResults()
{
if (document.myForm.hidden.value === 1) {
alert("Data Inserted1!");
}
}
</SCRIPT>
</div>
</div>
</div>
</form>
</body>
</html>
i want to do this "if the chosen radio button named "type" is follower insert the data into the follower table, and if the chosen radio button named "type" is leader insert the data into the leader table"
I'm using a database called rites in phpmyadmine

<%#page import="com.sun.corba.se.spi.presentation.rmi.StubAdapter.request(
Object, String, boolean)"%>
your import is wrong.
use
<%# page import="static com.sun.corba.se.spi.presentation.rmi.StubAdapter.register" %>

Related

The object in the Controller is not filled in when calling the POST method, it gives an error

I am making a Spring MVC application, when I fill out a table in jsp and click the "save" button, the data is not saved, an error is generated: Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null];
here is the output I have on the console: Pass_in_trip [key=null, trip=Trip [trip_no=0, comp=Company [id_comp=0, name=null], plane=null, town_from=null, town_to=null, time_out=null, time_in=null, passInTrips=[]], passenger=Passenger [name=null, passengerId=0, passInTrips=[]], place=6f, date=null]
and at the input to the insert method, my object is empty, tell me what I'm doing wrong?
Controller
#PreAuthorize("hasRole('ROLE_Admin')")
#RequestMapping(value = "insert", method = RequestMethod.GET)
public String insertnewform(Pass_in_trip pass_in_trip, Model uiModel) {
uiModel.addAttribute("trip",service.findallTrip());
uiModel.addAttribute("passenger",service.findallPassenger());
return "/pass_in_trip/insert";
}
#PreAuthorize("hasRole('ROLE_Admin')")
#RequestMapping(value = "insert", method = RequestMethod.POST)
public String insert(Pass_in_trip pass_in_trip, BindingResult bindingResult, Model uiModel,
HttpServletRequest httprervletrequest, RedirectAttributes redirectatributes) {
System.out.println(pass_in_trip);
if (bindingResult.hasErrors()) {
uiModel.addAttribute("pass_in_trip", pass_in_trip);
return "pass_in_trip/edit";
}
service.save(pass_in_trip);
return "redirect:/pass_in_trip/";
}
Insert.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Pass_in_trip</title>
<style>
form fieldset {
width: 40%;
}
form fieldset label {
display: block;
/*width : 50%;
float :left;*/
}
form fieldset input, form fieldset select, form fieldset textarea {
width: 100%;
}
</style>
</head>
<body>
<h1>Pass_in_trip</h1>
<form method="POST">
<fieldset>
<div>
<label>Flight:</label>
<select name="trip">
<c:forEach var="trip" items="${trip}">
<option value="${trip}" label="№ ${trip.trip_no} ${trip.town_from} ${trip.town_to}"/>
</c:forEach>
</select>
</div>
<div>
<label>Passenger:</label>
<select name="passenger">
<c:forEach var="passenger" items="${passenger}">
<option value="${passenger}" label="${passenger.passengerId} ${passenger.name}">
</c:forEach>
</select>
</div>
<div>
<label>Date: </label>
<input type="datetime" name="date" value="${pass_in_trip.date}">
</div>
<div>
<label>Place:</label>
<input type="text" name="place" value="${pass_in_trip.place}">
</div>
<div>
<input type="submit" value="Save">
</div>
</fieldset>
</form>
</body>
</html>
Pass_in_trip
#Entity
#Table (name="pass_in_trip")
public class Pass_in_trip implements Serializable {
#Override
public String toString() {
return "Pass_in_trip [key=" + key + ", trip=" + trip + ", passenger=" + passenger + ", place=" + place
+ ", date=" + date + "]";
}
#EmbeddedId
private KeysPass_in_trip key;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("tripId")
#JoinColumn(name="trip_no")
Trip trip = new Trip();
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("psgId")
#JoinColumn(name="id_psg")
Passenger passenger = new Passenger();
#Column(name="place")
private String place;
#Column(name="date")
private Timestamp date;
//Getters and setters

How to send dropdown value from the html form to the controller?

index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Super Spy App</title>
</head>
<body>
<h1>Our Super Cool Spy App</h1>
<h2>Create a Mission</h2>
<form action="/addMission" method="post">
<p><input type="submit" value="Create a Mission"></p>
</form>
<form action="/viewMission" method="get">
<h2>View Missions for</h2>
<select id="agents" name="agents">
<option value="Johnny English">Johnny English</option>
<option value="Natasha Romanova">Natasha Romanova</option>
<option value="Austin Powers">Austin Powers</option>
</select>
<input type="submit" value="Go">
</form>
</body>
</html>
ViewMissions.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>View Missions</title>
</head>
<body>
<h1> Here are the missions for</h1>
<div th:if="${missionList.empty}">
<h2>No Current Missions</h2>
</div>
<div th:unless="${missionList.empty}">
<table border="1">
<tr>
<th>Title</th>
<th>Gadget 1</th>
<th>Gadget 2</th>
<th colspan="2">Operation</th>
</tr>
<tr th:each="mission : ${missionList}">
<td th:text="${mission.title}"></td>
<td th:text="${mission.gadget1}"></td>
<td th:text="${mission.gadget2}"></td>
<td>edit</td>
<td>delete</td>
</tr>
</table>
</div>
<p> Back to home </p>
</body>
</html>
Controller Class
#GetMapping("/")
public String Home() {
return "index";
}
#PostMapping("/addMission")
public String addMission(Model model) {
model.addAttribute("mission", new Mission());
return "create_mission";
}
#GetMapping("/createMission")
public String ViewMission1(Model model) {
List<Mission> mission1 = database.getMissions();
model.addAttribute("missionList", mission1);
return "view_missions";
}
#PostMapping("/createMission")
public String createMission(#ModelAttribute Mission mission) {
int returnValue = database.createMission(mission);
System.out.println(returnValue);
return "view_missions";
}
#GetMapping("/viewMission")
public String viewMission2(Model model) {
List<Mission> mission1 = database.getMissions();
model.addAttribute("missionList", mission1);
return "view_missions";
}
getMissions method
public List<Mission> getMissions() {
MapSqlParameterSource namedParameters = new MapSqlParameterSource();
String query = "SELECT * FROM missions";
BeanPropertyRowMapper<Mission> missionMapper = new BeanPropertyRowMapper<Mission>(Mission.class);
List<Mission> missions = jdbc.query(query, namedParameters, missionMapper);
return missions;
}
Mission.java (the getter setter are already set but I didn't paste them here to prevent hustle and bustle)
public class Mission {
private Long id;
private String agent;
private String title;
private String gadget1;
private String gadget2;
}
So, in the above examples, I want to send the value selected from the dropdown list to my controller.
Im my html, if I select any value from the dropdown and press 'Go' it shows me the whole database for all the 3 agents but not the particular one that I selected.
Any suggestions how to curb this error.
I have tried searching for a solution on internet but they were using JSP which I haven't studied yet.
You can get the value submitted from the view to the controller in many ways. As you have a single value is passed from View to Controller you can use
#RequestParam
Your viewMission may look like this
#GetMapping("/viewMission")
public String viewMission2(#RequestParam#RequestParam(name = "agents", required = true) String agents, Model model) {
List<Mission> mission1 = database.getMissions(String agents);
model.addAttribute("missionList", mission1);
return "view_missions";
}
You have to pass the selected value to your query to filter the list based on the selected agent and your query will be
public List<Mission> getMissions(String agents) {
MapSqlParameterSource namedParameters = new MapSqlParameterSource();
String query = "SELECT * FROM missions WHERE agent ='" + agent +"'";
BeanPropertyRowMapper<Mission> missionMapper = new BeanPropertyRowMapper<Mission>(Mission.class);
List<Mission> missions = jdbc.query(query, namedParameters, missionMapper);
return missions;
}
Which will filter the list.

Passing two parameters using ajax and getting the values of parameters in another page

how can i pass two parameters using ajax from two different textboxes to another page.
which function should i use to do this.
Index.jsp
<html>
<head>
<script type="text/javascript">
function sendInfo(str,stri)
{
var XMLhttp;
if(str=="")
{
document.getElementById("my").InnerHTML="";
}
if(window.XMLHttpRequest)
{
XMLhttp=new XMLHttpRequest();
}
else
{
XMLhttp=new ActiveXObject("Microsoft.XMLhttp");
}
XMLhttp.onreadystatechange=function()
{
if(XMLhttp.readyState==4 && XMLhttp.status==200)
{
document.getElementById("my").innerHTML=XMLhttp.responseText;
}
}
XMLhttp.open("GET","get.jsp?feeid="+str+"&sid="+stri,true);
XMLhttp.send();
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>fee processing</title>
</head>
<body>
<h3>Fee Transaction</h3>
<form method="post" action="myservlet">
<table>
<tr>
<td>Date of Transaction</td>
<td><input type="text" name="date"/></td>
</tr>
<tr><td>Feeid</td>
<td><input type="text" name="feeid" onkeyup ="sendInfo(this.value)"></td></tr>
<tr><td>Student Id</td><td><input type="text" name="sid" onkeyup="sendInfo(this.value)"/></td></tr>
<tr><td><div id="my"></div></td></tr>
<tr><td>amount</td>
<td><input type="text" name="amount"/></td></tr>
<tr><td>Remaining</td>
<td><input type="text" name="remain"/></td>
</tr>
<tr><td><input type="submit" name="submit" value="submit"></td></tr>
</table>
</form>
</body>
</html>
get.jsp: i want those two parameter values in this page.
</head>
<body>
<form method="post" action="index.jsp">
<% String fid = request.getParameter("feeid");
int fidd =Integer.parseInt(fid);
System.out.print(fid);
String sid = request.getParameter("sid");
int sidd = Integer.parseInt(sid);
try
{
//int i =3;
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3307/mdb","root","tiger");
Statement stmt = con.createStatement();
//System.out.print("a");
String query1 = "select amount from feestudent where st_id="+sidd+" and fees_id="+fidd;
ResultSet rs = stmt.executeQuery(query1);
if(rs.next())
{
// System.out.print("d");
%>
<table>
<tr>
<td><input type="text" name = "totalamt" value="<%=rs.getInt("amount") %>"/></td>
<%
}
}
catch(Exception e)
{
e.printStackTrace();
}
%>
</tr>
</table>
%>
</form>
</body>
</html>
please Help me.
Thanks.
The problem in your code is caused by this line in the HTML:
<td><input type="text" name="feeid"
"which function should i use here?" ="sendInfo(this.value)"></td>
Your sendInfo(str, stri) JavaScript function expects two parameters, but you are only passing in one. Pass in a value for stri and you should be good to go.

How to reject a field from bean for validation when binding?

I have three fields department_Id,department_Name,department_location in departmentForm act as a model object in this model form.
I have use annotation to validate the fields. Now, I want to only use two fields in different jsp page say create.jsp and one field in different jsp page say getDepartmentById.
When I press submit button of create.jsp, validation is happening but after providing correct information its not submitted cause in this page.
I haven't give one field department_Id which is auto generated by my DAO layer. So, please help me, how to reject this value to execute my create.jsp page for successfully creating department in database.
When I printed the BindingResult object, it shown as follow:
Field error in object 'departmentForm' on field 'departmentId': rejected value [null];
codes [NotEmpty.departmentForm.departmentId,NotEmpty.departmentId,NotEmpty.java.lang.String,NotEmpty];
arguments [org.springframework.context.support.DefaultMessageSourceResolvable:
codes [departmentForm.departmentId,departmentId]; arguments [];
default message [departmentId],org.hibernate.validator.constraints.NotEmpty.message},
[Ljava.lang.Class;#4fc4a198,[Ljava.lang.Class;#764d2b11];
default message [may not be empty]`
This is how I coded in controller:
#RequestMapping(value = "/createDepartment", method = RequestMethod.POST)
public String createEmployee(#Valid DepartmentForm departmentForm,
BindingResult bindingResult, Map<String, DepartmentForm> model)
throws Exception {
if (bindingResult.hasErrors()) {
System.out.println(bindingResult);
bindingResult.reject(departmentForm.getDepartmentId());
return "departmentForm";
}
System.out.println("mr ankur jadiy");
model.put("departmentForm", departmentForm);
departmentForm.setUpdateStatus('A');
if (departmentForm.getUpdateStatus() == 'A') {
departmentServiceImpl
.actionDecider(convertDeptFormToDeptBO(departmentForm));
}
return "Success";
}
my DepartmentForm code is as follow:
package com.nousinfo.tutorial.model;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
public class DepartmentForm {
#NotEmpty
#Size(min = 1, max = 20,message="")
private String departmentId;
#NotEmpty
private String departmentName;
private String departmentLocation;
private Character updateStatus;
public String getDepartmentId() {
return departmentId;
}
public void setDepartmentId(String departmentId) {
this.departmentId = departmentId;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public String getDepartmentLocation() {
return departmentLocation;
}
public void setDepartmentLocation(String departmentLocation) {
this.departmentLocation = departmentLocation;
}
public Character getUpdateStatus() {
return updateStatus;
}
public void setUpdateStatus(Character updateStatus) {
this.updateStatus = updateStatus;
}
}
and my create.jsp is
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://jakarta.apache.org/taglibs/input-1.0" prefix="input"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="s"%>
<%# 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>Create Department</title>
<link rel="stylesheet" href="css/style.css" type="text/css"></link>
</head>
<body>
<table width="1254" height="74" border="0" align="center">
<tr>
<td width="300" height="68" align="center" bgcolor="#99CCFF"><h2>
<span class="style1">Employee Details </span>
</h2></td>
<td width="100" height="68" align="center" bgcolor="#FFFFFF"><img
src="./image/emps.jpg" width="190" height="92" /></td>
</tr>
</table>
<p>
<br />
</p>
<hr size="1" width="786">
<form:form id="form" method="post" action="/EmployeeWebSpring/departmentController/createDepartment"
modelAttribute="departmentForm">
<table>
<tr>
<form:hidden path="updateStatus" />
</tr>
<tr>
<td>
Department_Name:
<font color="red"><form:errors path="departmentName" /></font>
</td>
</tr>
<tr>
<td><form:input path="departmentName" /></td>
</tr>
<tr>
<td>
Department_Location:
<font color="red"><form:errors path="departmentLocation" /></font>
</td>
</tr>
<tr>
<td><form:input path="departmentLocation" /></td>
</tr>
</table>
<br>
<br />
<p> </p>
<br>
<tr>
<td><input type="submit" name="method" value="save" /></td>
<td><input type="submit" name="method" value="cancel" /></td>
</tr>
<hr size="1" width="786">
<p> </p>
</form:form>
</body>
</html>
What the error says is that you're missing value for departmentId, which is not surprising since you defined it as
#NotEmpty
#Size(min = 1, max = 20,message="")
You don't really need to validate departmentId if it's autogenerated by your code. You probably should remove it from the DepartmentForm, especially since it's not in the form, or at least make it optional.
You can make it mandatory in your business object, but the form backing object should reflect what's in the form.
update
If departmentId is a database-generated id, you should set it as disallowed in your controller's InitBinder:
#InitBinder
public void initBinder(WebDataBinder binder) {
binder.setDisallowedFields(new String[] { "departmentId" });
}

Unable load dropdown list when the page was loading in spring mvc

I trying to populate the dropdown list when page was loaded.But it is not loaded in UserPage.jsp from Controller.on submit method and also wrote referencedata method.
Controller:-
public ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
log.info("onSubmit handleRequest method"
+ request.getParameter("username"));
System.out.println("onSubmit handleRequest method"
+ request.getParameter("username"));
String username = "", password = "";
username = request.getParameter("username");
password = request.getParameter("password");
UserBean ubean = null;
System.out.println("After shownform method called");
HttpSession session = request.getSession(true);
try {
ubean = userservice.chkUsername(username, password);
System.out.println("Information" + ubean.getUsername());
} catch (DataException ex) {
ex.printStackTrace();
// throw ex;
}
session.setAttribute("User", ubean);
EmpPersonalBean personalBean = new EmpPersonalBean();
return new ModelAndView("jsp/UserPage", "EmpPersonalBean", personalBean);
}
protected Map referenceData(HttpServletRequest request) throws Exception {
log.info("UserDBBoardController======================referenceData");
Map referenceData = new HashMap();
List deparementList = new ArrayList();
deparementList = userservice.getDeparmentList();
referenceData.put("deparmentList", deparementList);
return referenceData;
}
UserPage.jsp
<%# page language="java" import="com.aims.bean.*,java.util.HashMap" contentType="text/html;charset=utf-8" pageEncoding="UTF-8"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%#taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%#taglib uri="/WEB-INF/tld/c.tld" prefix="c" %>
<html>
<head>
<title>AAI</title>
</head>
<body>
<form:form method="post" modelAttribute="EmpPersonalBean" action="userpage.htm">
<table>
<tr>
<td>Welcome <%=((UserBean)session.getAttribute("User")).getUsername()%></td>
</tr>
<tr>
<td>Department</td>
<td><form:select path="deparment">
<form:option value="NONE" label="--- Select ---" />
<form:options items="${deparmentList}" />
</form:select>
</td>
</tr>
</tr>
</table>
</form:form>
</body>
</html>
public class DepartmentBean {
private String deptcode,deptname;
public String getDeptcode() {
return deptcode;
}
public void setDeptcode(String deptcode) {
this.deptcode = deptcode;
}
public String getDeptname() {
return deptname;
}
public void setDeptname(String deptname) {
this.deptname = deptname;
}
}
And also attached displaying dropdown list in the userpage.sjp
Please help me.How to resolve the issue.
You also need to specify itemLabel and itemValue attributes in <form:options/> tag.
UPDATE
Replace this line in your jsp page. I think it should resolve your problem.
<form:options items="${deparmentList}" itemLabel="deptname" itemValue="deptcode" />
Hope this helps you. Cheers.
<td>Department</td>
<td><form:select path="deparment">
<form:option value="NONE" label="--- Select ---" />
<c:forEach var="department" items="${deparmentList}">
<form:option value="${department}" label="${department}" />
</c:forEach>
</form:select>
</td>
ModelAndView mav = new ModelAndView("viewName");
mav.addObject("deparmentList", deparementList);
return mav;
return modelAndView object.

Resources