Spring unable to get form values - java

Im using the below servlet to get the form values, when the form is posted im able to get the username and password but unable to access it in the mainpage.jsp which displays the username/password.
Servlet
package com.school.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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.school.beans.Login;
#Controller
public class Logincontroller {
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView login() {
return new ModelAndView("login", "loginform", new Login());
}
#RequestMapping(value = "/validatelogin", method = RequestMethod.POST)
public String validatelogin(#ModelAttribute("SchoolManagement")Login login,
ModelMap model) {
model.addAttribute("username", login.getUsername());
model.addAttribute("password", login.getPassword());
System.out.println("useranme = " + login.getUsername());
System.out.println("password = " + login.getPassword());
return "mainpage";
}
}
login.jsp
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<!--
<script src="javascript/login.js"></script>
<link rel="stylesheet" type="text/css" href="css/login.css"/>
http://www.mkyong.com/spring-mvc/spring-mvc-how-to-include-js-or-css-files-in-a-jsp-page/
-->
<!--<script src="<c:url value="/resources/js/jquery.1.10.2.min.js" />"></script>-->
<link href="<c:url value="/resources/css/login.css" />" rel="stylesheet">
<script src="<c:url value="/resources/js/login.js" />"></script>
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div id="top"></div>
<div id="middle">
<form:form method="POST" id="loginform" commandName="loginform"
action="/SchoolManagement/validatelogin">
<form:label path="username"> Username:</form:label>
<form:input path="username" /> <br>
<form:label path="password"> Password:</form:label>
<form:input path="password" />
<input type="submit" value="submit">
</form:form>
</div>
<div id="bottom"></div>
</body>
</html>
mainpage.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#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>MainPage</title>
</head>
<body>
<h2>Submitted Student Information</h2>
<table>
<tr>
<td>Name</td>
<td>${username}</td>
</tr>
<tr>
<td>Password</td>
<td>${password}</td>
</tr>
</table>
</body>
</html>

Try getting the values directly out of the request.
<%
String username = (String) request.getAttribute("username");
String password = (String) request.getAttribute("password");
%>
<table>
<tr>
<td>Name</td>
<td><%= username %></td>
</tr>
<tr>
<td>Password</td>
<td><%= password %></td>
</tr>
</table>
That should definitely work... if not, something's wrong with the setup.

your command name
commandName="loginform"
is different than model attribute
#ModelAttribute("SchoolManagement")
try to use same names

Related

spring:mvcUrl mapping wrong id

I am trying to map productId to URL in my jsp page, but the value is wrong.
The URL is returning Título 1 but the response is returning the right value:
HTML Mapping
My jsp code:
<%# page language="java" contentType="text/html; charset=iso-8859-1" pageEncoding="iso-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>Insert title here</title>
</head>
<body>
<div>
${success}
</div>
<table>
<tr>
<td>Id</td>
<td>Titulo</td>
<td>Valores</td>
</tr>
<c:forEach items="${products}" var="product">
<tr>
<td>${product.id}</td>
<td>${product.title}</td>
<td>
<c:forEach items="${product.prices}" var="price">
[${price.value} - ${price.bookType}]
</c:forEach>
</td>
</tr>
</c:forEach>
</table>
My Java Controller Code:
#RequestMapping(method=RequestMethod.GET)
public ModelAndView list() {
ModelAndView modelAndView = new ModelAndView("products/list");
modelAndView.addObject("products", productDAO.list());
return modelAndView;
}
My Java DAO Code:
public List<Product> list() {
return manager.createQuery("select distinct(p) from Product p join fetch p.prices", Product.class).getResultList();
}
Unfortunately I cannot see your method 'show'.
I guess you have a misprint in the path:
#RequestMapping("/show{/id}")
//--------------------^^ WRONG
public String show(#PathVariable("id") long id) {
...
}
instead
#RequestMapping("/show/{id}")
//--------------------^^ RIGHT

Passing parameter from controller to jsp in spring

