Spring MVC Controller working but not creating the specified response URL ,It is creating the url from request mapping string - spring

I am studying spring MVC based webapps. So I created a project in spring mvc and I have chosen eclipse IDE.Apache tomcat 8 server and jre1.8 the version of spring package is 4.2.5. In my project I created the login and that worked fine after login the I redirected the page to another jsp called 'branchinsert.jsp' that placed in an another folder (login.jsp and branchinsert.jsp are from different folders). In Branchinsert.jsp Spring MVC Controller is working but not create the specified response URL ,It is creating the url from request mapping string that means if I am giving the pattern like bellow mentioned,
#RequestMapping(value="/branchsubmitinsert.travel", method=RequestMethod.POST)
public ModelAndView submitBranchInsert(#ModelAttribute BranchModel branchModel){
ModelAndView modelAndView = new ModelAndView("/branch/branchinsert");
return modelAndView;
}
showing 404 error for the url /ProjectName/modules/branch/branchsubmitinsert.jsp
Actually the url i expected is /branch/branchinsert.jsp(this is what usually happens) but here created /branch/branchsubmitinsert.jsp url. why????
this is my code
web.xml
<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>CalicutTravels</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>
<listener><listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
ApplicationContext.xml
<?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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.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.classes.controller">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
spring-dispatcher-servlet.xml
<?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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.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:annotation-config />
<context:component-scan base-package="com.classes.controller">
</context:component-scan>
<mvc:annotation-driven/>
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/modules/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<!-- declare beans -->
<bean id="userDaoImplementation"
class="com.classes.dao.login.UserDaoImplementation" />
<bean id="userServiceImplementation"
class="com.classes.service.login.UserServiceImplementation" />
<!-- declare datasource bean "jdbc:postgresql://hostname:port
/dbname","username", "password");-->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432
/db_enterpricer_travel" />
<property name="username" value="vishnu" />
<property name="password" value="root" />
</bean>
</beans>
branchinsert.jsp's form field
<form action='branchsubmitinsert.travel' id='brach_submit' method='post' >
<fieldset class="well the-fieldset">
<legend class="the-legend"> INSERT </legend>
<table>
<tr>
<th> Branch Name :</th>
<td> <input type="text" name='branchName' id='branchName' /></td>
</tr>
<tr>
<td colspan="2" align="right"><input type="button" class="btn btn-default" value='INSERT' onclick='return validateBranchInsert()'/></td>
</tr>
</table>
</fieldset>
</form>
The controller class BranchController.java
package com.classes.controller.branch;
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 org.springframework.web.portlet.ModelAndView;
import com.classes.service.branch.BranchModel;
/**
* #author vishnu
*
*/
#Controller
#RequestMapping("/branch")
public class BranchController {
#RequestMapping(value="/branchinsert.travel", method=RequestMethod.GET)
public ModelAndView getBranchInsert(){
ModelAndView modelAndView = new ModelAndView("/branch/branchinsert");
return modelAndView;
}
#RequestMapping(value="/branchupdate.travel", method=RequestMethod.GET)
public ModelAndView getBranchUpdate(){
ModelAndView modelAndView = new ModelAndView("/branch/branchupdate");
return modelAndView;
}
#RequestMapping(value="/branchshow.travel", method=RequestMethod.GET)
public ModelAndView getBranchShow(){
ModelAndView modelAndView = new ModelAndView("/branch/branchshow");
return modelAndView;
}
#RequestMapping(value="/branchdelete.travel", method=RequestMethod.GET)
public ModelAndView getBranchDelete(){
ModelAndView modelAndView = new ModelAndView("/branch/branchdelete");
return modelAndView;
}
#RequestMapping(value="/branchsubmitinsert.travel",
method=RequestMethod.POST)
public ModelAndView submitBranchInsert(#ModelAttribute BranchModel
branchModel){
ModelAndView modelAndView = new ModelAndView("/branch/branchinsert");
modelAndView.addObject("branch",branchModel);
return modelAndView;
}
}

I changed the return type of method submitBranchInsert as String as follows
#RequestMapping(value="/branchsubmitinsert.travel", method=RequestMethod.POST)
public String submitBranchInsert(ModelMap model,#ModelAttribute BranchModel branchModel){
//ModelAndView modelAndView = new ModelAndView("/branch/branchinsert");
//modelAndView.addObject("branch",branchModel);
//return modelAndView;
model.addAttribute("branch", branchModel);
return "/branch/branchinsert";
}
now its ok but why i can't use ModelAndView here instead of Model in String ,
may be my sound dumb to the experts in Spring MVC.
I just want to know when should use ModelAndView instead of Model in String?
I don't want to ask this question as separately that is why I am asking this with my answer itself.
anybody can help me?

