I'm new in JSP and Servlets,
web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>LoginPage</servlet-name>
<servlet-class>com.planner.servlet.LoginPage</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginPage</servlet-name>
<url-pattern>/LoginPage</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContextBL.xml</param-value>
</context-param>
</web-app>
index.jsp file
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>Insert title here</title>
</head>
<body>
<form method="POST" action="/LoginPage">
<table border="1">
<tr>
<td>Login</td>
<td><input type="text" name="login" />
</td>
</tr>
<tr>
<td>Senha:</td>
<td><input type="password" name="pass" /></td>
</tr>
<tr>
<input type="submit" value="Entrar" />
</tr>
</table>
</form>
</body>
</html>
LoginPage.java
package com.planner.servlet;
import java.io.IOException;
import java.io.PrintWriter;
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 org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
/**
* Servlet implementation class LoginPage
*/
public class LoginPage extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public LoginPage() {
super();
}
#Override
public void init() throws ServletException {
WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
AutowireCapableBeanFactory bf = ctx.getAutowireCapableBeanFactory();
// bf.autowireBean(this);
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title> TESTE </title>");
out.println("</head>");
out.println("<body>");
out.println("Hello World!");
out.println("</body>");
out.println("</html>");
}
}
PROBLEM:
When I click on the submit button, it shows me the error:
**type Status report
message /Apontador_Web/LoginPage
description The requested resource is not available.**
And When I remove the tags "listener" and "context-param"
it loads the servlet.
What can be happening?
go to glashfish server output and look for an some exception
Tell me the name off exception
print all
You will need to add #WebServlet(urlPatterns={"/LoginPage"}) above your class name i.e public class LoginPage extends HttpServlet {
Related
how to render xhtml page , in springboot...,where should i put xhtml file
this is my project structure..what url should i hit for getting xhtml file.
how to call xhtml page
this is my xhtml page
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<body>
<form>
<p:panel header="Login Page">
<h:outputText value="id" />
<h:inputText id="id" value="#{a.id}" required="true"></h:inputText>
<h:message for="id" style="color:blue"></h:message>
<br></br>
<br></br>
<h:outputText value="name" />
<h:inputText id="name" value="#{a.name}" required="true"></h:inputText>
<h:message for="name" style="color:blue"></h:message>
<p:commandButton
action="#{a.validate()}"
value="login"></p:commandButton>
</p:panel>
<br></br>
<br></br>
</form>
</body>
</html>
even http:localhost:8080/hello url does not render and give index page
package login.example;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
#Controller
#ComponentScan
public class UserController {
#RequestMapping("/hello")
#ResponseBody
public String sayhii() {
return "index";
}
#Autowired
UserService userService;
#GetMapping("login-register/index")
public String index() {
return "index";
}
#GetMapping("/users")
public List<User> getAllUsers() {
return userService.getAllUsers();
}
#GetMapping("/user/{id}")
private User getUser(#PathVariable("id") long id) {
return userService.getUserById(id);
}
#DeleteMapping("/user/{id}")
public void deleteUser(#PathVariable("id") long id) {
userService.delete(id);
}
#PostMapping("/users")
public long saveUser(#RequestBody User user) {
userService.saveOrUpdate(user);
return user.getId();
}
#PutMapping("/users")
public User Update(#RequestBody User users) {
userService.saveOrUpdate(users);
return users;
}
}
this is usercontroller class,
how to work with this
i have added this in springboot main class
#Bean
public ServletRegistrationBean servletRegistrationBean() {
FacesServlet servlet = new FacesServlet();
return new ServletRegistrationBean(servlet, "*.xhtml");
}
added this in web.xml
<servlet>
<servlet-name>facesServlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>facesServlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.xhtml</welcome-file>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
and this in my index.xhtml file
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui">
now,it is working
and using this url http://localhost:8080/index.xhtml
I run the code on tomcat 8.0.39 and it first shows the login.jsp When I fill the name and password and hit submit it returns the 404 error:login.jsp image
HTTP Status 404 image
My code follows:
web.xml
<!-- webapp/WEB-INF/web.xml -->
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>To do List</display-name>
<welcome-file-list>
<welcome-file>login.do</welcome-file>
</welcome-file-list>
</web-app>
LoginServlet.java
package com.ezmsip;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(urlPatterns="/login.do")
public class LoginServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("WEB-INF/views/login.jsp").forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("name", request.getParameter("name"));
request.getRequestDispatcher("WEB-INF/views/welcome.jsp").forward(request, response);
}
}
login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hola desde una JSP</title>
</head>
<body>
<form action="/login.do" method="post">
Nombre: <input type="text" name="name" /> Password: <input type="password" name="password" /> <input type="submit" value="Log-in" />
</form>
</body>
</html>
welcome.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Bienvenido!</title>
</head>
<body>
Bienvenido! ${name}
</body>
</html>
Thanks!
It doesn't complain about login.jsp. It complains about /login.do. Did you deploy this app as the root web app in tomecat? Otherwise, it's under a context path, and you need your action to be something like /myWebApp/login.do.
In any case, the right thing to do is to prepend the context path:
action="${pageContext.request.contextPath}/login.do"
or, using the JSTL:
action="<c:url value='/login.do'/>"
I am very much new to developing java applications using Spring framework. I have previously developed applications using MVC architecture but this Spring is really killing me.
I mean I can't a get a single new thing right in less than hour. Anyway, I am stuck in a very common problem while handling forms. I have tried for hours, searched the web for my problem and none of them have worked. Is it something to do with Netbeans? I don't know.
index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form:form action="apptest.htm" commandName="userForm" method="POST">
Name:<form:input path="name" />
<br>
Age:<form:input path="age" />
<br>
City:<form:input path="city" />
<br>
<input type="submit" value="Submit">
<br>
</form:form>
</body>
</html>
InsertController.java
package SpringApp.Controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.portlet.ModelAndView;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import SpringApp.DAO.PeopleDAO;
import SpringApp.DAO.People;
import java.util.Map;
import org.springframework.web.bind.annotation.ModelAttribute;
#Controller
#RequestMapping("/apptest.htm")
/**
*
* #author ROHAN
*/
public class InsertController {
#RequestMapping(method = RequestMethod.GET)
public String viewRegistration(Map<String, Object> model) {
People userForm = new People();
model.put("userForm", userForm);
return "index";
}
#RequestMapping(method = RequestMethod.POST)
/*public String insertion(ModelMap modelMap) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("Beans.xml");
PeopleDAO dao=(PeopleDAO)ctx.getBean("people");
int status=dao.saveEmployee(new People("Kitty",22,"khardah"));
modelMap.put("msg2","success");
return "test";
}*/
public String processRegistration(#ModelAttribute(value="userForm") People people,
Map<String, Object> model) {
model.put("name",people.getName());
model.put("city",people.getCity());
return "test";
}
}
People.java (Bean class)
package SpringApp.DAO;
public class People {
private int id;
private String name;
private int age;
private String city;
public People()
{
super();
}
public People(String name,int age,String city)
{
this.name=name;
this.age=age;
this.city=city;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
#Override
public String toString() {
return "User [name=" + name + ", age=" + age+ ", city=" + city + "]";
}
}
dispatcher-servlet.xml
<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?xml version="1.0" encoding="UTF-8"?> -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<context:annotation-config />
<context:component-scan base-package="SpringApp" />
<mvc:annotation-driven />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
</beans>
index.jsp is my welcome page as configured in web.xml. Whenever I run the project, I get the following message:
29-Feb-2016 02:46:14.550 SEVERE [http-nio-8035-exec-183] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [jsp] in context with path [/SpringApp] threw exception [An exception occurred processing JSP page /index.jsp at line 17
14: </head>
15: <body>
16: <form:form action="apptest.htm" commandName="userForm" method="POST">
17: Name:<form:input path="name" />
18: <br>
19: Age:<form:input path="age" />
20: <br>
Stacktrace:] with root cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'userForm' available as request attribute
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:141)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:168)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:188)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:154)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.autogenerateId(AbstractDataBoundFormElementTag.java:141)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.resolveId(AbstractDataBoundFormElementTag.java:132)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.writeDefaultAttributes(AbstractDataBoundFormElementTag.java:116)
at org.springframework.web.servlet.tags.form.AbstractHtmlElementTag.writeDefaultAttributes(AbstractHtmlElementTag.java:422)
at org.springframework.web.servlet.tags.form.InputTag.writeTagContent(InputTag.java:142)
at org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:84)
at org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80)
at org.apache.jsp.index_jsp._jspx_meth_form_005finput_005f0(index_jsp.java:228)
at org.apache.jsp.index_jsp._jspx_meth_form_005fform_005f0(index_jsp.java:180)
at org.apache.jsp.index_jsp._jspService(index_jsp.java:134)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
My project structure is as follows:
Web pages
META-INF
WEB-INF
jsp
test.jsp
dispatcher-servlet.xml
applicationContext.xml
web.xml
index.jsp(outside WEB-INF)
Source Packages
Beans.xml
SpringApp.Controllers
InsertController
SpringApp.DAO
People.java
PeopleDAO.java
test.jsp
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%#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>
Name: ${userForm.name} <br>
City: ${userForm.city}
</body>
</html>
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'userForm' available as request attribute
As you can see from stacktrace index.jsp can't map model attribute to form parameters.
This happans because you have index.jsp in your <welcome-file-list>. So index.jsp is loaded before controller and don't have access to model values.
To solve this problem you have to:
move your index.jsp file to WEB-INF/jsp folder;
change <welcome-file-list> to this:
<welcome-file-list>
<welcome-file></welcome-file>
</welcome-file-list>
or delete this tag at all.
add "/" to #RequestMapping in InsertController class.
So, now your controller will process request, add value to model and pass it to index.jsp.
Below I posted full code.
InsertController
import SpringApp.DAO.People;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.Map;
#Controller
#RequestMapping({"/", "/apptest.htm"})
/**
*
* #author ROHAN
*/
public class InsertController {
#RequestMapping(method = RequestMethod.GET)
public String viewRegistration(Map<String, Object> model) {
People userForm = new People();
model.put("userForm", userForm);
return "index";
}
#RequestMapping(method = RequestMethod.POST)
public String processRegistration(#ModelAttribute(value="userForm") People people,
Map<String, Object> model) {
model.put("name",people.getName());
model.put("city",people.getCity());
return "test";
}
}
web.xml
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring MVC</display-name>
<description>Spring MVC</description>
<!-- For web context -->
<servlet>
<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>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
WEB-INF/application-context.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--<welcome-file-list>-->
<!--<welcome-file></welcome-file>-->
<!--</welcome-file-list>-->
</web-app>
it looks like your model attribute is not bind with request, make below change in your index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form:form action="apptest.htm" modelAttribute="userForm" method="POST">
Name:<form:input path="name" />
<br>
Age:<form:input path="age" />
<br>
City:<form:input path="city" />
<br>
<input type="submit" value="Submit">
<br>
</form:form>
</body>
</html>
Now be sure that you have a test.jsp having modelAttribute of People bean otherwise it will again cause of error.
I have created a web dynamic project using hibernate4 and spring4.
here are my files:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>posts</display-name>
<welcome-file-list>
<welcome-file>users.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application-context.xml</param-value>
</context-param>
</web-app>
here is the bean where I invoked init() method
package com.posts.beans;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.posts.models.Users;
import com.posts.services.UsersService;
#SuppressWarnings("serial")
#Component("Usersbean")
#Scope("session")
public class UsersBean implements Serializable{
#Autowired
private transient UsersService us;
private List<Users> lu;
public UsersBean() {
}
#PostConstruct
public void init(){
lu=us.getAllUsers();
System.out.println("hello");//doesn't shw up=init() doesnt work
}
public String getMyname(){
return "mohamed";
}
public List<Users> getLu() {
return lu;
}
public void setLu(List<Users> lu) {
this.lu = lu;
}
}
here is my jsp file ; I tried to show just one field:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%#taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="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=UTF-8">
<title>test list users</title>
</head>
<body>
<jsp:useBean id="users" class="com.posts.beans.UsersBean" />
<table border="1">
<tr><th>id</th><th>nom</th><th>prenom</th><th>login</th><th>password</th></tr>
</table>
<c:forEach var="user" items="${users.lu}">
<p><c:out value="${user.nom}" /></p>
</c:forEach>
</body>
</html>
so the console doesnt show the message "hello" in method init which means that id doesnt work.
maybe it is because that i didnt declare servlet element in web.xm, but i dont have any idea on how it works ..
NB: I tested Services With JUnit, worked fine
i have solved that problem with annotating UserBean class with #Service("userbean") and adding :
<bean id="usersBean" class="com.posts.beans.UsersBean" init-method="init" />
in application-context.xml file ..
when I run my application , i see hibernate generated code of SELECT and the message hello
Hello
Hibernate: select users0_.id as id1_2_, users0_.login as login2_2_, users0_.nom as nom3_2_, users0_.password as password4_2_, users0_.prenom as prenom5_2_ from public.users users0_
" in the console which means that init() method have been executed.
You can make it work in three different ways:
add to your application-context.xml bean that is responsible to work out #PostConstruct annotation:
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
add namespase that already has CommonAnnotationBeanPostProcessor inside:
<context:annotation-config />
or
<context:component-scan base-package="package.with.beans" /> <!-- scans components and adds <context:annotation-config /> -->
define init method in the tag bean of your class for argument "init-method"
I created a Spring MVC Project but the errors of form are not displayed .Why?
I try to create a simple form.This is the code of my Project.The project works but in jsp the error are not dispayed..Where did I go wrong?Thanks
Student.java
package coreservlets;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Student {
#Size(min=4,max=5,message="Size wrong")
#NotNull
private String name;
#Size(min=4,max=5,message="Size wrong")
#NotNull
private Integer age;
#Size(min=4,max=5,message="Size wrong")
#NotNull
private Integer id;
public String getName(){return name;}//getName
public void setName(String name){this.name=name;}//setName
public Integer getAge(){return age;}//getAge
public void setAge(Integer age){this.age=age;}//setAge
public Integer getId(){return id;}//getId
public void setId(Integer id){this.id=id;}//setId
}//Student
StudentController.java
package coreservlets;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class StudentController {
#RequestMapping(value="/",method=RequestMethod.GET)
public ModelAndView student(){
return new ModelAndView("student", "command", new Student());
}//student
#RequestMapping(value="/addStudent", method=RequestMethod.POST)
public String addStudent(#ModelAttribute #Valid Student student,ModelMap model){
model.addAttribute("name",student.getName());
model.addAttribute("age",student.getAge());
model.addAttribute("id",student.getId());
return "result";
}//addStudent
}//StudentController
student.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"%>
<!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>Spring MVC Form Handling</title>
</head>
<body>
<h2>Student Information</h2>
<form:form method="post" action="/SpringMVCFormExample/addStudent" >
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name"/></td>
<form:errors path="name" />
</tr>
<tr>
<td><form:label path="age">Age</form:label></td>
<td><form:input path="age"/></td>
<form:errors path="age" />
</tr>
<tr>
<td><form:label path="id">Id</form:label></td>
<td><form:input path="id"/></td>
<form:errors path="id" />
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form:form>
result.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"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted Student Information</h2>
<table>
<tr>
<td>Name</td>
<td>${name}</td>
</tr>
<tr>
<td>Age</td>
<td>${age}</td>
</tr>
<tr>
<td>Id</td>
<td>${id}</td>
</tr>
</table>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Spring MVC Form</display-name>
<servlet>
<servlet-name>SpringMVCForm</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVCForm</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
SpringMVCForm-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<context:component-scan base-package="coreservlets" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
Use BindingResult class as parameter in your method.
your method should look like this
public String addStudent(#ModelAttribute #Valid Student student,ModelMap model,BindingResult result)
Spring MVC will validate the model object annotated by the #Valid annotation after binding its properties with inputs from JSP form that uses Spring’s form tags. Any constraint violations will be exposed as errors in the BindingResult object, thus we can check the violation in the controller’s method like this:
if (result.hasErrors()) {
// form validation error
} else {
// form input is ok
}
The following code will return the user to the student form when a validation error occurs. When there is no validation error, the result template will be shown
#RequestMapping(value="/addStudent", method=RequestMethod.POST)
public String addStudent(#Valid Student student, BindingResult errors, Model model){
if (errors.hasErrors()) {
return "student";
}
model.addAttribute("name",student.getName());
model.addAttribute("age",student.getAge());
model.addAttribute("id",student.getId());
return "result";
}
You need to make sure that BindingResult errors is positioned exactly after #ModelAttribute #Valid Student student
Check out this and this tutorial for more info.
On another note, you should probably be redirecting the user after a successful POST. See this for more details
If you set the validation at model level you should use BindingResult:
#RequestMapping(value="/addStudent", method=RequestMethod.POST)
public String addStudent(#ModelAttribute #Valid Student student,ModelMap model,BindingResult errors){
if (errors.hasErrors()) {
List<FieldError> lerr = errors.getFieldErrors();
for (FieldError err: lerr) {
// manage the errorrs
}
}
model.addAttribute("name",student.getName());
model.addAttribute("age",student.getAge());
model.addAttribute("id",student.getId());
return "result";
}
if you want to handle validation at client level you can jquery.validate.js.