Execution of Struts basic application getting java.lang.NoSuchMethodException - java

I'm new to struts framework. So seeking some online tutorials and tried to develop a very basic application. But I'm unable to run it properly
after clicking button action method "execute()" was unable to locate
by container.
I am not getting what I'm missing.
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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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>SampleApplication</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>sample</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>sample</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!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>Sample Struts Application</title>
</head>
<body>
<s:form action="invoke">
<s:textfield name="name" label="UserName"></s:textfield><br>
<s:password name="password" label="Password"></s:password><br>
<s:submit value="GO"></s:submit>
</s:form>
</body>
</html>
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="invoke" class="com.techm.SampleStruts" method="execute">
<result name="success">/Success.jsp</result>
</action>
</package></struts>
SampleStruts.java
import com.opensymphony.xwork2.ActionSupport;
public class SampleStruts extends ActionSupport{
private static final long serialVersionUID = 1L;
String name, password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String execute()
{
return "success";
}
}
Jars used are :
commons-logging-1.0.4.jar
freemarker-2.3.8.jar
ognl-2.6.11.jar
servlet-api-2.5.jar
struts2-core-2.0.11.jar
StrutsInterceptors.rar
xwork-2.0.4.jar
Stack trace :
java.lang.NoSuchMethodException: com.techm.SampleStruts.execute()
at java.lang.Class.getMethod(Unknown Source)
at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.getActionMethod(AnnotationValidationInterceptor.java:55)
at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:41)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:86)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:123)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:167)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:86)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:105)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:83)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)

Finally i found the solution is that , after adding .action to the action value.
it is working fine.
<s:form action="invoke.action">
<s:textfield name="name" label="UserName"></s:textfield><br>
<s:password name="password" label="Password"></s:password><br>
<s:submit value="GO"></s:submit>

Related

Struts2 with maven no Action mapped for namespace and action name associated with context path

