Spring application getting null values on browser - spring-mvc

This is the web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app id = "WebApp_ID" version = "3.0"
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_3_0.xsd">
<display-name>First spring project</display-name>
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
This is spring-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.wasik.controller"></context:component-scan>
<mvc:annotation-driven/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
This the controller I am using annotations in that
package com.wasik.controller;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class mycontroller {
#RequestMapping(value="/admissionForm.html" , method=RequestMethod.GET)
public ModelAndView display(){
ModelAndView view=new ModelAndView("AdmissionForm");
return view;
}
#RequestMapping(value="/submitAdmissionForm", method=RequestMethod.POST)
public ModelAndView Success(#PathVariable Map<String, String>map) {
ModelAndView view =new ModelAndView ("AdmissionSuccess");
String name=map.get("name");
String password=map.get("password");
view.addObject("msg","hi "+name+ password);
return view;
}
}
After that I am taking the two values like username and password
addmissionForm.jsp
<form action="/springWithFormValidation/submitAdmissionForm" method="POST">
Name<input type="text" name="name">
password<input type="test" name="password">
<input type="submit" value="submit">
</form>
and finally population on the browser
admissionSuccess.jsp
<p> successfully registered with following details</p>
<h2> ${msg}</h2>

Related

Spring MVC Form Validation not validating

Trying to apply MVC Spring Validation to my web project. I think I have everything configured properly, but my form is not being validated.
I am not using Maven or Gradle. Rather, I am including the jar files I was told I needed by my tutorial in my build path.
The jar files are:
validation-api-1.1.0.Final.jar
hibernate-validator-5.0.1.Final.jar
I am following this tutorial: https://www.codejava.net/frameworks/spring/spring-mvc-form-validation-example-with-bean-validation-api
My config.xml file:
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<mvc:annotation-driven />
</beans>
My Model:
package bl;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
public class VendorValidation {
#NotEmpty
#Size(min = 1, message = "Field requires an entry")
private String vname;
#NotEmpty
private String vphone;
#NotEmpty
private String vemail;
#NotEmpty
private String vcity;
#NotEmpty
private String vstate;
#NotEmpty
private String vcountry;
#NotEmpty
private String vzipcode;
#NotEmpty
private String vtimezone;
public String getVname() {
return vname;
}
public void setVname(String vname) {
this.vname = vname;
}
public String getVphone() {
return vphone;
}
public void setVphone(String vphone) {
this.vphone = vphone;
}
public String getVemail() {
return vemail;
}
public void setVemail(String vemail) {
this.vemail = vemail;
}
public String getVcity() {
return vcity;
}
public void setVcity(String vcity) {
this.vcity = vcity;
}
public String getVstate() {
return vstate;
}
public void setVstate(String vstate) {
this.vstate = vstate;
}
public String getVcountry() {
return vcountry;
}
public void setVcountry(String vcountry) {
this.vcountry = vcountry;
}
public String getVzipcode() {
return vzipcode;
}
public void setVzipcode(String vzipcode) {
this.vzipcode = vzipcode;
}
public String getVtimezone() {
return vtimezone;
}
public void setVtimezone(String vtimezone) {
this.vtimezone = vtimezone;
}
}
My View:
<form:form method="post" id="va-form" action="insertVendor" modelAttribute="vendorValidation">
<div class="form-group">
<label>Vendor Name</label> <form:input type="text" path="vname" class="form-control"
id="nameForm" />
</div>
...
</form:form>
My Controller:
#RequestMapping(value = "vendorForm", method = RequestMethod.GET)
public String formView(ModelMap map, HttpServletRequest request) {
VendorValidation vendorValidation = new VendorValidation();
map.put("vendorValidation", vendorValidation);
return "vendorForm";
}
RequestMapping(value = "/insertVendor", method = RequestMethod.POST)
public String insertVendor(#Valid #ModelAttribute("vendorValidation") VendorValidation vendorValidation, BindingResult result,
HttpServletRequest request, ModelMap model) {
System.out.println("Found form errors: " + result.hasErrors());
if (result.hasErrors())
{
return "vendorForm";
}
else
{
// database logic
return "vendormanagement";
}
}
The BindingResult object does not contain any errors when attempting to submit the form and it should when I leave my fields empty. So the if (result.hasErrors()) does not fire and I get a database exception for trying to insert null values.
Download the Spring framework "-dist.zip" from here - https://repo.spring.io/release/org/springframework/spring/
Download hibernate ORM zip - https://sourceforge.net/projects/hibernate/files/hibernate-orm/5.4.2.Final/hibernate-release-5.4.2.Final.zip/download
Add jar from directory - hibernate-release-5.4.2.Final\lib\required
Download hibernate validator - https://sourceforge.net/projects/hibernate/files/hibernate-validator/6.0.16.Final/hibernate-validator-6.0.16.Final-dist.zip/download
Add jars present outside : hibernate-validator-6.0.16.Final\dist
Remember : Add all the jars to the classpath.
Now, I'm providing a sample code to demonstrate :
spring.xml or application-context.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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan
base-package="com.demo" />
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Add custom message resources -->
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames" value="resources/message"></property>
</bean>
</beans>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>project</display-name>
<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.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>
I think that this will solve your problem.