Since you mentioned modules folder in the prefix of viewResolver it is working like that..
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/modules/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
Which means return "branch/branchInsert" will find jsp in /modules/branch/branchInsert.jsp.
If you use just string to return means it's just an path from the jsp where you are sending the requset.So for that viewResolver wont add prefix folder.
But if you use ModelAndView the viewResolver will add the prefix and suffix.

Related

Spring MVC - 404 - The origin server did not find a current representation

Im trying to deploy a Spring MVC web app.
I want to redirect my index.jsp to another .jsp but i get this error.
HTTP Status 404 – Not Found
--------------------------------------------------------------------------------
Type Status Report
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
My project Struture:
src/main/java
com.example.beans
com.example.controller
com.example.dao
src/main/webapp/
WEB-INF
/jsp
test.jsp
spring-servlet.xml
web.xml
index.jsp
spring-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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Provide support for component scanning -->
<context:component-scan
base-package="com.example />
<!--Provide support for conversion, formatting and validation -->
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**"
location="/resources/" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="ds"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver"></property>
<property name="url"
value="jdbc:mysql://localhost:3306/dbexample></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="dao" class="com.example.dao.ObjectDao">
<property name="template" ref="jt"></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://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>Example</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Controller
#Controller
public class MainController {
#RequestMapping("hello")
public String redirect() {
return "viewpage";
}
#RequestMapping("/")
public String display() {
return "index";
}
#RequestMapping("test")
public String test() {
return "test";
}
index.jsp
<html>
<body>
<h2>Hello World!</h2>
View test
Click here...
</body>
</html>
When i clik on test I get this error in the sts log:
org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping for GET /example/hello
You should use '/' for mapping for your controllers.
You could try this:
#RequestMapping("/example/hello")
public String redirect() {
return "viewpage";
}
And it's better to use relative path for links:
View test
Click here...
More about pageContext see this

HTTP Status 404 - /FitnessTracker/delete/1

I'm working on Spring MVC + Hibernate + JSP example. In this example I've developed below screen and delete button which I want to delete the populated record.
When I'm clicking on delete link, its says HTTP Status 404 - /FitnessTracker/delete/1. I am really not understanding what is wrong here.
MinutesController.java
#Controller
public class MinutesController {
#Autowired
private ExerciseService exerciseService;
#RequestMapping(value = "/addMinutes", method = RequestMethod.GET)
public String getMinutes(#ModelAttribute ("exercise") Exercise exercise, ModelMap model) {
List<Exercise> exercises = exerciseService.findAll();
model.addAttribute("exercises", exercises);
return "addMinutes";
}
#RequestMapping(value = "/addMinutes", method = RequestMethod.POST)
public String addMinutes(#Valid #ModelAttribute ("exercise") Exercise exercise, BindingResult result, ModelMap model ) {
// check if there are any errors
if(result.hasErrors()) {
return "addMinutes";
}
// save the new Exercise
exerciseService.save(exercise);
// return all saved exercises
List<Exercise> exercises = exerciseService.findAll();
model.addAttribute("exercises", exercises);
return "addMinutes";
}
#RequestMapping(value = "/activities", method = RequestMethod.GET)
public #ResponseBody List<Activity> findAllActivities() {
return exerciseService.findAllActivities();
}
#RequestMapping(value = "/delete/{exerciseId}",method = RequestMethod.GET)
public String deleteActivity(#PathVariable("exerciseId") Long exerciseId) {
exerciseService.deleteExercise(exerciseId);
return "redirect:/activities";
}
}
addMinutes.jsp
<form:form commandName="exercise">
<form:errors path="*" cssClass="errorblock" element="div" />
<h4>View All Exercises</h4>
<table align="left" border="1" cellpadding="10">
<tr>
<th><b>Minutes</b></th>
<th><b>Activity</b></th>
<th><b>Delete</b></th>
</tr>
<c:forEach var="exercise" items="${exercises}">
<tr>
<td>${exercise.minutes}</td>
<td>${exercise.activity}</td>
<td><a href="<c:url value='/delete/${exercise.exerciseId}' />" >Delete</a></td>
</tr>
</c:forEach>
</table>
</form:form>
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">
<servlet>
<servlet-name>fitTrackerServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/servlet-config.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>fitTrackerServlet</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>fitTrackerServlet</servlet-name>
<url-pattern>/pdfs/**</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>fitTrackerServlet</servlet-name>
<url-pattern>/images/**</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>fitTrackerServlet</servlet-name>
<url-pattern>*.json</url-pattern>
</servlet-mapping>
<display-name>Archetype Created Web Application</display-name>
</web-app>
servlet-config.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"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
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/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<import resource="classpath:spring/database.xml"/>
<mvc:annotation-driven/>
<context:annotation-config />
<context:component-scan base-package="com.pluralsight"/>
<!-- For Static Resources -->
<mvc:resources location="assets" mapping="/assets/**"/>
<mvc:resources location="pdfs" mapping="/pdfs/**"/>
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<property name="contentNegotiationManager">
<bean class="org.springframework.web.accept.ContentNegotiationManager">
<constructor-arg>
<bean class="org.springframework.web.accept.PathExtensionContentNegotiationStrategy">
<constructor-arg>
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</map>
</constructor-arg>
</bean>
</constructor-arg>
</bean>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView" />
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.xstream.XStreamMarshaller">
<property name="autodetectAnnotations" value="true" />
</bean>
</constructor-arg>
</bean>
</list>
</property>
</bean>
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" p:paramName="language"/>
</mvc:interceptors>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" p:defaultLocale="en"/>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource"
p:basename="messages"></bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" p:order="2"/>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" p:order="0"/>
</beans>

Spring mvc - form:checkboxes dont bring me items

I am using form:checkboxes and isn't working. I can check the items in the html and when i put submit, debbuging, i see the items i had checked arent in the list of my form, the list is empty
Form
public class PresupuestoForm {
private long id;
private List<ItemVenta> elementos;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public List<ItemVenta> getElementos() {
return elementos;
}
public void setElementos(List<ItemVenta> elementos) {
this.elementos = elementos;
}
Controller
#RequestMapping(value = "/manageStock", method = RequestMethod.GET)
public ModelAndView controlarStockParaPasarAVenta(#RequestParam("getItem") long id){
try{
Presupuesto p = this.presupuestoService.getPresupuesto(id);
PresupuestoForm form = new PresupuestoForm();
form.setId(p.getId());
List<ItemVenta> elementos = new ArrayList<ItemVenta>();
getItemsFromPresupuesto(p, elementos); // Method that fill the list elementos with some items
ModelAndView m = new ModelAndView("manageStock");
m.addObject("command",form);
m.addObject("elementos",elementos);
return m;
}catch(Exception e){
...
}
}
#RequestMapping(value = "/manageStockForm", method = RequestMethod.POST)
public Object manageStockPresupuestoForm(#ModelAttribute("manageStockForm") PresupuestoForm form, BindingResult result){
Presupuesto p = null;
try{
p = this.presupuestoService.getPresupuesto(form.getId());
for(ItemVenta i : form.getElementos()){
}
return "redirect:becomeVenta.html?getItem="+form.getId();
}catch(BussinesException e){
...
}catch(Exception e){
...
}
}
HTML
<table>
<tr style="display: none;">
<td><form:input path="id"/></td>
</tr>
<tr>
<td><div class="texto">
<form:checkboxes path="elementos" items="${elementos}" itemLabel="itemName" />
</div></td>
</tr>
<tr>
<td>
<input class="linkboton" type="submit" value="Submit"/>
</td>
</tr>
</table>
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_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>SpringTiles</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
View Resolver
<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-context3.0.xsd">
<context:component-scan base-package="controllers" />
<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>
ItemVenta Mapping
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD3.0//EN"
"http://hibernate.sourceforge.n/hibernate-mapping-3.0.dtd">
<hibernate-mapping default-access="field" default-cascade="save-update">
<class name="ventas.ItemVenta">
<id column="id" name="id">
<generator class="native" />
</id>
<property name="precio" />
<property name="nombre" />
<property name="cantidad" />
<property name="idItem" />
<property name="tipo" />
</class>
</hibernate-mapping>
My form:checkboxes had to go over a list of entitys (ItemVenta) and save in the form's list elementos the entitys i checked. i googled answers and i found that i needed to add the method equals to my entity. It didn´t work. So intead of save entitys in the form´s list, now am i saving the ids of those entitys and it worked. I still go over a list of entitys.

Spring Hibernate integration with maven and mysql

I need to have a project with spring hibernate and mysql, the homepage works fine (it even gets data out from mysql and displays it) but when i click the add/edit or delete button i get a 404 error with the description The request sent by the client was syntactically incorrect.
My student Controller.java
package com.joseph.controller;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
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.bind.annotation.RequestParam;
import com.joseph.model.Student;
import com.joseph.service.StudentService;
#Controller
public class StudentController {
#Autowired
private StudentService studentService;
#RequestMapping("/index")
public String setupForm(Map<String, Object> map){
Student student = new Student();
map.put("student", student);
map.put("studentList", studentService.getAllStudent());
return "student";
}
#RequestMapping(value="/student.do", method=RequestMethod.POST)
public String doActions(#ModelAttribute Student student, BindingResult result, #RequestParam String action, Map<String, Object> map){
// System.out.println("inside doAction");
Student studentResult = new Student();
// System.out.println("after student object");
switch(action.toLowerCase()){//only in Java7 you can put String in switch
case "add":
studentService.add(student);
studentResult = student;
System.out.println("Inside case action value is - add");
break;
case "edit":
studentService.edit(student);
studentResult = student;
System.out.println("Inside case action value is - edit");
break;
case "delete":
studentService.delete(student.getStudentId());
studentResult = new Student();
System.out.println("Inside case action value is - delete");
break;
case "search":
Student searchedStudent = studentService.getStudent(student.getStudentId());
studentResult = searchedStudent!=null ? searchedStudent : new Student();
System.out.println("Inside case action value is - search");
break;
}
System.out.println("after switch");
map.put("student", studentResult);
map.put("studentList", studentService.getAllStudent());
return "student";
}}
My web.xml file is
<?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>CRUDWebAppMavenized</display-name>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:log4j.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>spring1</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring1</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<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>
My spring servlet.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:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<context:annotation-config />
<context:component-scan base-package="com.joseph" />
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
My spring1-servlet.xml file is
<?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:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<context:annotation-config />
<context:component-scan base-package="com.joseph" />
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
My student.jsp is
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# include file="/WEB-INF/jsp/includes.jsp"%>
<!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>Student Management</title>
</head>
<body>
<h1>Students Data</h1>
<form:form action="student.do" method="POST" commandName="student">
<table>
<tr>
<td>Student ID</td>
<td><form:input path="studentId" /></td>
</tr>
<tr>
<td>First name</td>
<td><form:input path="firstname" /></td>
</tr>
<tr>
<td>Last name</td>
<td><form:input path="lastname" /></td>
</tr>
<tr>
<td>Year Level</td>
<td><form:input path="yearLevel" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="action1" value="Add" />
<input type="submit" name="action2" value="Edit" />
<input type="submit" name="action3" value="Delete" />
<input type="submit" name="action4" value="Search" />
</td>
</tr>
</table>
</form:form>
<br>
<table border="1">
<th>ID</th>
<th>First name</th>
<th>Last name</th>
<th>Year level</th>
<c:forEach items="${studentList}" var="student">
<tr>
<td>${student.studentId}</td>
<td>${student.firstname}</td>
<td>${student.lastname}</td>
<td>${student.yearLevel}</td>
</tr>
</c:forEach >
</table>
</body>
</html>
Any help with this guys ?! I mean its able to connect to the database perectly fine i have no clue why the buttons are not working
I see following two problems:
First Issue:
In your controller, you use
#RequestMapping(value="/student.do", method=RequestMethod.POST)
but in your form you use
<form:form action="student.do" method="POST" commandName="student">
Shouldn't your form also use /student.do? Only reason I suspect this is because you have indicated that you get 404 (Page not found) error on trying to add/update.
Second Issue:
You use four submit buttons each with its own name
<input type="submit" name="action1" value="Add" />
<input type="submit" name="action2" value="Edit" />
<input type="submit" name="action3" value="Delete" />
<input type="submit" name="action4" value="Search" />
but, your controller method's #RequestParam assumes that you will get the value in one param.
public String doActions(#ModelAttribute Student student,
BindingResult result,
#RequestParam String action, //***THIS IS WRONG****
Map<String, Object> map){
First you should change it have a name:
#RequestParam("action") String action,
and, second add a hidden field (<input type="hidden" name="action" />) to carry the value of action to server and make sure that you update its value to "Add", "Edit", "Delete" or "Search" using Java Script by attaching on-click handlers to four action buttons.
Third Possible Cause of Concern:
Try to get rid of second dispatcher servlet, and use only one if possible. So, make the default one handle *.do as some people have faced issues when using two dispatcher servlet. I am sure it can be made to work but its difficult to pinpoint the error remotely using SO.
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
and, have all your #RequestMapping use .do, eg: index.do and student.do
This answer is based on what I can make out from the question.

error in xml files in spring mvc

I have three xml files for the spring project as follows
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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema
/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema
/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema
/util/spring-util-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema
/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema
/context/spring-context-3.0.xsd">
<context:annotation-config/>
<bean id="basicDataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/indi" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
</beans>
CController-servlet.xml(It is manager level 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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema
/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema
/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema
/util/spring-util-2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema
/context/spring-context-2.5.xsd">
<context:annotation-config/>
<context:component-scan base-package="project4"/>
<bean
class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<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" />
<bean name="frm4" class="project4.CController" >
<property name="userDAO" ref="myUserDAO" />
</bean>
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
</beans>
and UUController-servlet.xml(this is a dao level 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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema
/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema
/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema
/util/spring-util-2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema
/context/spring-context-2.5.xsd">
<bean id="mySessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="project4"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="myUserDAO" class="project4.UserDAOImpl1">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
</beans>
i have two xml files one for manager call and another for dao call...i know ref link from one xml points to the bean in another xml.I thought they will automatically link but i am getting the following error
Error creating bean with name
'org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping#0'
defined in ServletContext resource [/WEB-INF/CController-servlet.xml]: Initialization
of bean failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'frm4' defined in ServletContext resource [/WEB-INF/CController-servlet.xml]: Cannot
resolve reference to bean 'myUserDAO' while setting bean property 'userDAO'; nested
exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No
bean named 'myUserDAO' is defined
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'frm4' defined in ServletContext resource [/WEB-INF/CController-
servlet.xml]: Cannot resolve reference to bean 'myUserDAO' while setting bean property
'userDAO'; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named
'myUserDAO' is defined
UserDAOImpl1 is my hibernate template class and CCController is my spring controller class
CCController.java
package project4;
import project4.UserDAO1;
import project4.User1;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.validation.BindingResult;
#Controller
#RequestMapping("frm4.do")
public class CController{
private UserDAO1 userDAO;
public void setUserDAO(UserDAO1 userDAO) {
this.userDAO = userDAO;
}
#RequestMapping(params = "/add", method = RequestMethod.POST)
public ModelAndView add( #ModelAttribute("add") User1 user,HttpServletRequest
request,HttpServletResponse response) throws Exception {
userDAO.saveUser(user);
System.out.println("hai");
return new ModelAndView("redirect:list.htm");
}
#RequestMapping(params = "delete", method = RequestMethod.POST)
#Transactional
public ModelAndView delete(#ModelAttribute("delete") User1 user,HttpServletRequest
request,HttpServletResponse response) throws Exception {
userDAO.deleteUser(user);
return new ModelAndView("redirect:list.htm");
}
#RequestMapping(params = "find", method = RequestMethod.POST)
#Transactional
public ModelAndView find(#ModelAttribute("find") User1 user,HttpServletRequest
request,HttpServletResponse response) throws Exception {
userDAO.findUser(user);
return new ModelAndView("redirect:list.htm");
}
#RequestMapping(params = "update", method = RequestMethod.POST)
#Transactional
public ModelAndView update(#ModelAttribute("update") User1 user,HttpServletRequest
request,HttpServletResponse response) throws Exception {
userDAO.updateUser(user);
return new ModelAndView("redirect:list.htm");
}
public ModelAndView list(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelMap modelMap = new ModelMap();
modelMap.addAttribute("userList", userDAO.listUser());
modelMap.addAttribute("user", new User1());
return new ModelAndView("userForm", modelMap);
}
}
can someone help plz
EDIT:
the web.xml is as follows
<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>
<servlet>
<servlet-name>CController</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CController</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
frm4 bean has a property which has reference to userDAO, which is declared in other xml file. So make sure all the xml files are loaded in application context. To do this you need to add all the xml files in web.xml.
Try this :
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/UUController-servlet.xml,
/WEB-INF/application-context.xml,
/WEB-INF/CController-servlet.xml
</param-value>
</context-param>
EDIT :
If this is not working for you. Try adding other files in application-context.xml file. Use bean import tag.
<beans:import resource="/WEB-INF/UUController-servlet.xml"/>
<beans:import resource="/WEB-INF/CController-servlet.xml"/>
And load only application-context file at startup.
EDIT :
The reason behind the error 'Cannot map handler' is that you are scanning components at application startup and also having the same bean declared in application context.
<context:component-scan base-package="project4"/>
&
<bean name="frm4" class="project4.CController" >
<property name="userDAO" ref="myUserDAO" />
</bean>
Remove bean declaration from xml file since you already have scanned that particular component. And autowire myUserDAO bean in you controller class.
#Autowire
#Qualifier("myUserDAO")
private UserDAOImpl1 myUserDAO;
The problem is the UUController-servlet file is not loaded by the application context. Since it is a db level context add this to contextConfigLocation as shown below. Also I would recommend renaming it to dao-context.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/application-context.xml
/WEB-INF/UUController-servlet.xml
</param-value>
</context-param>

Resources