Java Servlet Null attributes [duplicate] - java

This question already has an answer here:
How do I pass current item to Java method by clicking a hyperlink or button in JSP page?
(1 answer)
Closed 2 years ago.
I'm having a problem with my code. I'm making a dealership website. I'm getting a null value for my attribute. My program runs through a foreach loop of my ArrayList on my JSP, I also have buttons on each car to purchase them. When the user chooses purchase on that item its suppose to fetch the car that they chose and forward it to a purchase page. But for some odd reason when I get to the purchase page the car value is null. Any help will be appreciated.
Servlet:
package com.servlets;
import java.io.IOException;
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 javax.servlet.http.HttpSession;
import com.dealership.Car;
import com.dealership.Inventory;
/**
* Servlet implementation class PurchaseServlet
*/
#WebServlet("/PurchaseServlet")
public class PurchaseServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public PurchaseServlet() {
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
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session = request.getSession(true);
Car purchaseCar = (Car)session.getAttribute("purchaseCar");
Inventory inventory = new Inventory();
if(purchaseCar == null) {
purchaseCar = new Car();
}
if (request.getParameter("purchase") != null) {
inventory.test(purchaseCar);
}
session.setAttribute("purchaseCar", purchaseCar);
RequestDispatcher rs = request.getRequestDispatcher("purchase.jsp");
rs.forward(request, response);
}
}
JSP:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<jsp:include page="/HomepageServlet" />
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css"
integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2"
crossorigin="anonymous">
<!-- Local CSS -->
<link rel="stylesheet" href="styles.css" />
<!-- Link to font -->
<link rel="preconnect" href="https://fonts.gstatic.com">
<link
href="https://fonts.googleapis.com/css2?family=Cinzel:wght#600&display=swap"
rel="stylesheet">
<title> Tropical Auto</title>
</head>
<body>
<div>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Nick's Tropical Autocenter</a> <a
class="navbar-brand" href="#"> <img src="mango.svg" width="30"
height="30" alt="" loading="lazy">
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse"
data-target="#navbarNav" aria-controls="navbarNav"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active"><a class="nav-link"
href="index.jsp"> INVENTORY <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item"><a class="nav-link" href="usedcars.jsp">USED
INVENTORY</a></li>
<li class="nav-item"><a class="nav-link" href="specials.jsp">SPECIALS</a>
</li>
<li class="nav-item"><a class="nav-link" href="#">ABOUT US</a>
</li>
</ul>
<form class="d-flex" action="SearchCarsServlet" method="post">
<input class="form-control me-2" type="search" name="searchInput"
placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</nav>
</div>
<div class=album py-5bg-light">
<div class="container">
<div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3">
<c:forEach var="car" items="${inventory.carList}">
<c:if
test="${car.used == false && car.residence < 120 && car.purchased == false}">
<div class="col">
<div class="card" style="width: 18rem;">
<img src=${car.image } class="card-img-top" alt="...">
<div class="card-body">
<p><span class="mandatory">${car.make}${car.model}</span></p>
<p class="card-text">${car.description}
</div>
<div class="d-flex justify-content-center align-items-center">
<form action="PurchaseServlet" method="POST">
<c:set var="purchaseCar" value="${car}" scope="application" />
<button type="submit" name="purchase" class="btn btn-success">Purchase</button>
</form>
<div class="dropdown">
<a class="btn btn-secondary dropdown-toggle" href="#"
role="button" id="dropdownMenuLink" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false"> Details </a>
<div class="dropdown-menu details-button"
aria-labelledby="dropdownMenuLink">
<a class="dropdown-item" href="#">Make: ${car.make}</a> <a
class="dropdown-item" href="#">Model: ${car.model}</a> <a
class="dropdown-item" href="#">Year: ${car.year}</a> <a
class="dropdown-item" href="#">Mileage: ${car.mileage}</a> <a
class="dropdown-item" href="#">Price: $${car.price}</a>
</div>
</div>
</div>
</div>
</div>
</c:if>
</c:forEach>
</div>
</div>
</div>
<!-- Optional JavaScript; choose one of the two! -->
<!-- Option 1: jQuery and Bootstrap Bundle (includes Popper) -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx"
crossorigin="anonymous"></script>
</body>
</html>

