Doesn't switch to another .jsp when I click submit. Spring mvc - java

My controller. When I open the browser, the start page starts.jsp and create model User, which haves one field(String name) and set,get method. In start.jsp haves field of text and submit "LOGIN".
#Controller
public class HomeController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView start() {
return new ModelAndView("start", "user", new User());
}
#RequestMapping(value = "/input", method = RequestMethod.POST)
public ModelAndView input(#ModelAttribute("user") User user) {
return new ModelAndView("input", "userName", user);
}
}
My start page. Have text field and submit.
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<title>start</title>
</head>
<body>
<h1>TEST</h1>
<form:form method="post" commandName="user" action="input">
<input type="text" name="name"><br>
<input type="submit" value="LOGIN">
</form:form>
</body>
</html>
My problem: I open localhost:8080/webapp and input name. In the moment there is creating examplar of model User. I push "LOGIN" and I turn in localhost:8080/input, where "input.jsp" is two page, which output "Hello world, {name}". But if I replace action="input" in start.jsp with action="webapp\input" then everything is good. But I think it's bad idea.

I don't see any issues with your code. I tried to set this example and works fine for below configuration.
webapp-servlet.xml:
<context:component-scan base-package = "com.test" />
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/" />
<property name = "suffix" value = ".jsp" />
</bean>
JSP locations :
\WEB-INF\jsp\input.jsp
\WEB-INF\jsp\start.jsp
sample input.jsp:
<%# page import="com.test.*" %>
<html>
<head>
<title>start</title>
</head>
<body>
<h1>TEST</h1>
<%
User user = (User)request.getAttribute("userName");
%>
Hello - <%=user.getName() %>
</body>
</html>
No changes required in start.jsp and HomeController

Related

Error messages not showing upon validating form