I have a controller method as follow.
#RequestMapping("/edit/{jobId}")
public String editJob(#PathVariable("jobId") Integer jobId,Model model){
model.addAttribute("id",jobId);
return "edit";
}
in which i am passing the jobId to get the instance of the job by id and returning "edit" string so that it maps to edit.jsp as per the InternalResourceViewResolver. But when i click on the link it goes to /edit/44 in which case 44 would be the id of the job for which the edit link belongs to. Finally i got the error stating no resource found.
home.jsp
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# page session="false"%>
<html>
<head>
<link rel="stylesheet" type="text/css"
href="<c:url value="/resources/css/style.css"/>" />
<link rel="stylesheet"
href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<title>Home</title>
</head>
<body id="main">
<div class="container">
<h2 style="color:white">All posted jobs</h2>
<c:if test="${empty jobList}">
<h6>No Job Post Yet</h6>
</c:if>
<c:if test="${!empty jobList}">
<c:forEach items="${jobList}" var="job">
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title">${job.title }</h3>
</div>
<div class="panel-body">${job.description }</div>
<div class="panel-footer">
<a id="link" href="delete/${job.id }">Delete</a>
<a id="link" href="edit/${job.id}">Edit</a>
</div>
</div>
</c:forEach>
</c:if>
<section>
<form:form method="post" action="add" modelAttribute="job"
class="form-horizontal">
<div class="form-group" id="addForm">
<form:label class="control-label" path="title">Title:</form:label>
<form:input class="form-control" path="title"/>
<form:label class="control-label" path="description">Description</form:label>
<form:textarea class="form-control" rows="5" path="description" />
<button class="btn btn-success">
<span class="glyphicon glyphicon-plus-sign"></span> Add a Job
</button>
</div>
<a id="addJob" href="add">+</a>
</form:form>
</section>
</div>
JobController.java
package com.job.src;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.job.src.model.Job;
import com.job.src.services.JobService;
#Controller
public class JobController {
#Autowired
private JobService jobService;
#RequestMapping(value= "/")
public String listJobs(Map<String,Object> map){
map.put("job", new Job());
map.put("jobList", jobService.listJobs());
return "home";
}
#RequestMapping(value= "/add", method=RequestMethod.POST)
public String addJob(Job job){
jobService.addJob(job);
return "redirect:/";
}
#RequestMapping("/delete/{jobId}")
public String deleteJob(#PathVariable("jobId") Integer jobId){
jobService.removeJob(jobId);
return "redirect:/";
}
#RequestMapping("/edit/{jobId}")
public String editJob(#PathVariable("jobId") Integer jobId,Model model){
model.addAttribute("id",jobId);
return "edit";
}
}
edit.jsp
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# 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>
<head>
<link rel="stylesheet" type="text/css"
href="<c:url value="/resources/css/style.css"/>" />
<link rel="stylesheet"
href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form:form method="post" action="editSuccess" modelAttribute="job"
class="form-horizontal">
<div class="form-group" id="addForm">
<form:label class="control-label" path="title">Title: </form:label>
<form:input class="form-control" path="title" />
<form:label class="control-label" path="description">Description</form:label>
<form:textarea class="form-control" rows="5" path="description" />
<button class="btn btn-success">
<span class="glyphicon glyphicon-plus-sign"></span> Add a Job
</button>
</div>
</form:form>
In editJob method your are returning only id of job with model attribute to edit.jsp. But actually on edit.jsp page you need job object so you need to get job object by id add it as model attribute.
#RequestMapping("/edit/{jobId}")
public String editJob(#PathVariable("jobId") Integer jobId,Model model){
//model.addAttribute("id",jobId); this is wrong
Job job = jobService.getJobById(jobId);
//write method in jobservice to get job by id i.e. getJobById(Integer jobId);
model.addAttribute("job",job)
return "edit";
}

problems taking the value of the select option jsp