It's a lot of code to comprehend but I would say the problem is here:
<foreach>
<form>
<c:set var="purchaseCar" value="${car}" scope="application" />
<submit...
</form>
</foreach>
Session scope will be enough here. But the real problem is this is executed for all records and each is overriding the previous one. So the purchaseCar variable is modified on each iteration.
Usually in a form you want to have <input> tags that sends the needed information with the request to the servlet. Usually that would be the car's ID :)

Related

Java. Thymeleaf. After CRUD operation all .CSS styles on page disappearing

A have simple CRUD web application. And I want to bind UI and backend with thymeleaf. After I create some data and get server response - all styles are disappearing. I'm new to thymeleaf, CSS and HTML. Can someone help me to figure out where is the problem?
Before and after:
Save operation method:
#PostMapping("/user/save")
public ModelAndView save(#ModelAttribute("userDTO") #Valid UserDTO userDTO,
BindingResult bindingResult, WebRequest request, Errors errors) {
User registered = new User();
if (!bindingResult.hasErrors()) {
registered = createUserAccount(userDTO, bindingResult);
}
if (registered == null) {
bindingResult.rejectValue("email", "message.regError");
}
if (bindingResult.hasErrors()) {
bindingResult.getAllErrors().forEach(error -> log.error(error.toString()));
return new ModelAndView("authorization/registration", "error", bindingResult.getAllErrors());
} else {
return new ModelAndView("users", "user", userDTO);
}
}
registration.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>User Registration</title>
<div th:replace="fragments/css_fragments :: css_background_layer"></div>
</head>
<body>
<div style="text-align:center">
<div th:replace="fragments/menu_fragments :: header_menu"></div>
</div>
<div style="margin: 0 auto; width: 20%; padding-top: 18%;">
<div class="registration-form">
<!--/*#thymesVar id="userDTO" type="com.socnetw.socnetw.model.UserDTO"*/-->
<form id="form" method="post" action="/user/save" th:object="${userDTO}">
<label>
<input name="username" placeholder="Username" required="required" th:field="*{username}"
type="text">
</label>
<ul>
<li th:each="err : ${#fields.errors('username')}" th:text="${err}"></li>
</ul>
<label>
<input name="realName" placeholder="Real Name"
type="text" th:field="*{realName}">
</label>
<ul>
<li th:each="err : ${#fields.errors('realName')}" th:text="${err}"></li>
</ul>
<span></span><br>
<label>
<input name="email" placeholder="Email" required="required" th:field="*{email}"
type="email">
</label>
<ul>
<li th:each="err : ${#fields.errors('email')}" th:text="${err}"></li>
</ul>
<label>
<input name="phoneNumber" placeholder="Phone Number" required="required" th:field="*{phoneNumber}"
type="tel">
</label>
<ul>
<li th:each="err : ${#fields.errors('phoneNumber')}" th:text="${err}"></li>
</ul>
<span></span><br>
<label>
<input name="password" placeholder="Password" th:field="*{password}"
required="required" type="password">
</label>
<ul>
<li th:each="err : ${#fields.errors('password')}" th:text="${err}"></li>
</ul>
<label>
<input name="passwordMatcher" placeholder="Repeat password" th:field="*{matchingPassword}"
required="required" type="password">
</label>
<ul>
<li th:each="err : ${#fields.errors('matchingPassword')}" th:text="${err}"></li>
</ul>
<span></span><br>
<button type="submit" style="margin-top: 20px">Register</button>
</form>
</div>
</div>
</body>
</html>
css fragment
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/html">
<div th:fragment="css_background_layer">
<link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css"
rel="stylesheet"
th:href="#{'https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css'}"
type="text/css">
<link href="css/style.css" rel="stylesheet"
th:href="#{css/style.css}"
type="text/css">
<div class="overlay"></div>
</div>
</html>
You need to use an absolute url to your css, rather than a relative one. When you go to /user/save it's looking for /user/save/css/style.css -- which probably doesn't exist.
th:href="#{/css/style.css}"

How the Spring maps url from a jsp to its respective controller?

