Try to figure out when I load my jsp page the error message is shown even if I do not submit the button. Can anyone advice how to show error message after submit the button. I post my code here for control.
Thanks in advance
LoginController
#Controller
//#RequestMapping("/")
public class LoginController {
#Autowired
private LoginService loginServiceImpl;
#RequestMapping(value="/login", method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView validUser(#ModelAttribute("person") PersonModel personModel) {
ModelAndView model= new ModelAndView("login");
try
{
boolean validUser = loginServiceImpl.isValidUser(personModel.getName(), personModel.getPassword());
//Zjistí zda-li je user přihlášen
if(validUser)
{
System.out.println("User Login Successful");
model.addObject("successMessage", personModel.getName());
}
else
{
System.out.println("Login wasn't Successful");
model.addObject("unsuccessmessage", "Invalid credentials!!");
}
}
catch(Exception e)
{
e.printStackTrace();
}
return model;
}
}
JSP Page
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<form:form id="loginForm" method="post" action="login" modelAttribute="person">
<form:label path="name">Login name:</form:label>
<form:input id="name" name="name" path="name" /><br>
<form:label path="password">Password</form:label>
<form:password id="password" name="password" path="password" /><br>
<input type="submit" value="Submit" />
<h2>${unsuccessMessage}</h2>
<h2>${successMessage}</h2>
</form:form>
</body>
</html>
Related
What I am want to do is to add a record to a table and then to display that newly added record in a jsp page.
Here is what I tried:
Controller:
#Controller
public class UserController {
#Autowired
UserRepository userRepo;
#RequestMapping("/adduser")
public String userform(Model m){
m.addAttribute("command", new Users());
return "adduser";
}
#RequestMapping("/saveuser")
public String save(#ModelAttribute("user") Users user,Model model){
userRepo.save(user);
model.addAttribute("user", user);
return "forward:/user";
}
#RequestMapping("/user")
public String user(Model model) {
return "user";
}
And the jsp page:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css"
href="webjars/bootstrap/3.3.7/css/bootstrap.min.css" />
<c:url value="/css/main.css" var="jstlCss" />
<link href="${jstlCss}" rel="stylesheet" />
</head>
<body>
<div class="container">
<div class="starter-template">
<h1>Product List</h1>
<table
class="table table-striped table-hover table-condensed table-bordered">
<tr>
<th>Id</th>
<th>Color</th>
<th>Gender</th>
<th>Category</th>
</tr>
<c:forEach var="u" items="${user}">
<tr>
<td>${u.userid}</td>
<td>${u.username}</td>
<td>${u.userphone}</td>
<td>${u.useremail}</td>
</tr>
</c:forEach>
</table>
</div>
</div>
<script type="text/javascript"
src="webjars/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
Upon running the code the record is getting added successfully but It is not getting displayed instead I am getting the error mentioned in the title.
What to do to make it work?
#RequestMapping("/user")
public List<User> user(Model model) {
...
return ...;
}
${user} is the result of that method user.
<c:forEach var="u" items="${user}">
The forEach tag requires as itemssomething Iterable.
In fact the name should have been plural: users.
You need something like
public class User {
int userid;
String username;
String userphone;
String useremail;
}
<td>${u.userid}</td>
<td>${u.username}</td>
<td>${u.userphone}</td>
<td>${u.useremail}</td>
I can`t understand one thing when i send request to get object by name from db,
it always return me null. I surf all sites try to fix it with session and etc. Nothing to work.
Any ideas?
enter image description here
This is my Servlet class:
#WebServlet(value = "/display", name = "IndexServlet")
public class IndexServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
if(!(request.getParameter("mysql")==null)) {
MySQLRepository sql = new MySQLRepository();
Headline object = sql.getByHeadline(request.getParameter("mysql"), DatabaseConnection.initDatabase());
request.setAttribute("id", object.getId());
request.setAttribute("headline", object.getHeadline());
RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("out.jsp");
requestDispatcher.forward(request,response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is index.jsp:
<%# page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>MySQLSolrProject</title>
</head>
<!DOCTYPE html>
<body>
<form action="out.jsp" method="get">
<p>Headline:</p>
<label>
<input type="text" name="mysql">
</label>
<%--<br>
<p>Full text:</p>
<label>
<input type="text" name="solr">
</label>--%>
<br><br>
<input type="submit" value="Search" formmethod="get">
</form>
</body>
</html>
This is out.jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Out</title>
</head>
<body>
<h2>Text is:</h2>
<table>
<tr><th>Id</th><th>Headline</th><th></th></tr>
<tr><td><%=session.getAttribute("id")%></td>
<td><%=session.getAttribute("headline")%></td>
</tr>
</table>
<p>Return to search</p>
</body>
</html>
the error was that Tomcat version 10.* didn't want to work with version 4 servlets
I downgraded Tomcat to version 9.* and it worked.
I made a form submit application via Spring MVC. After submitting the form, all values of input fields are visible in url.
let's suppose that after submitting the generated URL is this:
SpringTuto/successA?name=FirstUser&designation=Student&country=XYZ&dob=2018%2F01%2F16&skills=paragliding&address.street_name=avenue+Road&address.city=New+City&address.district=New+District&address.pin_code=322343
From the above url, I want to encode name, designation, country and all other parameters in some encrypted code.
After reading a few articles, i came to an understanding that I will use the URIeditor(org.springframework.beans.propertyeditors.URIEditor) to encode. But I don't know how to use it. If anyone has another way to do this please share it.
Thanks in advance.
Here is my Controller Class.
#Controller
public class SpgController {
#ModelAttribute("header")
public Model addHeader(Model view) {
int a = 10;
return view.addAttribute(a);
}
#InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/mm/dd");
binder.registerCustomEditor(Date.class, "dob", new CustomDateEditor(dateFormat, false));
binder.registerCustomEditor(String.class, "name" , new NamepropertyEditor());
}
#RequestMapping("/main")
public ModelAndView go() {
ModelAndView view = new ModelAndView("main");
return view;
}
#RequestMapping(value = "/successA", method = RequestMethod.GET)
public ModelAndView method(#Valid #ModelAttribute("bean") Bean bean, BindingResult result ) {
if (result.hasErrors()) {
ModelAndView view = new ModelAndView("main");
return view;
}
ModelAndView view = new ModelAndView("successAnother");
return view;
}
}
Here is the successAnother.jsp page
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>Insert title here</title>
</head>
<body>
<form >
Name: ${bean.name}<br/>
Designation: ${bean.designation}<br/>
DoB: ${bean.dob}<br/>
Skills: ${bean.skills}<br/>
Street: ${bean.address.street_name}<br/>
City: ${bean.address.city}<br/>
District: ${bean.address.district}<br/>
PinCode: ${bean.address.pin_code}<br/>
Country: ${bean.country}<br/>
</form>
</body>
</html>
Here is main.jsp(Application form)
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://www.springframework.org/tags" prefix = "spring" %>
<!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>Spring</title>
</head>
<body>
English|French|Hindi
<h3>${msg}</h3>
<form:errors path = "bean.*"/>
<form action="successA" method="get">
<table>
<tr>
<td><spring:message code = "label.userName"/><input type="text" name="name">
</td>
</tr>
<tr>
<td><spring:message code = "label.userDesignation"/><input type="text" name="designation">
</td>
</tr>
<tr>
<td><spring:message code = "label.userCountry"/><input type="text" name="country">
</td>
</tr>
<tr>
<td>
<spring:message code = "label.userDoB"/><input type= "text" name = "dob" >
</td>
</tr>
<tr>
<td>
<spring:message code = "label.Skils"/><select name = "skills" multiple >
<option value= "driving">Driving</option>
<option value = "diving">Diving</option>
<option value = "swimming">Swimming</option>
<option value = "paragliding">Paragliding</option>
</select>
</td>
</tr>
<tr>
<td>
<h5><spring:message code = "label.userAddress"/></h5>
<spring:message code = "label.userStreetname"/><input type = "text" name = "address.street_name">
<spring:message code = "label.userCity"/> <input type = "text" name = "address.city">
<spring:message code = "label.userDistrict"/><input type = "text" name = "address.district">
<spring:message code = "label.userPin"/><input type = "text" name = "address.pin_code">
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td><input type="submit" value=<spring:message code = "label.userSubmit"/>></td>
</tr>
</table>
</form>
</body>
</html>
If your application supports HTTPS, then it can be achieved easily using spring security by doing some configuration as follows.
<http>
<intercept-url pattern="/**" access="ROLE_USER" requires-channel="https"/>
...
</http>
Integrating spring security with spring mvc is very simple.
I'm learning spring mvc and understand the use of the Model and ModelAttribute. However, I can't retrieve the Model's attribute so I resorted to using the JSP param value. What am I doing wrong? I checked the model still had a value for the attribute using #ModelAttribute("username") User user / user.username and sure enough it does.
Controller
package login.user;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class LoginUser {
#RequestMapping("/")
public String showMenu()
{
return "menu";
}
#RequestMapping("login")
public String loginUser(Model model)
{
User newUser = new User();
model.addAttribute("user", newUser);
return "login-user";
}
#RequestMapping("processUser")
public String processUser(Model model)
{
Option newOption = new Option();
model.addAttribute("option", newOption);
return "process-login";
}
}
User
package login.user;
public class User {
private String username;
private char password[];
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public char[] getPassword() {
return password;
}
public void setPassword(char[] password) {
this.password = password;
}
}
login-user.jsp
<%# 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"%>
<!DOCTYPE html>
<html>
<head>
<link href="<c:url value="/resources/css/style.css" />" rel="stylesheet" type="text/css" />
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login User</title>
</head>
<body>
<div>
<form:form action="processUser" modelAttribute="user">
<table>
<tr>
<td>Username:</td>
<td>
<form:input path="username" />
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<form:input type="password" path="password" />
</td>
</tr>
<tr>
<td>
<input type="submit" name="Login" />
</td>
</tr>
</table>
</form:form>
</div>
</body>
</html>
process-login.jsp
<%# 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"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form:form modelAttribute="option">
<h3>Welcome ${param.username}. Please choose an activity below</h3> <---- changed from ${user.username}
<div>
<form:select path="option">
<form:option value="Email" label="Email"></form:option>
<form:option value="Enter Recipe" label="Enter Recipe"></form:option>
<form:option value="Retrieve Recipe" label="Retrieve Recipe"></form:option>
</form:select>
</div>
</form:form>
</body>
</html>
Just change your last #RequestMapping method as follows:
#RequestMapping("processUser")
public String processUser(#ModelAttribute("user") User user, Model model)
{
Option newOption = new Option();
model.addAttribute("user", user);
model.addAttribute("option", newOption);
return "process-login";
}
Now use ${user.username} in jsp.
The spring model data is stored in the standard Java request scope. If you are trying to get the username, you need to add it in the request scope again. So, you can write the processUser method as follows.
#RequestMapping("processUser")
public String processUser(#ModelAttribute("user") User user,Model model)
{
Option newOption = new Option();
// do stuff with user data
newOption.setUsername(user.getUsername());
model.addAttribute("option", newOption);
return "process-login";
}
So, you should be able to get it in the jsp as ${option.username}.
Hi i got this error try to learn some of Spring Java framrework.
I got an 405 - Request method 'POST' not supported and i need some help to see what is my error on this
my controller
#Controller
#RequestMapping("overcomandant/addSitio.asp")
public class addSitioController {
#RequestMapping(method = RequestMethod.GET)
public ModelAndView addSitioForm() {
ModelAndView asf = new ModelAndView();
asf.setViewName("admin/addNewSite");
asf.addObject("sitio", new Sitio());
return asf;
}
#RequestMapping(value="admin/addNewSite", method = RequestMethod.POST)
public String addSitioSubmit(Sitio st, ModelMap model) {
model.addAttribute("url", st.getUrl());
model.addAttribute("nombre", st.getNombre());
model.addAttribute("estado", st.getEstado());
return "admin/exito";
}
#ModelAttribute("estadoLista")
public Map<String,String> ListadoEstados() {
Map<String, String> estado = new LinkedHashMap<>();
estado.put("1","Activo");
estado.put("2","Inactivo");
estado.put("3","Testing");
return estado;
}
}
and this is my form addNewSite.jsp
<form:form method="POST" commandName="sitio">
<div class="form-group">
<form:label path="id">ID</form:label>
<form:input path="id" cssClass="form-control"/>
</div>
<div class="form-group">
<form:label path="url">URL</form:label>
<form:input path="url" cssClass="form-control"/>
</div>
<div class="form-group">
<form:label path="nombre">Nombre</form:label>
<form:input path="nombre" cssClass="form-control"/>
</div>
<div class="form-group">
<form:label path="estado">Estado</form:label>
<form:select path="estado" cssClass="form-control">
<form:option value="0">Seleccione</form:option>
<form:options items="${estadoLista}" />
</form:select>
</div>
<input type="submit" value="Enviar" class="btn btn-primary" />
</form:form>
and the exito.js
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<p><c:out value="${url}"></c:out></p>
</body>
</html>
I try to understand what is worng.
The controller creates an object site adding the info form the form an then the otrer .jsp renders the new object created...
You have to specify your form action to correspond the method in your controller : admin/addNewSite.
The 405 error tells you that the form action is unknown.