So i have to make this app where you have a list of birdspecies and you can add new ones to the list. This form needs to have some validation but for some reason the error messages aren't showing up. Also, when you enter all the input correctly, everything works perfect but when you enter wrong input, it should just show the same page again, but it returns a whitelabel error instead.
here is my modelclass with the validation:
public class BirdSpecie {
#NotEmpty(message="This input may not be empty")
private String name;
#NotNull(message="This input may not be empty")
#DecimalMin(value="1250", message="The earliest year of discovery allowed is 1250")
private Integer yearOfDiscovery;
#NotEmpty(message="This input may not be empty")
#Pattern(regexp= "^[A-Z]{1,2}[0-9]{3}$", message="Code should start with one or more capital letters [A-Z] followed by 3 digits")
private String code;
Here is my controller method:
#PostMapping(value="/{locationName}/addBirdSpecie")
public String onSubmit (
#PathVariable("locationName")String locationName,
#Valid #ModelAttribute("spottedBirdSpecie") BirdSpecie birdSpecie,
Model model, BindingResult result)
{
model.addAttribute("spottedBirdSpecie", birdSpecie);
BirdSpotLocation birdSpotLocation = spottedBirdService.findByName(locationName).get();
yearValidation.validate(birdSpecie,result);
if(result.hasErrors()) {
return "addSpecie";
}else {
birdSpotLocation.increaseBirdSpot(birdSpecie);
model.addAttribute("location", birdSpotLocation);
return "birdsList";
}
}
and here is my jsp file:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#taglib prefix = "form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<spring:url value="/css/style.css" var="urlCss"/>
<link rel="stylesheet" href="${urlCss}" type="text/css" />
<title>Create a new bird Specie</title>
</head>
<body>
<h1>Create new bird specie: </h1>
<form:form method="post" action="addBirdSpecie" modelAttribute="spottedBirdSpecie">
<spring:url value="/birdspotting/" var="showLocation" />
<div>
<p>
Specie: <form:input path="name" size="25"/><br>
<form:errors path="name" cssClass="error"/>
</p>
<p>
Year of discovery: <form:input path="yearOfDiscovery" size="25"/><br>
<form:errors path="yearOfDiscovery" cssClass="error"/>
</p>
<p>
Books of birds code: <form:input path="code" size="25"/><br>
<form:errors path="code" cssClass="error"/>
</p>
<input type="submit" value="Spot new bird"/>
</div>
</form:form>
</body>
</html>
the error messages are showing correctly in my console, but they won't show up on the website.

Is it possible to output a drop-down list with values from DB in an easier way?

This way is not greatest. I'm looking for a better way. Is it possible to do without Lists?
My PageController:
public class CreateUserPageController {
#Autowired
private UserServiceImpl userServiceImpl;
#RequestMapping(value = "/create-user", method = RequestMethod.GET)
public ModelAndView showForm() {
ModelAndView model = new ModelAndView("admin/create-user");
model.addObject("user", new User());
UserRoleDTO[] roles = UserRoleDTO.values();
List<String> roleNames = new ArrayList<>();
for (UserRoleDTO role : roles) {
roleNames.add(role.getName());
}
model.addObject("roleNames", roleNames);
return model;
}
#RequestMapping(value = "/create-user", method = RequestMethod.POST)
public ModelAndView submitForm(#ModelAttribute("user") User user) {
userServiceImpl.create(user);
return showForm();
}
}
My JSP:
<%# 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" %>
<html>
<head>
<title>Create test</title>
</head>
<body>
<h1>Create Test</h1>
<form:form method="POST" action="/create-test" modelAttribute="topicTestDTO">
<form:input path="topic.name" type="text" list="topic_list" placeholder="choose or create topic"/>
<datalist id="topic_list">
<c:forEach items="${topicList}" var="topic">
<option>${topic}</option>
</c:forEach>
</datalist>
<br>
<form:input path="test.name" type="text" placeholder="create test name"/>
<input type="submit">
</form:form>
</body>
</html>
Thanks for help.
If you need more information, tell me which one and I'll complete the code.
Here the problem is for every request it goes to Database to retrieve the data, even data is not changing also it reduces the performance of application.
By using local cache we can achieve performance, so while application loading it self data will be queried from database and store it in cache,then we can reuse the data from cache.

Spring MVC validation annotations not displaying error messages

I am new to spring framework. Currently, I am doing spring validations using annotations.
So look at my DAO Class:
public class Spitter {
private Long id;
#NotNull(message = "Username cannot be null")
#Size(min = 10, max = 14, message = "Username must be between 10 and 14 characters long")
private String username;
SETTERS AND GETTERS }
This is my controller:
#Controller
#RequestMapping("/spitters")
public class SpitterController {
#RequestMapping(value = "/edit", method=RequestMethod.GET)
public String createSpitterProfile(Model model) {
model.addAttribute("spitter", new Spitter());
return "spitters/edit";
}
#RequestMapping(value = "/edit/createAccount", method = RequestMethod.POST)
public String addSpitterFromForm(Model model, #Valid #ModelAttribute("spitter")Spitter spitter, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "spitters/edit";
} else {
// spitterService.addSpitter(spitter);
return "redirect:/home";
}
}
}
And JSP file:
<%--suppress XmlDuplicatedId --%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="s" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%# taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Spitter</title>
</head>
<body>
<h2>Create free Spitter account</h2>
<sf:form action="/spitters/edit/createAccount"
method="post" commandName="spitter">
<table class="formtable">
<tr>
<td class="label">User Name</td>
<td><sf:input class="control" name="username" path="username"
type="text"></sf:input></br>
<sf:errors path="username"></sf:errors></td>
</tr>
<td class="label"></td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</sf:form>
</body>
</html>
However, Spitter Controller can receive data from jsp form. But constraints(#NotNull and #Size) added in DAO Class don't work and I don't know why.
Please be more spceific about the non-working constraints. An example
would help
Maybe your bean data is valid and username is just empty string. I think you use Hibernate Validator, if so try to add #NotEmpty constraint to username field
I believe you need to register bean MethodValidationPostProcessor. See Spring Docs

Extrating data from jsp form to controller and saving them to database

Hello I am trying to save data from a form to database however I have no idea how to continue now. I have this following code.
I tried using the request.getParameter("id") in the controller which gave me an compiler error.
So how do I get the data from the jsp form to the controller and then save them to the MySQL database ?
jsp file
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="ProductController" method="post">
<p>Enter product name :</p> <input id="productName" type="text" name="username"> <BR>
<p>Enter product serial number :</p> <input id="serialNumber" type="password" name="password"> <BR>
<input type="submit" placeholder="Submit" />
</form>
</body>
</html>
The controller
#Controller
#RequestMapping("/product")
public class ProductController {
#Autowired
private ProductService productService;
#RequestMapping("/list")
public ModelAndView list() {
ModelAndView modelAndView = new ModelAndView("product/list");
System.out.println("Count:" + productService.getProducts().size());
modelAndView.addObject("test", "mytest");
modelAndView.addObject("count", productService.getProducts().size());
modelAndView.addObject("products", productService.getProducts());
return modelAndView;
}
}
and product DAO
#Override
public void saveProduct(Product product) {
//persist(product);
Session session = this.sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.persist(product);
tx.commit();
session.close();
}
you have to use name attribute of html element to get value, like request.getParameter("username");

How do you query a database from JSP Form Data?

I am in need of assistance. I am trying to write a basic form that populates a drop-down list and based on what you select, it queries the database. However, I cannot get it to do it, It just receives all the queries. I am at a loss so if you have any helpful advice or helpful links, that'd be great. I really need to learn Spring MVC, and Hibernate combined. thanks!
HomeController Code: (This controller populates the list)
/**
* Handles requests for the application home page.
*/
#Controller
public class SearchController {
#Autowired
FilmBo filmBo;
/**
* Simply selects the home view to render by returning its name.
*/
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, ModelMap model) {
Selection selection = new Selection();
model.addAttribute("selection", selection);
return "search";
}
#ModelAttribute("categoryList")
public List<String> populateList(){
List<String> categoryList = filmBo.searchByCategory("");
return categoryList;
}
}
Here is the MainController that the form upon submit gets sent to:
public class FilmController {
private static final Logger logger = LoggerFactory.getLogger(SearchController.class);
#Autowired
FilmBo filmBo;
#RequestMapping(value = "/films", method = RequestMethod.GET)
public String home(Locale locale, Model model, #RequestParam(value="title",required=false) String title,
#RequestParam(value="category",required=false) String category) {
logger.info("Welcome home! The client locale is {}.", locale);
List<Film> filmList = filmBo.searchByTitle(title);
logger.info("filmList: " + filmList);
model.addAttribute("filmList", filmList);
List<String> filmCategory = filmBo.searchByCategory(category);
logger.info("filmCategory: " + filmCategory);
model.addAttribute("filmCategory",filmCategory);
return "films";
}
}
Here is my jsp page:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# page session="false"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div class="form">
<form:form action="${pageContext.request.contextPath}/films"
method="GET" commandName="selection">
Film Title<input type="text" name="title">
<br>
Select a Film Category:<br>
<form:select path="selection">
<form:option value="NONE" label="--- Select ---" />
<form:options name="category" items="${categoryList}" />
</form:select>
<button name="submit" type="submit">Submit Name</button>
</form:form>
</div>
</body>
</html>

Categories

Resources