I am working on a Spring web project , I have many JSP files and many controllers , but I am not able to grab how this
<form:form action="updateCustomer" autocomplete="true" commandName="customer">
form is automatically mapped to the respective controller in which the updateCustomer is defined. There are other controllers also but how exactly the url updateCustomer goes to respective controller.
The Customer.jsp file is as follows :
<%# 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 prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html>
<html lang="en">
<head>
<link
href="${pageContext.request.contextPath}/static/css/bootstrap-nav-wizard.css"
rel="stylesheet">
<link
href="${pageContext.request.contextPath}/static/css/intlTelInput.css"
rel="stylesheet">
<style>
ul.nav-wizard li a i {
margin-right: 15px;
}
</style>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="${pageContext.request.contextPath}/static/js/flickity.pkgd.min.js"></script>
<script src="${pageContext.request.contextPath}/static/js/jquery.fancybox.pack.js"></script>
<script src="${pageContext.request.contextPath}/static/js/waypoints.min.js"></script>
<script src="${pageContext.request.contextPath}/static/js/custom/customer.js"></script>
<script src="${pageContext.request.contextPath}/static/js/jqueryform-validator.js"></script>
<script src="${pageContext.request.contextPath}/static/js/custom/common.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/intlTelInput.min.js"></script>
</head>
<body>
<form:form action="updateCustomer" autocomplete="true" commandName="customer">
<form:hidden path="buyerId"/>
<form:hidden path="user.userId" />
<section>
<div class="container" style="margin-top: 10px;">
<div class="row">
<h3 class="main-title">My Profile</h3>
</div>
<div class="row">
<div>
<!-- Main Content Start -->
<div id="myTabContent" class="tab-content">
<!-- Step 1 Content Start -->
<div class="tab-pane fade active in" id="step1">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Personal Details</h3>
</div>
<div class="panel-body">
<div class="row">
<div class="col-xs-12 col-sm-4 form-group">
<label>First Name</label><span class="req">*</span>
<form:input class="form-control" path="user.firstName"
type="text" maxlength="75"
/>
</div>
<div class="col-xs-12 col-sm-4 form-group">
<label>Middle Name</label>
<form:input class="form-control" path="user.middleName" maxlength="75"
type="text" />
</div>
<div class="col-xs-12 col-sm-4 form-group">
<label>Last Name</label><span class="req">*</span>
<form:input class="form-control" path="user.lastName"
type="text" maxlength="75"
/>
</div>
</div>
</div><!--//panel body over -->
</div><!--//panel panel default over -->
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Company Details</h3>
</div>
<div class="panel-body">
<div class="row">
<div class="col-xs-12 col-sm-6 form-group">
<label>Company Name</label><span class="req">*</span>
<form:input path="companyName" class="form-control"
type="text"
maxlength="45"
/>
</div>
</div>
</div>
</div>
</div>
<div class="row" style="display: none;" id="mainBtn">
<div class="col-xs-6 col-sm-2 pull-right" style="min-width: 170px;">
<button class="btn" type="submit" name="action" value="2" style= "min-width: 170px;">Save & Continue</button>
</div>
<div class="col-xs-6 col-sm-2 pull-right" style="text-align: right; padding-right:0px;"> <!-- added property padding-right:0px; to style on 17/7 -->
<button class="btn" type="submit" name="action" value="1" style= "min-width: 170px;">Save</button>
</div>
</div>
<div class="row" id="editBtn">
<div class="col-xs-6 col-sm-2 pull-right">
<a class="btn pull-right" id="edit"
href="#" onclick="makeEditable()" style="min-width: 170px;">Edit</a>
</div>
</div>
<br> <br>
</div>
<!-- Step 1 Content End -->
</div>
<!-- Main Content End -->
</div>
</div>
</div>
<!-- /container -->
</section>
</form:form>
</body>
</html>
The controller File is as follows :
package com.htss.web.controller;
//assume all imports
#Controller
#RequestMapping("/buyer")
public class BuyerController {
#Autowired
private BuyerService customerService;
#Autowired
private UserService userService;
#Autowired
private CommonService commonService;
#Autowired
private MessageSource messageSource;
#RequestMapping(value = "/open/customer")
public String customerInfo() {
return "customer";
}
#RequestMapping(value = "/edit_profile")
public String editCustomerProfile(HttpSession session, Model model) {
Integer buyerId = (Integer) session.getAttribute("entityId");
BuyerFormBean bean = customerService.retrieveCustomer(buyerId);
Long userId = (Long) session.getAttribute("userId");
try {
UserFormBean user = userService.getUser(userId);
bean.setUser(user);
} catch (IllegalAccessException | InvocationTargetException e) {
}
model.addAttribute("customer", bean);
model.addAttribute("countries", commonService.getCountryDropdown());
model.addAttribute("action", "updateCustomer");
return "buyerProfile";
}
#RequestMapping(value = "/updateCustomer")
public String updateCustomerProfile(Model model, HttpSession session, BuyerFormBean customer) {
try {
if (action == 1 || action == 2) {
customer = customerService.modifyCustomer(customer);
}
}
catch (Exception e) {
e.printStackTrace();
model.addAttribute("error",messageSource.getMessage("msg.Error",null,Locale.US));
}
Integer buyerId = (Integer) session.getAttribute("entityId");
BuyerFormBean bean = customerService.retrieveCustomer(buyerId);
Long userId = (Long) session.getAttribute("userId");
try {
UserFormBean user = userService.getUser(userId);
bean.setUser(user);
} catch (IllegalAccessException | InvocationTargetException e) {
}
model.addAttribute("customer", bean);
model.addAttribute("message",messageSource.getMessage("msg.Success",null,Locale.US));
return "Customer";
}
}
Now the question is when I click save button the url formed is :
http://localhost:8080/82ism/buyer/updateCustomer
How this happened ? and now when I need a button to some other controller I need to give the whole URL as follows :
${pageContext.request.contextPath}/seller/edit_profile
The project is working all fine I am just trying to understand this concept.
The whole point of spring is so you don't have to worry about that stuff.
jsp's get found cause of the propperty's in application.propperties:
like:
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
For the forms and methods... It's not like it magicly happens.
A form you have to cal by name and methods are eighter mapped to a url or action
like:
#RequestMapping("/")
or
#RequestMapping(method=RequestMethod.POST)
To call the values of a form from the controller you first have to bind them to a entity model with the fields of the form as variables.
The method would look like:
#RequestMapping(method = RequestMethod.POST)
public String processRegister(#ModelAttribute("userForm") User user,
Map<String, Object> model) {
...
return "view";
}