SpringMVC error to run jsp

I have a problem with the following code.
When I run mobile/menu it works, but when I run mobile/Home, with a
jsp in WEB-INF/views/Menu.jsp, it doesn't work.
Can anyone help me to find the mistake?
Thanks in advance.
My Controller
#RestController
#RequestMapping(value="/mobile")
public class UsersController {
#Autowired
UsersService userServices;
#RequestMapping(value="/menu", method=RequestMethod.POST, headers="Accept=application/json")
public #ResponseBody Map<String,Object> getMenu(mng_menu menu){
Map<String,Object> map = new HashMap<String,Object>();
List<mng_menu> list = userServices.listaMenu();
if (list != null){
map.put("status","200");
map.put("message","Data found");
map.put("data", list);
}else{
map.put("status","404");
map.put("message","Data not found");
}
return map;
}
#RequestMapping(value="/Home", method = RequestMethod.GET, headers="Accept=application/json")
public ModelAndView Home(){
ModelAndView view =new ModelAndView("Menu");
return view;
}
My SpringMVC-servlet
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
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>SpringMVC</display-name>
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/mobile/Home</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/mobile/menu</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

Using Spring3.2 MVC with embedded jetty9

I am trying to implement an embedded jetty server using spring mvc for dispatching. I tried several tutorials but monstyl they are out of date or don't use embedded jetty.
So far I created a new spring mvc project from scratch in intellij idea.
src/
main/
java/
com.springapp.mvc/
HelloController.java
Launcher.java
webapp/
WEB-INF/
mvc-dispatcher-servlet.xml
web.xml
pom.xml
HelloController.java
#Controller
#RequestMapping("/")
public class HelloController {
#RequestMapping(method = RequestMethod.GET)
public String printWelcome(ModelMap model) {
model.addAttribute("message", "Hello world!");
return "hello";
}
}
Launcher.java
public class Launcher {
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
//todo: implementation to use dispatcher-servlet...
server.start();
server.join();
}
}
mvc-dispatcher-servlet.xml
<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"
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.xsd">
<context:component-scan base-package="com.springapp.mvc"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
web.xml
<web-app 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 Application</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
How do I tell the server correctly to use the dispatcher servlet?
I tried a few things out but nothing really worked yet.
The solution for everyone who is also interested... (in scala not in java)
val server: Server = new Server(8080)
private val root: WebAppContext = new WebAppContext
root.setContextPath("/")
root.setDescriptor("src/main/webapp/web.xml")
root.setResourceBase("src/main/webapp/"))
root.setParentLoaderPriority(true)
server.setHandler(root)
server.start()
server.join()

No thread-bound request found in Spring MVC