Although it is a common problem but I cannot figure it out.
I am running Strut2 with maven project. My project structure is given bellow
is
Product.java
package beans;
public class Product {
private int id;
private String name;
private float price;
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 float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
ProductAction.java
package actions;
import beans.Product;
public class ProductAction{
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
private Product product;
public String execute(){
return "success";
}
}
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts
Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<action name="product" class="actions.ProductAction" method="execute">
<result name="success">welcome.jsp</result>
</action>
</package>
</struts>
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
index.jsp
<html>
<body>
<h2>Hello World!</h2>
<div>
<%# taglib uri="/struts-tags" prefix="s" %>
<s:form action="product">
<s:textfield name="product.id" label="Product Id"></s:textfield>
<s:textfield name="product.name" label="Product Name"></s:textfield>
<s:textfield name="product.price" label="Product Price"></s:textfield>
<s:submit value="save"></s:submit>
</s:form>
</div>
</body>
</html>
and welcome.jsp
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title></title>
</head>
<body>
<%# taglib uri="/struts-tags" prefix="s" %>
Product Id:<s:property value="id"/><br/>
Product Name:<s:property value="name"/><br/>
Product Price:<s:property value="price"/><br/>
</body>
</html>
I am using Glassfish server. It runs index.jsp well. But when I fill the form and submit it shows
HTTP Status 404 - There is no Action mapped for namespace [/] and
action name [product] associated with context path [/deploytest].
type Status report
messageThere is no Action mapped for namespace [/] and action name
[product] associated with context path [/deploytest].
descriptionThe requested resource is not available.
GlassFish Server Open Source Edition 4.1.1
My pom.xml has dependency
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.3.28</version>
</dependency>

Struts2 login error with MySQL

I have created a simple login application for Struts2 but I can't login with a local MySQL database. My code is the following:
login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
</head>
<body>
<s:form action="loginprocess">
<s:textfield name="username" label="Username"></s:textfield>
<s:password name="password" label="Password"></s:password>
<s:submit cssStyle="float:left;" value="Login"></s:submit>
</s:form>
</body>
</html>
loginerror.jsp
<%# 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>Login</title>
</head>
<body>
Sorry username or password error!
<jsp:include page="login.jsp"></jsp:include>
</body>
</html>
main.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="/struts-tags" prefix="s" %>
<!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>My Page</title>
</head>
<body>
<h2>Welcome!</h2>
</body>
</html>
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD
Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="loginprocess" class="com.login.struts2.LoginTest">
<result name="success">main.jsp</result>
<result name="error">loginerror.jsp</result>
</action>
</package>
</struts>
LoginDao.java
package com.login.struts2;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class LoginDao {
public static boolean validate(String username, String password){
boolean status=false;
Connection conn = null;
try
{
String URL = "jdbc:mysql://localhost:3306/struts_register2";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(URL, "root", "1235");
PreparedStatement ps=conn.prepareStatement("select * from test where username=? AND password=?");
ps.setString(1,username);
ps.setString(2,password);
ResultSet rs = ps.executeQuery();
status = rs.next();
}
catch(Exception e){e.printStackTrace();}
return status;
}
}
LoginTest.java
package com.login.struts2;
public class LoginTest {
private String username,password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserpass() {
return password;
}
public void setUserpass(String password) {
this.password = password;
}
public String execute(){
if(LoginDao.validate(username, password)){
return "success";
}
else{
return "error";
}
}
}
web.xml
<?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">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
If I try to change the query at LoginDao.java, by having OR instead of AND, it redirects me to main.jsp. I can't find a solution.My database has the fields with "test" (VARCHAR(10) for username and password. Any ideas?
The input field for the password has a name password.
<s:password name="password" label="Password"></s:password>
Then the setter should be the same name.
public void setPassword(String password) {
this.password = password;
}
In this way the parameter will be populated and you will not have null value.

Struts 2, Error 404

I have tried many things, but not able to solve the issue of Error 404 while I click the submit button of the HR form. I need to get redirected to the output.jsp page as soon as I submit the form of HR. Can anyone help?
Web.Xml
<?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">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>input.jsp</welcome-file>
</welcome-file-list>
</web-app>
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="default" extends="struts-default">
<action name="output" class="com.vcm.login.LoginAction" method="execute">
<result name="success">/output.jsp</result>
<result name="input">/input.jsp</result>
</action>
</package>
</struts>
LoginAction.java
package com.vcm.login;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
private String username;
private String password;
private String message;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String execute(){
if(username.equals("jyotsna")&& password.equals("jyotsna")){
return Action.SUCCESS;
}
else{
addActionError("NOT a VALID user");
return Action.LOGIN;
}
}
public void validate(){
if((username==null) || (username.trim().equals("")))
addFieldError("username","ID cannot be blank");
if(password==null || password.trim().equals(""))
addFieldError("password","password incorrect");
}
}
Input.jsp
<%# 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>
<table style="align:center">
<tr>
<td width="25%" style="background-color:#33CCFF">
<form action="output">
<p style="color:white"><b><i>HR LOGIN</i></b></p><br>
HR id:<input type="text" name="username" value="" /><br><br>
Psswd:<input type="password" name="password" value="" /><br><br>
<input type="submit" value="login">
</form>
</td>
<td width="70%">
<img src="https://assets.dice.com/external/images/empLogos/6fccd30f19c09f1afee9414a18 5fde3d.jpg" height="100%" width="100%"></td>
<td width="25%" style="background-color:#33CCFF">
<form method="post" action=" ">
<p style="align:center;color:white"><b><i>EMPLOYEE LOGIN</i></b></p><br>
Emp id:<input type="text" name="id" value="" /><br><br>
Psswd :<input type="password" name="psswd" value="" /><br><br>
<input type="submit" value="login">
</form>
</td>
</tr>
</table>
</body>
</html>
Output.jsp
<%# 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>output</title>
</head>
<body>
<p>
Page of a HR
</p>
</body>
</html>
Use the struts tags.
Load them by adding this at the beginning:
<%# taglib prefix="s" uri="/struts-tags" %>
Use them like this:
<s:form action="output" method="post">
<s:textfield key="username" label="HR id:" />
<s:textfield key="password" label="Psswd:" />
<s:submit type="button">login</s:submit>
</s:form>
Alter the layout by switching/altering the struts ui theme and by using css.

404 page when running project through eclipse on Tomcat

