I don't understand how to access form data within the JSP page inside my Action class
login.jsp:
<div class="well">
<form id="loginForm" method="POST" action="hr/login/" novalidate="novalidate">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon" id="UserEmail"><i class="fa fa-user" title="Enter Your username"></i></span>
<input type="text" class="form-control" id="username" name="username" value="" required title="Please enter you username" placeholder="Enter Username" />
</div>
<span class="help-block"></span>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon" id="UserPasswordMatch"><i class="fa fa-lock" title="Choose password"></i></span>
<input type="password" class="form-control" id="passwordmatch" name="passwordmatch" value="" required title="Enter your password" placeholder="Enter Password" />
</div>
</div>
<button type="submit" class="btn btn-success btn-block">Login</button>
</form>
</div>
BookingAction.java:
public class BookingAction {
private String name;
HotelReservationServceImpl service = new HotelReservationServceImpl();
public String execute() throws Exception {
return "success";
}
public String loginExecute()
{
return "success";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I also have a User class with private attributes which include username and password with getters and setters.
service.java:
public class HotelReservationServceImpl implements IHotelReservationService {
HotelReservationDAOImpl dbcon = new HotelReservationDAOImpl();
#Override
public int login(String username, String passwrd) {
if(username.isEmpty() || passwrd.isEmpty())
{
System.out.print(" Enter username and password ");
}
else
{
int i = dbcon.login(username, passwrd);
}
//dbcon.dbConnector();
return 0;
}
}
struts.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="helloworld" extends="struts-default">
<action name="hello"
class="com.reservation.action.BookingAction"
method="execute">
<result name="success">/HelloWorld.jsp</result>
</action>
<action name="login"
class="com.reservation.action.BookingAction"
method="loginExecute">
<result name="success">/HelloWorld.jsp</result>
</action>
</package>
</struts>
Use Struts tags to bind the form to the action and input fields to action properties.
<%# taglib prefix="s" uri="/struts-tags" %>
<s:form id="loginForm" method="POST" action="login" novalidate="novalidate">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon" id="UserEmail"><i class="fa fa-user" title="Enter Your username"></i></span>
<s:textfield cssClass="form-control" id="username" name="user.username" value="" required title="Please enter you username" placeholder="Enter Username" />
</div>
<span class="help-block"></span>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon" id="UserPasswordMatch"><i class="fa fa-lock" title="Choose password"></i></span>
<s:password cssClass="form-control" id="passwordmatch" name="user.password" value="" required title="Enter your password" placeholder="Enter Password" />
</div>
</div>
<button type="submit" class="btn btn-success btn-block">Login</button>
</s:form>
To bind the form you should set the action name to the form tag. To bind input fields you should set property names to the struts input tags.
The properties are in the User bean that you should aggregate to the action class.
private User user;
public User getUser() { return user; }
public void setUser(User user) { this.user = user; }
If you don't want to generate extra HTML to the page use
<constant name="struts.ui.theme" value="simple"/>
Related
I have a SpringBoot app. with this thymelaf template, that works fine when submitting:
<div class="form-group required-control">
<label for="gre">GRE</label>
<input id="gre" type="checkbox" name="gre" th:checked="*{gre}" th:onclick="submit()" />
</div>
but when I add another checkbox, It always take in account the first one, regardless which one I click
<div class="form-group required-control">
<label for="gre">GRE</label>
<input id="gre" type="checkbox" name="gre" th:checked="*{gre}" th:onclick="submit()" />
<label for="gre2">GRE2</label>
<input id="gre2" type="checkbox" name="gre2" th:checked="*{gre2}" th:onclick="submit()" />
</div>
There is no technical problem here. I think there is a problem with your submit() function, because I created a normal form and tried your same instance, and all selection combinations worked correctly.
I am adding the entity, controller and html files respectively for example.
public class Example {
private boolean gre;
private boolean gre2;
public Example() {
}
// getter/setter ...
}
#Controller
#RequestMapping("/example")
public class ExampleController {
#GetMapping("/create")
public String createExample(Model model) {
model.addAttribute("example", new Example());
return "example-form";
}
#PostMapping("/insert")
public String insertExample(Model model, Example example) {
model.addAttribute("example", example);
return "example-form";
}
}
<!DOCTYPE HTML>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<div>
<form action="/example/insert" method="post" th:object="${example}">
<div class="form-group required-control">
<label for="gre">GRE</label>
<input id="gre" type="checkbox" name="gre" th:checked="*{gre}" />
<label for="gre2">GRE 2</label>
<input id="gre2" type="checkbox" name="gre2" th:checked="*{gre2}" />
</div>
<button type="submit">Submit Form</button>
</form>
</div>
</body>
</html>
If you don't want to add an attribute into the Model, you can receive checkbox condition via HttpServletRequest.
#GetMapping("/create")
public String createExample() {
return "example-form";
}
#PostMapping("/insert")
public String insertExample(User user, HttpServletRequest request) {
user.setGre(request.getParameter("gre") != null);
user.setGre2(request.getParameter("gre2") != null);
userServiceImp.updateUser(editedUser); //for example updating user in database
return "/";
}
HTML will be like this:
<form th:action="/insert" method="post">
<div class="form-group required-control">
<label>GRE</label>
<input type="checkbox" name="gre"/>
<label>GRE 2</label>
<input type="checkbox" name="gre2"/>
</div>
<button type="submit">Submit Form</button>
</form>
I have a question, I didn't understand why this part of the code(where is registration) Spring doesn't find even if I wrote an url. But the same code in another part, for example, add a new book or add the new author of the book is working correctly it added everything into the database and send me into another page. But if I register the person and click submit it always shows me 400 - bad request error. Please help me. What I wrote wrong?
This is my controller(doesn't work registration part with register book (not redirect to registerbook and doesn't add data into DB)):
#Controller
public class HelloController {
private static final Logger logger = Logger.getLogger(HelloController.class.getName());
#Autowired
#Qualifier("author")
private AuthorzDAO authorzDAO;
#Autowired
#Qualifier("book")
private BooksDAO booksDAO;
#Autowired
#Qualifier("borrow")
private BorrowsDAO borrowsDAO;
#Autowired
#Qualifier("person")
private PersonDAO personDAO;
#RequestMapping(value = "/",method = RequestMethod.GET)
public ModelAndView printHello() {
return new ModelAndView("hello", "command", new LoginPerson());
}
#RequestMapping(value = "/",method = RequestMethod.POST)
public String login(#ModelAttribute("SpringWeb")LoginPerson person, ModelMap model, HttpServletRequest request) {
model.addAttribute("info", personDAO.getInfromStudent(person.getEmail(), person.getPassword()));
model.addAttribute("takenbook", person.getEmail());
if (person.getEmail().equals("admin#admin.com") && person.getPassword().equals("admin")) {
logger.warning("AAAAA");
logger.warning(person.getEmail());
return "admin";
} else if(personDAO.checkPerson(person.getEmail(), person.getPassword()) == true){
logger.warning(personDAO.checkPerson(person.getEmail(), person.getPassword()).toString());
logger.warning("BBBBB");
logger.warning(person.getPassword());
return "personinfo";
} else {
return new ResponseStatusException().error();
}
}
#RequestMapping(value = "/registration", method = RequestMethod.GET)
public ModelAndView registration() {
return new ModelAndView("registration", "person", new Person());
}
#RequestMapping(value = "/registration", method = RequestMethod.POST)
public String register(#ModelAttribute("person") Person person) {
logger.warning("Hello");
logger.warning(person.toString());
personDAO.connectPerson(person);
return "redirect:/registerbook";
}
#RequestMapping(value = "/registerbook", method = RequestMethod.GET)
public ModelAndView registerbook() {
//model.addAttribute("newborrow", new Borrows());
return new ModelAndView("registerbook", "newborrow", new Borrows());
}
#RequestMapping(value = "/registerbook", method = RequestMethod.POST)
public String regbook(#ModelAttribute("newborrow") Borrows borrows, ModelMap model) {
logger.warning(String.valueOf(borrows.getId()));
model.addAttribute("borrowid", borrows.getId());
model.addAttribute("personid", borrows.getStudentid());
model.addAttribute("bookid", borrows.getBookid());
Date today = new Date();
Calendar cal = new GregorianCalendar();
cal.setTime(today);
cal.add(Calendar.DAY_OF_MONTH, -30);
Date today30 = cal.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Timestamp todays30 = Timestamp.valueOf(dateFormat.format(today30));
Timestamp todayy = Timestamp.valueOf(dateFormat.format(today));
borrows.setTakendate(todayy);
borrows.setBroughtdate(todays30);
borrowsDAO.insertBorrow(borrows);
return "hello";
}
#RequestMapping(value = "/addauth", method = RequestMethod.GET)
public ModelAndView addauth() {
return new ModelAndView("addauthbooks", "adding", new Authorz());
}
#RequestMapping(value = "/example", method = RequestMethod.POST)
public String addingauthor(#ModelAttribute Authorz authorz, ModelMap model) {
model.addAttribute("id_author", authorz.getAuthorid());
model.addAttribute("fname_author", authorz.getName());
model.addAttribute("lname_author", authorz.getSurname());
logger.warning(String.valueOf(authorz.getAuthorid()));
logger.warning(authorz.getName());
logger.warning(authorz.getSurname());
authorzDAO.insertAuthorz(authorz);
return "example";
}
#RequestMapping(value = "/addbooks", method = RequestMethod.GET)
public ModelAndView addbook() {
return new ModelAndView("addbook", "addingbook", new Books());
}
#RequestMapping(value = "/admin", method = RequestMethod.POST)
public String addingbook(#ModelAttribute Books books, ModelMap model) {
model.addAttribute("id", books.getId());
model.addAttribute("name", books.getName());
model.addAttribute("pagecount", books.getPagecount());
model.addAttribute("point", books.getPoint());
model.addAttribute("authorid", books.getAuthorid());
model.addAttribute("typeid", books.getTypeid());
model.addAttribute("fragment", books.getFragment());
logger.warning(String.valueOf(books.getId()));
logger.warning(books.getName());
logger.warning(String.valueOf(books.getPagecount()));
booksDAO.insertBook(books);
return "admin";
}
#RequestMapping(value = "/deleteauth", method = RequestMethod.GET)
public ModelAndView deleteauthbooks() {
return new ModelAndView("deleteauthbooks", "deletingauthor", new Authorz());
}
#RequestMapping(value = "/admins", method = RequestMethod.POST)
public String deleteresult(#ModelAttribute Authorz authorz, ModelMap model) {
model.addAttribute("id", authorz.getAuthorid());
model.addAttribute("name", authorz.getName());
model.addAttribute("surname", authorz.getSurname());
authorzDAO.delete_book(authorz.getSurname());
return "admin";
}
#RequestMapping(value = "/deletebooks", method = RequestMethod.GET)
public ModelAndView deletebook() {
return new ModelAndView("deletebooks", "deletingbook", new Books());
}
#RequestMapping(value = "/nadmin", method = RequestMethod.POST)
public String deletebookresult(#ModelAttribute Books books, ModelMap model) {
model.addAttribute("id", books.getId());
model.addAttribute("name", books.getName());
model.addAttribute("pagecount", books.getPagecount());
model.addAttribute("point", books.getPoint());
model.addAttribute("authid", books.getAuthorid());
model.addAttribute("typeid", books.getTypeid());
booksDAO.delete_book(books.getName());
return "admin";
}
#RequestMapping(value = "/borrow", method = RequestMethod.GET)
public ModelAndView borrows() {
return new ModelAndView("borrow", "borrowing", new LoginPerson());
}
#RequestMapping(value = "/res", method = RequestMethod.POST)
public String borrow(#ModelAttribute LoginPerson borrows, ModelMap model) {
logger.warning(borrows.getEmail());
List list_borrows = personDAO.searchStudent(borrows.getEmail());
logger.warning(list_borrows.toString());
model.addAttribute("borrow", list_borrows);
return "result";
}
#RequestMapping(value = "/changebook", method = RequestMethod.GET)
public ModelAndView change() {
return new ModelAndView("changebook", "changing", new Person());
}
#RequestMapping(value = "/changebook", method = RequestMethod.POST)
public String changebook(#ModelAttribute("changebook") Person point, ModelMap model, HttpServletRequest request) {
model.addAttribute("point", point.getPoint());
model.addAttribute("email", point.getEmail());
logger.warning("Upper");
logger.warning(String.valueOf(point.getPoint()));
logger.warning(point.getEmail());
logger.warning(request.getParameter("email"));
if(point.getPoint() != null && request.getParameter("email") != null) {
logger.warning("It works!!!");
personDAO.changeBook(point.getPoint(), request.getParameter("email"));
}
logger.warning("Down");
return "changebook";
}
}
This is my jsp of registration:
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: lado
Date: 2019-05-19
Time: 17:48
To change this template use File | Settings | File Templates.
--%>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Registration</title>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<center><h2>Person Information</h2></center>
<%--<form:form method = "post" action = "/springlab_war_exploded/admin" modelAttribute="person">--%>
<form:form method ="post" modelAttribute="person">
<fieldset>
<center>
<div id="legend">
<legend class="">Registration</legend>
</div>
</center>
<center>
<div class="control-group">
<!-- id -->
<label class="control-label" for="id">Id:</label>
<div class="controls">
<input type="number" id="id" name="id" placeholder="" class="input-xlarge">
<p class="help-block">Id can contain only numbers</p>
</div>
</div>
<div class="control-group">
<!-- name -->
<label class="control-label" for="name">First name:</label>
<div class="controls">
<input type="text" id="name" name="name" placeholder="" class="input-xlarge">
<p class="help-block">First name can contain any letters or numbers, without spaces</p>
</div>
</div>
<div class="control-group">
<!-- surname -->
<label class="control-label" for="surname">Last name:</label>
<div class="controls">
<input type="text" id="surname" name="surname" placeholder="" class="input-xlarge">
<p class="help-block">Last name can contain any letters or numbers, without spaces</p>
</div>
</div>
<div class="control-group">
<!-- E-mail -->
<label class="control-label" for="email">Email:</label>
<div class="controls">
<input type="email" id="email" name="email" placeholder="" class="input-xlarge">
<p class="help-block">Please provide your Email</p>
</div>
</div>
<div class="control-group">
<!-- Password-->
<label class="control-label" for="pass">Password:</label>
<div class="controls">
<input type="password" id="pass" name="pass" placeholder="" class="input-xlarge">
<p class="help-block">Password should be at least 4 characters</p>
</div>
</div>
<div class="control-group">
<!-- Date -->
<label class="control-label" for="birthdate">Date:</label>
<div class="controls">
<input type="datetime" id="birthdate" name="birthdate" placeholder="" class="input-xlarge">
<p class="help-block">Please enter your birthdate</p>
</div>
</div>
<div class="control-group">
<!-- Sex -->
<label class="control-label" for="gender">Sex:</label>
<div class="controls">
<input type="text" id="gender" name="gender" placeholder="" class="input-xlarge">
<p class="help-block">Please enter your gender only M or F</p>
</div>
</div>
<div class="control-group">
<!-- Class -->
<label class="control-label" for="job">Job:</label>
<div class="controls">
<input type="text" id="job" name="job" placeholder="" class="input-xlarge">
<p class="help-block">Job can contain any letters or numbers, without spaces</p>
</div>
</div>
<div class="control-group">
<!-- Point -->
<label class="control-label" for="point">Point:</label>
<div class="controls">
<input type="number" id="point" name="point" placeholder="" class="input-xlarge">
<p class="help-block">Point can contain only numbers</p>
</div>
</div>
<div class="control-group">
<!-- Phone number -->
<label class="control-label" for="phonenumber">Phone number:</label>
<div class="controls">
<input type="tel" id="phonenumber" name="phonenumber" placeholder="" class="input-xlarge">
<p class="help-block">Please enter your phone number</p>
</div>
</div>
<div class="control-group">
<!-- Button -->
<div class="controls">
<button class="btn btn-success" name="submit" value="submit">Next</button>
</div>
</div>
</center>
</fieldset>
</form:form>
</body>
</html>
And my jsp register book
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%--
Created by IntelliJ IDEA.
User: lado
Date: 2019-06-02
Time: 12:51
To change this template use File | Settings | File Templates.
--%>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Register Book</title>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<%--<form:form class="form-horizontal" action='/springlab_war_exploded/login' method="post">--%>
<form:form class="form-horizontal" action="/springlab_war_exploded/login" method="post" modelAttribute="newborrow">
<fieldset>
<div id="legend">
<legend class="">Register Book</legend>
</div>
<div class="control-group">
<!-- id -->
<%--<label class="control-label" for="borrowid">Borrow Id:</label>--%>
<div class="controls">
<form:label path="id">Borrow Id:</form:label>
<form:input path="id"/>
<%--<input type="number" id="borrowid" name="borrowid" placeholder="" class="input-xlarge">--%>
<p class="help-block">Enter borrow id(it is your id)</p>
</div>
</div>
<div class="control-group">
<!-- name -->
<%--<label class="control-label" for="personid">Person Id:</label>--%>
<div class="controls">
<form:label path="studentid">Person Id:</form:label>
<form:input path="studentid"/>
<%--<input type="number" id="personid" name="personid" placeholder="" class="input-xlarge">--%>
<p class="help-block">Eneter person id(it is your id)</p>
</div>
</div>
<div class="control-group">
<!-- surname -->
<%--<label class="control-label" for="bookid">Book Id:</label>--%>
<div class="controls">
<form:label path="bookid">Book Id:</form:label>
<form:input path="bookid"/>
<%--<input type="number" id="bookid" name="bookid" placeholder="" class="input-xlarge">--%>
<p class="help-block">Enter book id</p>
</div>
</div>
<div class="control-group">
<!-- Button -->
<div class="controls">
<button class="btn btn-success" name="submit" value="submit">Submit</button>
</div>
</div>
</fieldset>
</form:form>
</body>
</html>
Don't need "/" while redirecting or forwarding a request.
Can you try "redirect:registerbook";
I work with a Spring Mvc app and get HTTP Status [404] – [Not Found]. The landing page is namely index.jsp,
and called from the controller method,
#Controller
public class BitcoinWalletController {
#RequestMapping("/")
public String showBitcoinWallet() {
return "index";
}
}
In the index.jsp page, send money button is initially disabled,
<div class="buttons_box">
<button type="button" class="btn btn-default btn-lg active" <%= canSendMoney ? "" : "disabled='true'"%>
data-toggle="modal" data-target="#myModal">Send money
</button>
</div>
and only be active if the synchronization is completed and boolean canSendMoney returns true.
If the button is active, the code handles the POST operation is provided,
<%--modal contents here--%>
<div class="modal-content">
<div class="model-header">
<button type="button" class="close" data-dismiss="modal">×!</button>
<h4 class="modal-title">Send Money</h4>
</div>
<form id="send-form" class="form-horizontal" action="sendMoney.jsp" method="POST">
<div class="modal-body">
<div class="form-group">
<label for="amount" class="col-sm-2 control-label">Send</label>
<div class="col-xs-4">
<input id="amount" name="amount" class="form-control" value="0">
</div>
<div class="btc-col">
<span>BTC</span>
</div>
</div>
<div class="form-group">
<label for="address" class="col-sm-2 control-label">to</label>
<div class="col-sm-10">
<input id="address" name="address" class="form-control">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-default">Send</button>
</div>
</form>
</div>
The sendMoney.jsp code is provided below,
<body>
<%
String amount = request.getParameter("amount").trim();
String address = request.getParameter("address").trim();
WalletSendMoneyController.getSendMoneyController().send(address, amount);
// New location to be redirected
String site = new String("/");
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
%>
</body>
When I put all the required and correct infos and press the button, It should return to the original page- index.jsp. Instead, I get the error, HTTP Status [404] – [Not Found],
I currently don't have any handle for the address http://localhost:8080/sendMoney.jsp. Because, if the POST submission is correct, I would like to redirect to the "/".
I have the jsps in the WEB-INF folder in the project directory,
The jsps location provided in the dispatcher-servlet.xml file,
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsps/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
The we.xml knows where the dispatcher-servlet.xml is located,
<servlet>
<description></description>
<display-name>dispatcher</display-name>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
How to solve the issue? Thanks.
Your code showing: You are actually trying to submit form to sendMoney.jsp which is not exist(might be, cause i can't see your whole project). Though you need to submit the form to a controller with a ModelAttribute which you need to create.
The following things you have to do for POST to controller from form.
Make a class for form fields
public class Data {
private String address;
private String amount;
public Data() {
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}
Bind a new Data object in GET controller where you load the form in HTML
#RequestMapping("/")
public String showBitcoinWallet() {
model.addAttribute("data", new Data());
return "index";
}
The following form will be in your index.jsp page, Where /send is the controller's mapping where to POST the form
<form:form id="send-form" modelAttribute="data" class="form-horizontal" action="/send" method="POST">
<div class="modal-body">
<spring:bind path="amount">
<div class="form-group">
<label for="amount" class="col-sm-2 control-label">Send</label>
<div class="col-xs-4">
<form:input path="amount" id="amount" name="amount" class="form-control" value="0"></form:input>
</div>
<div class="btc-col">
<span>BTC</span>
</div>
</div>
</spring:bind>
<spring:bind path="address">
<div class="form-group">
<label for="address" class="col-sm-2 control-label">to</label>
<div class="col-sm-10">
<form:input path="address" id="address" name="address" class="form-control"></form:input>
</div>
</div>
</spring:bind>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-default">Send</button>
</div>
</form:form>
Following controller for /send POST
#RequestMapping(value = "/send", method = RequestMethod.POST)
public String sendMoney(Data data) {
//here will be your code for send money and whatever you have to do..
...send(data.getAddress(), data.getAmount());
return "redirect:/"; //here will the location where you want to redirect
}
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
Have you defined this in your spring-config.xml file ??
I am using eclipse with tomcat here is my servlet ,the problem is when I click the button called GetStared it redirects me to empty html page with the text "surved at :myproject123" . myproject123 is the name of my project in the eclipse IDE.
#WebServlet("/home")
public class homeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String htmlFile = "loginPage.html";
RequestDispatcher view = request.getRequestDispatcher(htmlFile);
view.forward(request, response);
}
}
Here is my html file : called index.html
<div class="background-wrap">
<video id="video-bg-elem"
preload="auto"
autoplay="autoplay"
loop="loop" muted="muted">
<source src="video.mp4" type="video/mp4">
Video not supported
</video>
</div>
<div class="content">
<div class="info">
<div class="vertical_align">
<h2>Spotify</h2>
<output>Music for each moment.</output>
</div>
<div class="vertical_align2">
<form action="home" method="GET">
<button type="submit"
value="Get Started"
class="animated_button">
GET STARTED
</button>
</form>
</div>
</div>
</div>
Here is loginPage.html
<div class="myCirle">
<img src="logo10.png" />
<div class="under_logo">
<p>Spotify.</p>
</div>
</div>
<form class="form-signin" action="login" method="POST">
<div class="form-input" >
<input type="text" name="Username" placeholder = "Enter username" />
</div >
<div class="form-input" >
<input type="password" name="Password" placeholder="Enter password" />
</div >
<div class="form-input">
<input type="submit" name="submit" value="Sign In" class="btn-login" /><br />
<input type="submit" name="submit" value="Sign In With Facebook" class="btn-loginFB" />
</div>
<div class="form-input">
Forgot password?
</div>
<div class="form-input">
<input type="submit" name="submit" value="Not a spotifyier yet?" class="btn-reg" />
</div>
</form>
</div>
</body >
problem seems to be with forward the request....you can try this.. request.getRequestDispatcher("/"+htmlFile); or request.getRequestDispatcher("//"+htmlFile);
it is so because getRequestDispatcher () accepts link to the resources instead of direct file name.So if your file in inside your webapp like MyApp/myFile,then
request.getRequestDispatcher("/myFile");
if it is inside WEB-INF,then..
request.getRequestDispatcher("/WEB-INF/myFile");
and so on...
I am working on application using html, thymeleaf, Spring MVC, I wanted to send table data to spring controller but in when I clicked on save button of the application, getting an error on console:
java.lang.IllegalStateException: Neither BindingResult nor plain
target object for bean name 'salesProduct[0]' available as request
attribute
at org.springframework.web.servlet.support.BindStatus.(BindStatus.java:144)
at org.thymeleaf.spring4.util.FieldUtils.getBindStatusFromParsedExpression(FieldUtils.java:396)
Browser Error:
HTTP Status 500 - Request processing failed; nested exception is
org.thymeleaf.exceptions.TemplateProcessingException: Error during
execution of processor
'org.thymeleaf.spring4.processor.attr.SpringInputGeneralFieldAttrProcessor'
(sales:290)
I have added three attributes to controller like salesBean, paymentBean and salesProductFormBean, you can see in below spring controller code that is the reason in html I have not added th:object="${...}" in the form tag.
HTML
Sales.html
<form th:action="#{/salesForm}" method="post" class="mainData"
id="form">
<div class="buttonBar" id="mainbutton">
<div>
<button class="btn" id="save" type="submit">
<img th:src="#{/resources/images/save.svg}" /> Save
</button>
<button class="btn" id="reset" onclick="clearForm()" type="reset">
<img th:src="#{/resources/images/reset.svg}" /> Reset
</button>
<button type="button" class="btn" id="clientNew">
<img th:src="#{/resources/images/notebook.svg}" /> Client Creation
</button>
</div>
</div>
<div class="container">
<div class="mp-pusher" id="mp-pusher">
<nav id="mp-menu" class="mp-menu"></nav>
<div class="scroller-inner"></div>
<div class="containerMain">
<div class="mainArea">
<div class="inputArea">
<div class="ccode">
<lable class="lable">Client code</lable>
<input type="text" class="inputfield" id="ccode"
th:field="*{salesBean.client.clientId}" />
<button type="button" class="inputbutton" id="clientData"></button>
</div>
<div>
<ul class="tabs" data-persist="true">
<li>Basic data</li>
<li>Payment</li>
</ul>
<div class="tabcontents">
<div id="tab1">
<div class="invNo">
<lable class="lable">Invoice number</lable>
<input type="text" id="invNo" th:field="*{salesBean.salesId}"
name="salesId" class="inputfield disabled"
readonly="readonly" />
</div>
<div class="invdate calendar">
<lable class="lable">Invoice date</lable>
<input type="date" class="inputfield" id="invdate"
th:field="*{salesBean.invoiceDate}" /> <span
class="calendar"><img
th:src="#{/resources/images/calendar.svg}" /></span>
</div>
<div class="txtChallan">
<lable class="lable">Challan number</lable>
<input type="text" class="inputfield" id="txtChallan"
th:field="*{salesBean.challanNumber}" />
</div>
<div class="txtChallDt calendar">
<lable class="lable">Date</lable>
<input type="date" class="inputfield" id="txtChallDt"
th:field="*{salesBean.challanDate}" /> <span
class="calendar"><img
th:src="#{/resources/images/calendar.svg}" /></span>
</div>
<div class="txtPO">
<lable class="lable">P. O. ID</lable>
<input type="text" class="inputfield" id="txtPO"
th:field="*{salesBean.purchaseOrderId}" />
</div>
<div class="txtPoDt calendar">
<lable class="lable">Date</lable>
<input type="date" class="inputfield" id="txtPoDt"
th:field="*{salesBean.purchaseOrderDate}" /> <span
class="calendar"><img
th:src="#{/resources/images/calendar.svg}" /></span>
</div>
</div>
<div id="tab2">
<div class="txtCash">
<lable class="lable">Cash</lable>
<input type="number" class="inputfield" id="txtCash"
th:field="*{paymentBean.cash}" />
</div>
</div>
</div>
<!-- tabcontents -->
</div>
<!-- blank -->
<!-- for autocomplete -->
<div class="ui-widget" id="autocomplete_desc">
<div class="tableArea">
<div class="tablePanel">
<div class="tableButtonBar">Material entry</div>
<section class="tableHolder">
<table id="invoicetable" class="transactionTable table"
cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>Serial</th>
<th>Description</th>
<th>Nos.</th>
<th>Quantity</th>
<th>Rate</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr
th:each="salesProduct, stat: *{salesProductFormBean.salesProducts}">
<td th:text="${stat.count}">1</td>
<td><input type="text"
**Line no: 290** th:field="*{salesProduct[__${stat.index}__].numbers}" /></td>
<td><select type="select" class="selectfield"
id="product"
th:field="*{salesProduct[__${stat.index}__].product.productId}">
<option value="Select"></option>
<option th:each="prdList : ${productList}"
th:value="${prdList.productId}"
th:text="${prdList.productName}"></option>
</select></td>
<td><input type="number"
th:field="*{salesProduct[__${stat.index}__].quantity}" /></td>
<td><input type="number"
th:field="*{salesProduct[__${stat.index}__].rate}" /></td>
<td><input type="number"
th:field="*{salesProduct[__${stat.index}__].amount}" /></td>
</tr>
</tbody>
</table>
</section>
</div>
<!-- tablePanel -->
</div>
<!-- tableArea -->
</div>
</div>
<!-- inputArea -->
</div>
<!-- mainArea -->
</div>
<!-- containerMain -->
</div>
<!-- /container -->
</div>
</form>
Controller
#Autowired
private List<SalesProduct> salesProducts= new ArrayList<SalesProduct>();
#ModelAttribute("salesProducts")
public List<SalesProduct> salesProducts() {
return salesProducts;
}
#RequestMapping(value= "/sales", method = RequestMethod.GET)
public String salesInvoicePage(final ModelMap model) {
String userName = LoginController.getPrincipal();
model.addAttribute("user", userName);
model.addAttribute("salesBean", new Sales());
model.addAttribute("paymentBean", new Payment());
SalesProductForm salesProductForm = new SalesProductForm();
SalesProduct salesProduct= new SalesProduct();
salesProducts.add(salesProduct);
salesProductForm.setSalesProducts(salesProducts);
model.addAttribute("salesProductFormBean", salesProductForm);
//model.addAttribute("salesProducts", salesProducts);
List<Product> productList= productService.list();
model.addAttribute("productList", productList);
return "sales";
}
Model
public class SalesProduct implements java.io.Serializable {
private Integer salesProductId;
private Product product;
private UserDetail userDetailByModifiedBy;
private UserDetail userDetailByCreatedBy;
private Date createdDate;
private Date modifiedDate;
private String numbers;
private Float quantity;
private Float rate;
private Float amount;
private Set<Sales> saleses = new HashSet<Sales>(0);
//Setter and Getters
}
public class SalesProductForm {
private List<SalesProduct> salesProducts;
public List<SalesProduct> getSalesProducts() {
return salesProducts;
}
public void setSalesProducts(List<SalesProduct> salesProducts) {
this.salesProducts = salesProducts;
}
}
I got stuck in this issue but dont know what am I missing. Does anyone knows what am I doing wrong?