I m building an app using Spring mvc and I am trying to access an http request from a bean outside the scope of the DispatcherServlet. I read similar posts and figured out that I need to add the RequestContextListener. However I keep getting the same error .Below you can see the controller and the bean I m injecting to the controller:
#Controller
public class ChargeController {
// Injected bean
#Autowired
public StripeCharger stripeCharger;
#RequestMapping(value = "/stripecharge", method = RequestMethod.POST)
public String chargeStripe(ModelMap model) {
// user`s custom code
String response = stripeCharger.charge();
}
}
part of the web.xml
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
The injected bean
package com.controller;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.stripe.Stripe;
import com.stripe.exception.StripeException;
import com.stripe.model.Charge;
public class StripeCharger {
public String token;
public StripeCharger()
{
HttpServletRequest curRequest = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
this.token = curRequest.getParameter("stripeToken");
}
}
-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<mvc:default-servlet-handler />
<mvc:annotation-driven />
<context:component-scan base-package="com.controller" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- This bean is auto-generated -->
<!-- define the bean to inject the Stripe charger -->
<bean id="StripeCharger" class="com.controller.StripeCharger" scope="request">
<aop:scoped-proxy/>
</bean>
</beans>
Anybody could help me with this issue? Thank you

spring mvc 3 No mapping found for HTTP request with URI

Error info: No mapping found for HTTP request with URI [/TestSpringWebApp/hello.htm]
Any help would be greatly appreciated!
I am using annotation to map request to controller.
controller code :
#Controller
#RequestMapping("/hello.htm")
public class HelloController {
protected final Log logger = LogFactory.getLog(getClass());
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String now = (new Date()).toString();
logger.info("Returning hello view with " + now);
return new ModelAndView("hello", "now", now);
}
}
Dispatcher-servlet.xml as follows:
<?xml version="1.0" encoding="UTF-8"?>
<beans ...>
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<!--
Most controllers will use the ControllerClassNameHandlerMapping above, but
for the index controller we are using ParameterizableViewController, so we must
define an explicit mapping for it.
-->
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.htm">indexController</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<!--
The index controller.
-->
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
<!-- <bean name="/hello.htm" class="com.kibboko.poprocks.web.HelloController"/>-->
</beans>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans ...>
<!--bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}" /-->
<!-- ADD PERSISTENCE SUPPORT HERE (jpa, hibernate, etc) -->
</beans>
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans ...>
<!--bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}" /-->
<!-- ADD PERSISTENCE SUPPORT HERE (jpa, hibernate, etc) -->
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app ...>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>
</web-app>
You also need to add
<mvc:annotation-driven />
to your Dispatcher-servlet.xml file.
You have to add #RequestMapping to the method, not to the class. If you add it to the class it will be applied as a prefix to all the methods mapping of this class, but you also have to map the methods of the class.
You can have #RequestMapping for class also, but every method also should have its own " #RequestMapping" please see below example.
#Controller
#RequestMapping("/appointments")
public class AppointmentsController {
private final AppointmentBook appointmentBook;
#Autowired
public AppointmentsController(AppointmentBook appointmentBook) {
this.appointmentBook = appointmentBook;
}
#RequestMapping(method = RequestMethod.GET)
public Map<String, Appointment> get() {
return appointmentBook.getAppointmentsForToday();
}
#RequestMapping(value="/{day}", method = RequestMethod.GET)
public Map<String, Appointment> getForDay(#PathVariable #DateTimeFormat(iso=ISO.DATE) Date day, Model model) {
return appointmentBook.getAppointmentsForDay(day);
}
#RequestMapping(value="/new", method = RequestMethod.GET)
public AppointmentForm getNewForm() {
return new AppointmentForm();
}
#RequestMapping(method = RequestMethod.POST)
public String add(#Valid AppointmentForm appointment, BindingResult result) {
if (result.hasErrors()) {
return "appointments/new";
}
appointmentBook.addAppointment(appointment);
return "redirect:/appointments";
}
}

Resources