Using Struts2 , I have set up a very simplistic webapp but when i run it in eclipese i got 404 error.. here is my all codes and jarfiles
URL : localhost:8985/firststruts/index.jsp
Jar files
commons-fileupload-1.3.1
commons-io-2.2
commons-lang-2.4
commons-logging-1.1.3
commons-logging-api-1.1
freemarker-2.3.19
javassist-3.11.0.GA
ognl-3.0.6
struts2-core-2.3.16.3
xwork-core-2.3.16.3
Struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts
Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="Product" class="com.javatpoint.Product">
<result name="success">welcome.jsp</result>
</action>
</package>
</struts>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<display-name>firstjsp</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*</url-pattern>
</filter-mapping>
</web-app>
product.java
public class Product {
private int id;
private String name;
private float price;
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 float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String execute() {
return "success";
}
}
welcome.jsp
<%# taglib uri="/struts-tags" prefix="s" %>
Product Id:<s:property value="id"/><br/>
Product Name:<s:property value="name"/><br/>
Product Price:<s:property value="price"/><br/>
index.java
<%# taglib uri="/struts-tags" prefix="s" %>
<s:form action="product">
<s:textfield name="id" label="Product Id"></s:textfield>
<s:textfield name="name" label="Product Name"></s:textfield>
<s:textfield name="price" label="Product Price"></s:textfield>
<s:submit value="save"></s:submit>
</s:form>
im new to struts2 so please help me to solve this.

Spring MVC 3 Validator not displaying Error Message

I have problem with displaying error message in spring Application.i am using Spring MVC 3 and Apache Tiles. when i am having error in form than it will not displays error message.
please help me hear is the piece of code.
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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>SpringExample</display-name>
<welcome-file-list>
<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>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/dispatcher-servlet.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
dispatcher-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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.examples.spring" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles2.TilesView
</value>
</property>
</bean>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
</beans>
tiles.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
"http://tiles.apache.org/dtds/tiles-config_2_0.dtd">
<tiles-definitions>
<definition name="create_account_success" template="/WEB-INF/jsp/account/SuccessJSP.jsp">
</definition>
<definition name="account_create" template="/WEB-INF/jsp/account/testForm.jsp">
</definition>
</tiles-definitions>
testForm.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/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>Insert title here</title>
</head>
<body>
<form:form id="form" modelAttribute="formCreate" method="post">
<table>
<tr>
<td>Name :</td>
<td><form:input path="name"/>
<form:errors path="name"/>
</td>
</tr>
<tr>
<td>Password :</td>
<td><form:input path="password"/>
<form:errors path="password"/>
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
AccountRegistrationController.java
package com.examples.spring.controller;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
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;
import com.examples.spring.dto.AccountDTO;
import com.examples.spring.validator.AccountValidator;
#Controller
public class AccountRegistrationController {
public static final String BASE_URL = "/account";
#RequestMapping(value = BASE_URL + "/create" ,method = RequestMethod.GET)
public ModelAndView accountCreate(){
ModelAndView view = new ModelAndView();
view.addObject("formCreate", new AccountDTO());
view.setViewName("account_create");
return view;
}
#RequestMapping(value = BASE_URL + "/create" ,method = RequestMethod.POST)
public ModelAndView accountRegistration(#ModelAttribute AccountDTO accountDTO,BindingResult result ){
ModelAndView view = new ModelAndView();
AccountValidator validator = new AccountValidator();
validator.validate(accountDTO, result);
if (result.hasErrors()) {
view.setViewName("account_create");
view.addObject("formCreate", accountDTO);
return view;
}
view.setViewName("create_account_success");
return view;
}
#RequestMapping(value = BASE_URL + "/login" ,method = RequestMethod.GET)
public ModelAndView accountLogin(){
ModelAndView view = new ModelAndView();
view.setViewName("account_login");
return view;
}
}
AccountValidator.java
package com.examples.spring.validator;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.examples.spring.dto.AccountDTO;
public class AccountValidator implements Validator {
#Override
public boolean supports(Class<?> clazz) {
return AccountDTO.class.isAssignableFrom(clazz);
}
#Override
public void validate(Object result, Errors error) {
AccountDTO accountDTO = (AccountDTO) result;
ValidationUtils.rejectIfEmpty(error, "name", "require.name", "Name Requires.");
ValidationUtils.rejectIfEmpty(error, "password", "require.password", "Password Requires.");
}
}
AccountDTO.java
package com.examples.spring.dto;
public class AccountDTO {
private String name;
private String password;
public AccountDTO() {
// TODO Auto-generated constructor stub
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
My Code is working well but it does not displays error messages in <form:errors />.
please help me.
The third parameter to ValidationUtils.rejectIfEmpty is an error code. It should be a key to the actual message in your resource bundle. I don't know how it behaves if it can't find a value. You should change it to use a key, and optionally set a default message. See the api.
You need to register your validator with the controller in which you want to use it. See: http://static.springsource.org/spring/docs/3.0.0.RC3/reference/html/ch05s07.html#validation.mvc

Categories