I need to take the value of the select option to send it to another page to be processed, but can not capture the value.
any ideas?
the select is loaded from the database, that part works, shows the categories of product.
<%#page import="com.sun.xml.internal.txw2.Document"%>
<%#page import="java.util.ArrayList"%>
<%# page import = "com.seminario.beans.categoria" %>
<%# page import = "com.seminario.datos.DbCategoria" %>
<%# page import = "com.seminario.beans.Producto" %>
<%# page import = "com.seminario.datos.DbProducto" %>
<jsp:useBean id="dataProd" class="com.seminario.datos.DbProducto" scope="page"/>
<jsp:setProperty name="dataProd" property="*"/>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<link href="../stylo.css" rel="stylesheet" type="text/css" media="screen" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Alta Producto</title>
</head>
<%
categoria c = new categoria();
DbCategoria bdc = new DbCategoria();
ArrayList <categoria> myList = new ArrayList();
myList = bdc.SelectAll();
%>
<body>
<h1>Nuevo Producto</h1>
<form name ='formulario' action='nuevoProducto.jsp' method='post' >
Descripcion<input name='descripcion' type='text' size='20' required><br>
Precio<input name='precio' type='text' size='20' required><br>
Stock<input name='stock' type='text' size='20' required><br>
**Categoria <select name="categoid" id="categoid">
<% for(int i=0;i<myList.size();i++){%>
<option value="<%= myList.get(i).getId() %>" > <%out.print(myList.get(i).getDescripcion());%></option>
<%}%>
</select><br>**
Imagen<input name="imagen" text="seleccionar archivo" type="file" size="10" accept="image/jpg" /><br>
<input type ="submit" value ='Guardar' />
<!-- <input type="submit" value="guardar">-->
</form>
<br><br><a href='menuAdmin.jsp'>Volver al menu principal</a>
</body>
</html>

html, jsp ,javascript

I have three jsp GetAllEmployee,EmployeeFindByid,EmployeeFindByName ,now i have to code for EmployeeFindById ,EmployeeFindByName in one jsp, i have provide the button for all three in home page (index.jsp) as the user click on employeeFindbyid new pop window open and demanding for id after click on submit button output should be populate in index.jsp i have done with GetAllEmployeei m stucking in portion of EmployeeFindByid,EmployeeFindByName cause i have to write these in one jsp page as the user click on button one pop window should be open and taking the value then pop window should be closed automatically. I am not able to provide the conditon how to execute particular section of code of one jsp
this is my servlet package com.nousinfo.tutorial;
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;
import com.nousinfo.tutorial.employee.service.model.bo.EmployeeBO;
import com.nousinfo.tutorial.service.bo.EmployeeService;
import com.nousinfo.tutorial.service.bo.impl.EmployeeServiceImpl;
import com.nousinfo.tutorial.service.exception.EmployeeServiceBOException;
import com.nousinfo.tutorial.service.exception.EmployeeServiceException;
/**
* Servlet implementation class GetEmployee
*/
public class GetEmployee extends HttpServlet {
private static final long serialVersionUID = 1L;
EmployeeService employeeService = new EmployeeServiceImpl();
/**
* #see HttpServlet#HttpServlet()
*/
public GetEmployee() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#service(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String name = request.getParameter("findbyid");
System.out.println(name);
RequestDispatcher dispatcher = null;
try {
if (request.getParameter("findbyid") != null) {
request.setAttribute("EmployeeObject", findEmployees(Long
.parseLong(request.getParameter("findbyid"))));
dispatcher = request.getRequestDispatcher("/jsp/employee.jsp");
} else {
request.setAttribute("employeeList", getAllEmployee());
dispatcher = request.getRequestDispatcher("/jsp/winopen.jsp");
}
if (dispatcher != null)
dispatcher.forward(request, response);
} catch (EmployeeServiceBOException e) {
e.printStackTrace();
}
}
private List<EmployeeBO> getAllEmployee() throws EmployeeServiceBOException {
return employeeService.getAllEmployees();
}
private EmployeeBO findEmployees(long id) throws EmployeeServiceBOException {
return employeeService.getEmployee(id);
}
private List<EmployeeBO> findEmployees(String name)
throws EmployeeServiceBOException {
return employeeService.findEmployees(name);
}
}
this is my index.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>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" href="../css/style.css" type="text/css"></link><title>Home</title>
</head>
<body>
<table width="951" height="116" border="0" align="center">
<tr>
<td width="661" height="112" align="center" bgcolor="#99CCFF"><h2>Project Management </h2></td>
<td width="266" height="112" align="center" bgcolor="#FFFFFF"><img src="../image/nous.jpg" alt="1" width="266" height="84" /></td>
</tr>
</table>
<p> </p>
<table width="949" height="183" border="0" align="center">
<tr>
<td height="42" align="center" bgcolor="#3366FF"><strong>Find Employee </strong></td>
</tr>
<tr>
<td height="43"><form id="form2" method="post" action="/EmployeeWeb/GetEmployee">
<input name="Submit2" type="submit" class="button" value="GetAllEmployee"/>
</form> </td>
</tr>
<tr>
<td width="943" height="43">
<input name="Submit" type="submit" value="getEmployee By ID"
onClick="window.open('file.jsp','mywindow','width=500,height=200 align=center,toolbar=no,resizable=yes,menubar=yes' )" />
</td>
</tr>
<tr>
<td height="43">
<input name="Submit2" type="submit" class="button" value="Get Employee By Name" onClick="window.open('winopen.jsp','mywindow','width=500,height=350,toolbar=no,resizable=yes,menubar=yes')"/>
</td>
</tr>
</table>
<p> </p>
</body>
</html>
this is my getAllEmployee.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>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%#page language="java" import="com.nousinfo.tutorial.employee.service.model.bo.*" %>
<%#page language="java" import="java.util.*" %>
<input name="employee id" value="">
<table >
<tr>
<th>EmployeeNumber</th>
<th>FirstName</th>
<th>LastName</th>
<th>Title</th>
<th>Address-1</th>
<th>Address-2</th>
<th>City</th>
<th>State</th>
<th>Pincode</th>
<th>Mobile_Number</th>
<th>Date_Of_Birth</th>
</tr>
<c:forEach var="employee" items="${employeeList}">
<tr>
<td>${employee.empNumber}</td>
<td>${employee.firstName}</td>
<td>${employee.lastName}</td>
<td>${employee.title}</td>
<td>${employee.address1}</td>
<td>${employee.address2}</td>
<td>${employee.city}</td>
<td>${employee.state}</td>
<td>${employee.pincode}</td>
<td>${employee.mobileNUmber}</td>
<td>${employee.dateOfBirth}</td>
</tr>
</c:forEach>
</table>
</body>
</html>