Getting blank page JSP load

I'm having a problem that when my JSP loads, it returns a blank page. The page is supposed to call the Controller with the parameter "btnListar" and call de DAO to list entries from the database. I debugged the code (I'm using NetBeans to build this app), and the values are being passed correctly, the variables are filled with entries from the DB that the DAO gets, but the page the browser is supposed to show just doesn't appear, it's blank.
My Controller:
public class ExperienciaControle extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String action = request.getParameter("action");
switch (action) {
case "btnCadastrar": {
Experiencia exp = new Experiencia();
exp.setEmpresa(request.getParameter("txtEmpresa"));
exp.setCargo(request.getParameter("txtCargo"));
exp.setData(request.getParameter("txtData"));
exp.setAtribuicoes(request.getParameter("txtAtrib"));
ExperienciaDAO dao = new ExperienciaDAO();
dao.insertExp(exp);
break;
}
case "btnAtualizar": {
Experiencia exp = new Experiencia();
exp.setEmpresa(request.getParameter("txtEmpresa"));
exp.setCargo(request.getParameter("txtCargo"));
exp.setData(request.getParameter("txtData"));
exp.setAtribuicoes(request.getParameter("txtAtrib"));
ExperienciaDAO dao = new ExperienciaDAO();
dao.updateExp(exp);
break;
}
case "btnRemover": {
Experiencia exp = new Experiencia();
exp.setId(Integer.parseInt(request.getParameter("chckId")));
ExperienciaDAO dao = new ExperienciaDAO();
dao.deleteExp(exp);
break;
}
case "btnListar": {
ExperienciaDAO dao = new ExperienciaDAO();
ArrayList<Experiencia> expArray = dao.selectExp();
request.setAttribute("expArray", expArray);
break;
}
default:
break;
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}
}
My JSP:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# page import="java.util.*" %>
<%# page import="Modelo.*" %>
<!DOCTYPE html>
<html>
<head>
<script src="../js/dropdown.js"></script>
<script src="../js/jquery-1.12.3.min.js"></script>
<script src="../js/lista.js"></script>
<link type="text/css" rel="stylesheet" href="../css/bootstrap.css" />
<link type="text/css" rel="stylesheet" href="../css/admin.css" />
<link type="text/css" rel="stylesheet" href="../css/dropdown.css" />
<link type="text/css" rel="stylesheet" href="../css/body.css" />
<link type="text/css" rel="stylesheet" href="../css/main.css" />
<link type="text/css" rel="stylesheet" href="../css/fonts.css" />
<title>Currículo | Administração</title>
</head>
<body>
<div class="body">
<div>
<nav id="primary_nav_wrap">
<ul>
<li class="current-menu-item">Home</li>
<li><a>Experiência</a>
<ul>
<li>Adicionar</li>
<li>Listar</li>
</ul>
</li>
<li><a>Educação</a>
<ul>
<li>Adicionar</li>
<li>Atualizar</li>
<li>Remover</li>
</ul>
</li>
<li><a>Habilidade</a>
<ul>
<li>Adicionar</li>
<li>Atualizar</li>
<li>Remover</li>
</ul>
</li>
</ul>
</nav>
</div>
<div id="divAddExp" style="display:none" class="cadastros">
<form name="frmExp" action="../ExperienciaControle" method="POST">
<h1 style="font-family: Roboto">Cadastro de Experiência</h1><br />
<label for="lblEmpresa">Empresa </label><input type="text" name="txtEmpresa" class="form-control" /><br />
<label for="lblCargo">Cargo </label><input type="text" name="txtCargo" class="form-control" /><br />
<label for="lblData">Data </label><input type="text" name="txtData" class="form-control" /><br />
<label for="lblAtrib">Atribuições </label><textarea rows="4" cols="50" name="txtAtrib" class="form-control"></textarea><br />
<input class="btn" type="submit" name="btnCadastrar" value="Cadastrar" />
</form>
</div>
<div id="divUpdExp" class="cadastros">
<form name="frmExp" action="/ExperienciaControle" method="GET">
<h1 style="font-family: Roboto">Listagem de Experiência</h1><br />
<table>
<thead>
<tr>
<th> </th>
<th>ID</th>
<th>Empresa</th>
<th>Cargo</th>
</tr>
</thead>
<%
request.getRequestDispatcher("/ExperienciaControle?action=btnListar").forward(request, response);
ArrayList<Experiencia> expArray = (ArrayList<Experiencia>) request.getAttribute("expArray");
for (Experiencia exp : expArray) {
%>
<tr>
<td><input type="checkbox" name="chckID" value="<%= exp.getId()%>" /></td>
<td><%= exp.getId()%></td>
<td><%= exp.getEmpresa()%></td>
<td><%= exp.getCargo()%></td>
</tr>
<%
}
%>
</table>
<span><input class="btn" type="submit" name="btnListar" value="Listar" /></span>
<span><input class="btn" type="submit" name="btnAtualizar" value="Atualizar" /></span>
<span><input class="btn" type="submit" name="btnRemover" value="Remover" /></span>
</form>
</div>
</div>
</body>
</html>
If I remove the Java code from the JSP and turn it into a pure HTML page, it works perfectly, the page comes up without any problems. Tomcat (and Glassfish) log shows no error messages, which makes things even harder. :(
What am I doing wrong here? Why am I getting a blank page?
COMPLETE CODE: http://gitlab.creationkit.com.br/thales/Curriculum

HTTP Status 405 - Request method 'GET' not supported

I want to add payments to my clients database but when I add the payments I got this error "GET NOT SUPPORTED" I don't know what's the problem. Can you guys help me?
#Controller
public class PaymentsController {
#Autowired
private UsersService usersService;
#Autowired
private PaymentsService paymentsService;
#RequestMapping(value = "/addPayments", method = RequestMethod.POST)
public String addPayments(HttpServletRequest request, ModelMap map) {
String user = request.getParameter("userId"); // this is the identifier for the user of this payment
String transactName = request.getParameter("transactName");
String paid = request.getParameter("paid");
String unpaid = request.getParameter("unpaid");
String balance = request.getParameter("balance");
String total = request.getParameter("total");
//.... get all other attributes you've passed from the form through request.getParameter("");
//next, check whether or not a user with the userId from the screen exists in the db
Users userObject = usersService.getUsers(user);
//.getUsersByUserId(user);
if (userObject != null) {
// this means that we have a valid user to insert the payment to
UsersPayments payment = new UsersPayments();
payment.setUsers(userObject);
payment.setTransactName(transactName);
payment.setPaid(paid);
payment.setUnpaid(unpaid);
payment.setBalance(balance);
payment.setTotal(total);
//.... set the other properties of UsersPayment object
paymentsService.addPayments(payment);
}
else {
// you have an error right here
}
map.put("paymentsList", paymentsService.getAllPayments());
return "payments";
}
}
payments.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"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# include file="/WEB-INF/jsp/includes.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link href="<c:url value="/resources/css/design.css" />" rel="stylesheet">
<link href="<c:url value="/resources/css/customized.css" />" rel="stylesheet">
<link href="<c:url value="/resources/css/bootstrap.css" />" rel="stylesheet">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Canadian Immigration Consultancy</title>
</head>
<body>
<div id="wrapper">
<div id="logo">
<img src="<c:url value="/resources/images/logo4.png" />" height="200px" width="230px"/>
<img src="<c:url value="/resources/images/header06.jpg" />" height="200px" width="765px"/>
</div>
<div class="red">
<div align="center" id="slatenav">
<ul>
<li>Home</li>
<li>View All</li>
<li>Reports</li>
<li>Add Leads</li>
<li><spring:message code="user.logout"/></li>
</ul>
</div>
</div>
<div id="balance" >
<form action="addPayments" method="POST">
<div class="well well-sm box16">
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title">Payments</h3>
</div>
<div class="panel-body">
<div class="form-group">
<br><div class="col-sm-2 control-label">Transaction Name</div>
<div class="col-sm-10">
<input type="text" class="form-control" name="transactName" autofocus />
</div>
</div>
<div class="form-group">
<br><div class="col-sm-2 control-label">Amount Paid</div>
<div class="col-sm-10">
<input type="text" class="form-control" name="paid" />
</div>
</div>
<div class="form-group">
<br><div class="col-sm-2 control-label">Unpaid</div>
<div class="col-sm-10">
<input type="text" class="form-control" name="unpaid" />
</div>
</div>
<div class="form-group">
<br><div class="col-sm-2 control-label">Total Balance</div>
<div class="col-sm-10">
<input type="text" class="form-control" name="balance" />
</div>
</div>
<div class="form-group">
<br><div class="col-sm-2 control-label">Total Amount</div>
<div class="col-sm-10">
<input type="text" class="form-control" name="total" />
</div>
</div>
<div class="save">
<input type="submit" class="btn btn-success" value="Save" />
</div>
</form>
</div>
</div>
</div>
</body>
</html>
You only seem to have one handler mapping, and it's POST. Add another handler mapping for the same url path with GET. Consider the "POST Redirect GET" pattern as well.

Control over where a form display the output from your submission

In my web application, I have a home page where the options available to the user are placed in a fixed sidebar in the top of the screen, and each one of this options are opened inside of a tag <div> in this same page.
My problem is: when this content is a form, and I submit it to the server, after the processing, the output page isn't opened in this <div>, but in the entire navigation space. What I want is a way of capture this return and display it in the same <div> it was originated.
the code for my home page is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="../../assets/ico/favicon.ico">
<title>HorarioLivre</title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="navbar-fixed-top.css" rel="stylesheet">
<!-- Just for debugging purposes. Don't actually copy this line! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body onload="close_page()">
<!-- Fixed navbar -->
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">HorarioLivre</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>Evento</li>
<li>Lista Horarios</li>
<li>Cadastra Horarios</li>
<li>Usuarios</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
${usuario.nome} <b class="caret"></b>
<ul class="dropdown-menu">
<li>Perfil</li>
<li>Configurações</li>
<li>Sair</li>
</ul>
</li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
<div class="container">
<div class="page-header">
<h1></h1>
</div>
<div class="panel panel-default" id="results">
<div class="panel-heading">
<div align="right"><button type="button" class="btn btn-lg btn-danger" onclick="close_page()">Fechar</button></div>
</div>
<div class="panel-body" id="content">
Panel content
</div>
</div>
</div> <!-- /container -->
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
function load_page(url){
$('#results').css("display", "block");
$('#content').load(url);
$('#container').draggable();
}
function close_page(){
$('#results').css("display", "none");
$('#content').empty();
}
</script>
</body>
</html>
I am using Spring, and the pages linked here are handled by Controller. By example,the page "cadastra_evento.html" is:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Lista de Eventos</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="alert alert-info">
<strong>Eventos</strong> Segue a lista de eventos cadastrados.
</div>
<div class="container">
<div class="row">
<div class="col-md-3">Nome</div>
<div class="col-md-3">Descrição</div>
<div class="col-md-3">Periodo</div>
<div class="col-md-3">Duração</div>
</div>
<c:forEach var="item" items="${lista}">
<div class="row">
<div class="col-md-3"><c:out value="${item.nome}"/></div>
<div class="col-md-3"><c:out value="${item.descricao}"/></div>
<div class="col-md-3"><c:out value="${item.data_inicial}"/> - <c:out value="${item.data_final}"/></div>
<div class="col-md-3"><c:out value="${item.duracao}"/></div>
</div>
</c:forEach>
</div>
<div class="alert alert-info">
<strong>Novo</strong> Cadastre um novo evento.
</div>
<form method="post" action="cad_evento.html">
<input type="text" name="nome" placeholder="Nome" size=20 maxlength=40> <br/>
<input type="text" name="descricao" placeholder="Descrição" size=30 maxlength=100> <br/>
<h3>Periodo da Data</h3>
inicio: <input name="data_inicial" placeholder="DD-MM-AAAA" required pattern="\d{2}-\d{2}-\d{4}" /> <br/>
final: <input name="data_final" placeholder="DD-MM-AAAA" required pattern="\d{2}-\d{2}-\d{4}" /> <br/>
<h3>Periodo do Horário</h3>
inicio: <input name="hora_inicial" placeholder="HH:MM:SS" required pattern="\d{2}:\d{2}:\d{2}" /> <br/>
final: <input name="hora_final" placeholder="HH:MM:SS" required pattern="\d{2}:\d{2}:\d{2}" /> <br/>
<input type="text" name="duracao" placeholder="duração" size=20 maxlength=2> <br/>
<button type="submit" class="btn btn-lg btn-primary">Cadastrar</button>
</form>
</body>
</html>
To finish, the page "cad_evento.html" used as action for the form above, is handled by method of same name from Controller:
#RequestMapping(value="/cad_evento", method=RequestMethod.POST)
public ModelAndView cadastra_evento(#RequestParam("nome") String nome, #RequestParam("descricao") String descricao, #RequestParam("data_inicial") String data_inicial, #RequestParam("hora_inicial") String hora_inicial, #RequestParam("data_final") String data_final, #RequestParam("hora_final") String hora_final, #RequestParam("duracao") int duracao) {
if(sessao != null)
{
if(sessao.getUsuario().temAutorizacao("cad_evento"))
{
Date d_inicio = new Date(Date.parse(data_inicial));
Date d_final = new Date(Date.parse(data_final));
Time h_inicio = new Time(Time.parse(hora_inicial));
Time h_final = new Time(Time.parse(hora_final));
EventoDAO evento = new EventoDAO(nome, descricao, d_inicio, d_final, h_inicio, h_final, duracao, sessao.getUsuario());
int saida = evento.cadastra();
if(saida == 0)
{
ModelAndView mav = new ModelAndView();
mav.addObject("message", "Erro ao cadastrar o evento");
return mav;
}
else
{
ModelAndView mav = new ModelAndView();
mav.setViewName("/listagem_evento");
return mav;
}
}
else
{
ModelAndView mav = new ModelAndView();
mav.addObject("message", "Usuário sem permissão de acesso");
return mav;
}
}
else
{
ModelAndView mav = new ModelAndView();
mav.setViewName("/usuario_login_page");
return mav;
}
}
Someone have any thoughts about how to do that?
Well, spring mvc just open new page with a content you set in ModelAndView. If you want to load somthing just in some part of page ( in this case ) there pure javascript / jquery ajax is needed. So steps needed here:
Add javascript which will do ajax request to controller
Controller need to return JSON ( #ResponseBody can help you )
You have to do some DOM manipulation using javascript/jquery to put JSON answer to your div.

Categories

Resources