I am trying to run a simple Spring 3 MVC project to save form data but when I submit data the page goes to add.html with empty forms and no data is save in Mysql neither it is shown on the page.
Controller
package com.app.a;
/**
* Handles requests for the application home page.
*/
#Controller
#RequestMapping(value="/")
public class HomeController {
#Autowired
private Personrepo personRepo;
#RequestMapping(method=RequestMethod.GET)
public String showForm(ModelMap model){
List<Person> persons = personRepo.getAll();
model.addAttribute("persons", persons);
Person person = new Person();
person.setId(UUID.randomUUID().toString());
model.addAttribute("person", person);
return "home";
}
#RequestMapping(value="/add", method=RequestMethod.POST)
public ModelAndView add(#ModelAttribute(value="person") Person person,BindingResult result){
ModelAndView mv = new ModelAndView("home");
if(!result.hasErrors()) {
personRepo.add(person);
person = new Person();
person.setId(UUID.randomUUID().toString());
mv.addObject("person", person);
}
mv.addObject("persons", personRepo.getAll());
return mv;
}
#RequestMapping(value="/edit", method=RequestMethod.POST)
public ModelAndView edit(#ModelAttribute(value="person") Person person,BindingResult result) {
ModelAndView mv = new ModelAndView("home");
if(!result.hasErrors()) {
personRepo.edit(person);
person = new Person();
mv.addObject("person", person);
}
mv.addObject("persons", personRepo.getAll());
return mv;
}
#RequestMapping(value="/delete", method=RequestMethod.POST)
public ModelAndView update(#ModelAttribute(value="person") Person person,BindingResult result){
ModelAndView mv = new ModelAndView("home");
if(!result.hasErrors()) {
personRepo.delete(person.getId());
//personRepo.delete(person);
person = new Person();
mv.addObject("person", person);
}
mv.addObject("persons", personRepo.getAll());
return mv;
}
}
Home .jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%#taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<!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">
</head>
<body>
<table align="center">
<c:forEach items="${persons}" var="person">
<tr>
<td>Welcome:</td>
<td><c:out value="${person.firstName}" /></td>
</tr>
<tr>
<td>Your lastname:</td>
<td><c:out value="${person.lastName}" /></td>
</tr>
</c:forEach>
</table>
<form:form modelAttribute="person" method="post" action="add.html">
<form:hidden path="id" />
<table>
<tr>
<td><form:label path="firstName">First Name:</form:label></td>
<td><form:input path="firstName" /></td>
</tr>
<tr>
<td><form:label path="lastName">Last Name</form:label></td>
<td><form:input path="lastName" /></td>
</tr>
<tr>
<td><form:label path="money">Money</form:label></td>
<td><form:input path="money" /></td>
</tr>
</table>
<input type="submit" value="Save" />
</form:form>
</body>
</html>
From the looks of it, unless you are doing content negotiation, you don't have a controller method mapped to the URL add.html.
Compare:
<form:form modelAttribute="person" method="post" action="add.html">
and
#RequestMapping(value="/add", method=RequestMethod.POST)
Make it
<form:form modelAttribute="person" method="post" action="add">
and you should be fine.
Related
Hi there im new with spring boot and mvc model im trying to create some methods to call some data to the Mongo D.B using postman im getting the data but now i want to show this data in a web page but i cant figure out how mapping works in spring boot.
I have this methods:
#Controller
#RequestMapping("/Informacion")
public class InformacionControlador {
#Autowired
private informacionRepo informacioRepo;
public InformacionControlador(informacionRepo informacioRepo) {
this.informacioRepo = informacioRepo;
}
//This method is comment because using postman get the answer in json format
// #GetMapping("/Listar")
// public List<Informacion> getAll() {
// List<Informacion> info = this.informacioRepo.findAll();
// return info;
// }
//Now this is the method that i want to work like the first one but
//instead of json answer y want to see the data in ListarInformacion page
#GetMapping("/Listar")
public String informacion(ModelMap model) {
model.addAttribute("info", informacioRepo.findAll());
return "ListarInformacion";
}
#PutMapping
public void insert(#RequestBody Informacion informacion) {
this.informacioRepo.insert(informacion);
}
}
Also i put this lines in application.properties file to set the folder where the page will be storage
spring.mvc.view.prefix=/webapp/Vistas
spring.mvc.view.suffix=.jsp
This is my ListarInformacion page
<html>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>
<head>
<title>Title</title>
</head>
<body>
<form:form method="GET" action="/webapp/Vistas/ListarInformacion" modelAttribute="Informacion">
<table class="table table-striped table-hover">
<thead class="thead-dark">
<tr>
<th scope="col">ID</th>
<th scope="col">Nombre</th>
<th scope="col">Identificación</th>
<th scope="col">Fecha Creación</th>
</tr>
</thead>
<c:forEach var="p" items="${info}">
<tr>
<td>${p.idInformacion}</td>
<td>${p.nombre}</td>
<td>${p.pais}</td>
<td><fmt:formatDate pattern="dd/MM/yyyy" value="${p.fechaCreacion}"/></td>
<td>
</td>
</tr>
</c:forEach>
</table>
</form:form>
</body>
</html>
this is the location of my files
can anyone tell me what am i missin because when i try to access to the url localhost:8080/Informacion/Listar the answer is a String that says /ListarInformacion ant its no redirecting me to the page that its supose to redirect
You should try to access localhost:8080/Informacion/Listar as you have already given mapping to the controller class (/Informacion)
the preferred location to put the jsp in a spring boot project is
--webapp
--WEB-INF
--jsp
--your.jsp
in your case it is
-
-webapp
--WEB-INF(Create WEB-INF directory if you don't have)
--Vistas(folder)
--jsp
--hello.jsp
And your view path in properties file will be spring.mvc.view.prefix=/WEB-INF/Vistas
This is my code. I'm trying to add values to my table using JSP and MYSQL. Name of the table and database is correct.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import ="java.sql.*" %>
<%# page import ="javax.sql.*" %>
<!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>Inserting Data from form</title>
</head>
<body>
<h1> Insert a Record</h1>
<form method="post" action="insertrecord.jsp">
<table>
<tr>
<td>
<input type="text" name="uname">
</td>
<td>
<input type="password" name="upass">
</td>
<tr>
<tr>
<td><input type="submit" name="submit" value ="submit"></td>
</tr>
</table>
</form>
<%
String sub = request.getParameter("submit");
if(sub!=null)
{
String uname=request.getParameter("uname");
String password = request.getParameter("upass");
if(uname!=null && password!=null)
{
try
{
Connection con;
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo","root","");
Statement stmt = con.createStatement();
int i = stmt.executeUpdate("insert into user values ('"+uname+"','"+password+"')");
out.println("Record Inserted Successfully");
stmt.close();
con.close();
}
catch(SQLException e)
{
out.println(e.getMessage());
}
}
}
%>
</body>
</html>
When I click on submit. I'm getting this error:
HTTP Status 404 – Not Found
Type Status Report
Message /something/insertrecord.jsp
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
Apache Tomcat/9.0.5
<script type="text/javascript" src="${pageContext.request.contextPath}/resources/js/jquery.validate.min.js"></script>
<script>
function setHiddenVal(){
var goAhead = true;
var myVal="I am hidden value";
document.getElementById("secretValue").value = myVal;
if (goAhead == true) {
document.forms["register-form"].submit();
}
}
</script>
</head>
<body>
<!--Main Container Starts here-->
<div class="main_container">
<div class="header">
<div class="right_panel">
<h2 align="center"><u>User Master</u></h2>
<div class="top-form">
<div>
**<form:form action="/usermaster" modelAttribute="CustomerForm" id="register-form" method="POST">**
<table cellspacing="0" cellpadding="0" border="" class="form1">
<tr>
<td class="label">Name:</td>
<td>
<form:input path="firstname"/>
</td>
</tr>
<tr>
<td class="label">Password:</td>
<td>
<form:input path="password"/>
</td>
</tr>
</tbody>
</table>
<div>
<table>
<tr>
<td> </td>
<td>
<input type="button" class="btn blue px16" value="Search" />
<input type="button" name="submit" id="btnsubmit" value="Submit" onclick="setHiddenVal();"/>
<input type="button" class="btn blue px16" value="Clear" />
<input type="button" class="btn blue px16" value="Change Password" />
<input type="button" class="btn blue px16" value="Manage User Notification Profile" />
</td>
</tr>
</table>
</div>
</form:form>
</div>
</div>
<div class="clear"></div>
</div>
</div>
</div>
</body>
</html>
so above one is my code for jsp and below is the code of controller
#RequestMapping(value={"/usermaster" }, method = RequestMethod.POST)
public final String addUserMaster(#ModelAttribute("CustomerForm") CustomerForm pricing, Map<String, Object> map,
Model model, HttpServletRequest request) {
System.out.println("the first name is "+pricing.getFirstname());
System.out.println("the password is "+pricing.getPassword());
return "usermaster";
}
#RequestMapping(value={"/showusermaster" }, method = RequestMethod.GET)
public String showPage(ModelMap model){
model.addAttribute("CustomerForm", new CustomerForm());
return "usermaster";
}
But my page gets open up using a popup with the url:
C:\Users\ganganshu.s\AppData\Local\Microsoft\Windows\Temporary Internet Files\Content.IE5\YW6383E8\usermaster
so it should open like
http://localhost:8080/enbee/usermaster
Could you please tell me what should I put in the form action.. as I think some mistake is there in the form action does in spring MVC we put the action like in the case I mentioned above.
Spring confg file is given below :
<mvc:interceptors>
<bean class="com.enbee.admin.interceptor.AuthenticationInterceptor" />
<!-- Declare a view resolver-->
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" p:order="1" />
and the jsp name is usermaster.jsp
and in the sidemenu.jsp I have changed to this :
<li>User Master</li>
Change the method parameter of RequestMapping annotation to RequestMethod.POST:
#RequestMapping(value="/usermaster", method = RequestMethod.POST)
public final String addUserMaster(...){
...
}
so that when you submit your form to the URL /usermaster using method="POST" this method will get executed.
You also need to have a method (mapped to an URL) that will show this page to the user. You can use a method as below for this:
#RequestMapping(value = "/showusermaster", method = RequestMethod.GET)
public String showPage(ModelMap model){
model.addAttribute("CustomerForm", new CustomerForm());
return "usermaster";
}
With this method in place, the URL
http://localhost:8080/enbee/showusermaster
will show the usermaster.jsp page to the user. Now when you submit this form, the above addUserMaster method will be invoked.
You don't have to create new jsp file. The url /showusermaster will return the usermaster.jsp to the user, where the user can add form values and submit the form:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
...
<c:url var="submitUrl" value="/usermaster">
<form:form id="form" action="${submitUrl}" modelAttribute="CustomerForm" method="POST">
Now when the user clicks on the submit button, this form will be submitted to /usermaster URL and will be handled by addUserMaster method.
Try to specify the content type returned by your controller method, adding produces = "text/html" param to your #RequestMapping annotation.
we have problem with diacritic in jsp form in school project. We use Spring 3.0. In JSP form we have inputs which can contains words with diacritic (czech language,f.e "šáříěá"). When I start project and write diacritic words into these inputs and send form, immediately in controller are wrong values. Diacritic letters has strange form, for example "Ä???Ä".
Following code is our form.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Nový prostor</title>
</head>
<body>
<h1>Nový prostor</h1>
<form:form method="POST" commandName="PLACE" >
<fieldset>
<legend>Adresa prostoru</legend>
<table>
<tr>
<td><form:label path="name">Název prostoru</form:label></td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td><form:label path="street">Ulice a č.p.</form:label></td>
<td><form:input path="street" /></td>
</tr>
<tr>
<td><form:label path="zip_code">PSČ</form:label></td>
<td><form:input path="zip_code" /></td>
</tr>
<tr>
<td><form:label path="city">Město</form:label></td>
<td><form:input path="city" /></td>
</tr>
</table>
</fieldset>
<fieldset>
<legend>Parametry prostoru</legend>
<table>
<tr>
<td><form:label path="rows">Počet řad</form:label></td>
<td><form:input path="rows" /></td>
</tr>
<tr>
<td><form:label path="columns">Počet sedaček v řadě</form:label></td>
<td><form:input path="columns" /></td>
</tr>
<tr>
<td><form:label path="note">Poznámky</form:label></td>
<td><form:textarea path="note" /></td>
</tr>
</table>
</fieldset>
<input type="submit" value="Vytvořit">
</form:form>
</body>
And this is conroller:
#Controller
#RequestMapping("/newPlace")
public class NewPlaceController {
#Autowired
private PlaceService placeService;
/**
* Pri pozadavku typu get vrati nazev jsp ktere se ma renderovat, nabinduje Complex place do formualre
* #param model
* #return
*/
#RequestMapping(method=RequestMethod.GET)
public String showNewPlaceForm(Model model){
model.addAttribute("PLACE", new ComplexPlace());
return "newPlaceForm";
}
/**
*Pri pozadavku POST ulozi data z formulare do DB
*
* #param place
* #param result
* #return
*/
#RequestMapping(method=RequestMethod.POST)
public String createNewPlace(#ModelAttribute(value="PLACE") ComplexPlace place, BindingResult result){
System.out.println(place.getName());
placeService.buildPlaceService(place);
placeService.PersistNewPlace();
return "/index";
}
}
System.out.println write strange value on console. Know somebody where is problem? I want remark, that we have small expirience with Java web programming.
Thanks
you can't use any other language other then standard english.if you want to do this then u have to use any standard free unicode converter.convert your character and put their unicode character at run time it is converted in your original language...i hope it works for you.
I have a very simple implementation of the DefaultModelBinder, I need it to fire some custom validation.
public class MyViewModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
ModelStateDictionary modelState = bindingContext.ModelState;
var model = (MyViewModel)base.BindModel(controllerContext, bindingContext);
var result = ValidationFactory.ForObject<MyViewModel>().Validate(model);
CustomValidation(result, modelState);
return model;
}
}
MyViewModel is a public sealed class.
The model binder is registered in the Global.asax this way:
ModelBinders.Binders.Add(typeof(MyViewModel), new MyViewModelBinder());
The problem is that the model is never populated! But the MVC default model binder (I remove the registration in global.asax) works fine.
This is the view HTML:
<table>
<tr>
<td><label for="Name">Name</label></td>
<td><input id="Name" name="Name" type="text" value="" /></td>
</tr>
<tr>
<td><label for="Code">Code</label></td>
<td><input id="Code" name="Code" type="text" value="" /></td>
</tr>
</table> </div>
Every field matches a property of the model.
From the information you provided I am unable to reproduce the problem. Here's what I did.
View model:
public sealed class MyViewModel
{
public string Name { get; set; }
public string Code { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// at this stage the model is populated perfectly fine
return View();
}
}
Index View:
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<% using (Html.BeginForm()) { %>
<table>
<tr>
<td><label for="Name">Name</label></td>
<td><input id="Name" name="Name" type="text" value="" /></td>
</tr>
<tr>
<td><label for="Code">Code</label></td>
<td><input id="Code" name="Code" type="text" value="" /></td>
</tr>
</table>
<input type="submit" value="OK" />
<% } %>
</body>
</html>
Model binder:
public class MyViewModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var model = (MyViewModel)base.BindModel(controllerContext, bindingContext);
// at this stage the model is populated perfectly fine
return model;
}
}
So now the question is, how does your code differs than mine and what is it in those CustomValidation and Validate methods?