Edit link of a table of each row will send the primary key of the row to controller

Hi i am new in jsp and Spring. I have a table of employee information. I want to add a edit link in each row and an edit link will be click it will send the primary key of the row to the controller. When i click the edit link it display the error "The request sent by the client was syntactically incorrect ()."
This page display the table
employeeList.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Employee List</title>
</head>
<body>
<div align="center">
<h1 align="center">Employee List</h1>
<table align="center" border="1">
<tr><th>Pk</th><th>Employee Name</th><th>Employee email</th><th>Address</th><th>Manager Id</th><th>Edit</th><th>Delete</th></tr>
<c:forEach var="employeeList" items="${list}">
<tr>
<td><c:out value="${employeeList.id}"/></td>
<td><c:out value="${employeeList.name}"/> </td>
<td><c:out value="${employeeList.email}"/> </td>
<td><c:out value="${employeeList.address}"/></td>
<td><c:out value="${employeeList.managerId}"/></td>
<td><a href="editEmployee.htm?id=${id}" >Edit</a></td>
<td><a href="deleteEmployee.htm?id=${id}" >Delete</a></td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
my controller code is
#RequestMapping(value="/editEmployee.htm")
public String editEmployee(#RequestParam("id") int id,ModelMap model){
try {
Employee employee = employeeService.getEmployeeById(id);
model.addAttribute("employee", employee);
return "editEmployee";
} catch (Exception ex) {
return "index";
}
}
editEmployee.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# 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>Registration Page</title>
<style>
.error {
color: #ff0000;
font-style: italic;
}
</style>
</head>
<body>
Edit Employee<br>
</body>
</html>
How i can solve this problem.
Change your jsp to something like this
<c:url var="editUrl" value="/editEmployee.htm" />
<a href="${editUrl}?id=${employeeList.id}">
Edit
</a>
<c:url var="deleteUrl" value="/deleteEmployee.htm" />
<a href="${deleteUrl}?id=${employeeList.id}">
Delete
</a
#RequestMapping(value="/editEmployee.htm") - wrong
#RequestMapping(value="/editEmployee/{id}")
public String editEmployee(#PathVariable int id,ModelMap model){
try {
Employee employee = employeeService.getEmployeeById(id);
model.addAttribute("employee", employee);
return "editEmployee";
} catch (Exception ex) {
return "index";
}
}
and also a href="editEmployee.htm?id=${id}
this should be something like a href="editEmployee/${id}

Categories

Resources