How does Spring know which view is to be returned? - spring

I'm new to Spring MVC and I don't understand how does spring knows that it must return the priceincrease.jsp, if it isn't mapped in the controller?
The other thing I don't understand is how does spring auto-completes the form action?
My controller is:
#Controller
#RequestMapping(value="/priceincrease.html")
public class PriceIncreaseFormController {
/** Logger for this class and subclasses */
protected final Log logger = LogFactory.getLog(getClass());
#Autowired
private ProductManager productManager;
#RequestMapping(method = RequestMethod.POST)
public String onSubmit(#Valid PriceIncrease priceIncrease, BindingResult result)
{
if (result.hasErrors()) {
return "priceincrease";
}
int increase = priceIncrease.getPercentage();
logger.info("Increasing prices by " + increase + "%.");
productManager.increasePrice(increase);
return "redirect:/hello.html";
}
#RequestMapping(method = RequestMethod.GET)
protected PriceIncrease formBackingObject(HttpServletRequest request) throws ServletException {
PriceIncrease priceIncrease = new PriceIncrease();
priceIncrease.setPercentage(15);
return priceIncrease;
}
public void setProductManager(ProductManager productManager) {
this.productManager = productManager;
}
public ProductManager getProductManager() {
return productManager;
}
}
And this is the jsp the controller returns
<%# include file="/WEB-INF/views/include.jsp" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<title><fmt:message key="title"/></title>
<style>
.error { color: red; }
</style>
</head>
<body>
<h1><fmt:message key="priceincrease.heading"/></h1>
<form:form method="post" commandName="priceIncrease">
<table width="95%" bgcolor="f8f8ff" border="0" cellspacing="0" cellpadding="5">
<tr>
<td align="right" width="20%">Increase (%):</td>
<td width="20%">
<form:input path="percentage"/>
</td>
<td width="60%">
<form:errors path="percentage" cssClass="error"/>
</td>
</tr>
</table>
<br>
<input type="submit" value="Execute">
</form:form>
Home
</body>
</html>
UPDATE:
Here is my app-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"
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">
<bean id="productManager" class="com.mycompany.springapp.service.SimpleProductManager">
<property name="products">
<list>
<ref bean="product1"/>
<ref bean="product2"/>
<ref bean="product3"/>
</list>
</property>
</bean>
<bean id="product1" class="com.mycompany.springapp.domain.Product">
<property name="description" value="Lamp"/>
<property name="price" value="5.75"/>
</bean>
<bean id="product2" class="com.mycompany.springapp.domain.Product">
<property name="description" value="Table"/>
<property name="price" value="75.25"/>
</bean>
<bean id="product3" class="com.mycompany.springapp.domain.Product">
<property name="description" value="Chair"/>
<property name="price" value="22.79"/>
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>
<!-- Scans the classpath of this application for #Components to deploy as beans -->
<context:component-scan base-package="com.mycompany.springapp.web" />
<!-- Configures the #Controller programming model -->
<mvc:annotation-driven/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>

When the DispatcherServlet is initialized, it will look for ViewResolver beans in its ApplicationContext. You've only registered one
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
When your handler method returns, Spring looks at the return value (and the handler) to determine what to do. In your case, ie. a returned String value, it will use a ViewNameMethodReturnValueHandler which indicates that the returned String value is to be used as a view name.
Once that is done, the DispatcherServlet will loop through the ViewResolver beans checking if the view name can be resolved to a View object. If it can, it will use that View, if it can't it will try the next one. It will fail if it can't resolve a view name.

i've been doing some research and i've found the answer to one of two questions:
How does Spring know which view is to be returned?
Spring Framework Reference Documentation - 17.13.3 The View - RequestToViewNameTranslator
http://docs.spring.io/spring/docs/4.1.2.BUILD-SNAPSHOT/spring-framework-reference/htmlsingle/#mvc-coc-r2vnt

Related

Why my action can not to work in my javaWeb project?

IDE Version:struts2.5.8+spring4.3.6+hibernate5.2.8.
I'm a new worker in Java Web.
After I checked carefully my code,but the action can not to work.
Every time i'm running my code in Tomcatv9.0, my chrome web browser display en "HTTP Status 404" type Status report.
description: The requested resource is not available.
web.xml code:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="MyStrutsApp" 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">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- <param-value>/WEB-INF/applicationContext-*.xml,classpath*:applicationContext-*.xml</param-value> -->
<param-value>classpath:beans.xml</param-value>
</context-param>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
struts.xml code:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<include file="struts-default.xml"></include>
<constant name="struts.i18n.encoding" value="UTF-8"></constant>
<constant name="struts.action.extension" value="do,action"></constant>
<constant name="struts.serve.static.browserCache" value="false"> </constant>
<constant name="struts.devMode" value="true" />
<constant name="struts.configuration.xml.reload" value="true"></constant>
<constant name="struts.enable.DynamicMethodInvocation" value="true" />
<package name="registration" extends="struts-default" namespace="/" >
<action name="user" class="userAction" method="add">
<result name="success">/registerSuccess.jsp</result>
<result name="fail">/registerFail.jsp</result>
<allowed-methods>add</allowed-methods>
</action>
</package>
</struts>
beens.xml code:
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:annotation-config />
<context:component-scan base-package="com.diyuan" />
<!--
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/spring" />
<property name="username" value="root" />
<property name="password" value="bjsxt" />
</bean>
-->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:jdbc.properties</value>
</property>
</bean>
<bean id="dataSource" destroy-method="close"
class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName"
value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--
<property name="annotatedClasses">
<list>
<value>com.bjsxt.model.User</value>
<value>com.bjsxt.model.Log</value>
</list>
</property>
-->
<property name="packagesToScan">
<list>
<value>com.diyuan.integration.model</value>
</list>
</property>
<property name="hibernateProperties">
<value>
org.hibernate.dialect.MySQL5Dialect
</value>
</property>
</bean>
<!--
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
-->
<bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="userDao" class="com.diyuan.integration.dao.impl.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="userManager" class="com.diyuan.integration.service.impl.UserManagerImpl">
<property name="userDao" ref="userDao"/>
</bean>
<bean id="userAction" class="com.diyuan.integration.action.UserAction" scope="prototype">
<property name="um" ref="userManager"/>
</bean>
action code:
package com.diyuan.integration.action;
import javax.annotation.Resource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import com.diyuan.integration.model.User;
import com.diyuan.integration.service.UserManager;
import com.opensymphony.xwork2.ActionSupport;
public class UserAction extends ActionSupport {
private String username;
private String password;
private String password2;
private UserManager um;
public UserManager getUm() {
return um;
}
public void setUm(UserManager um) {
this.um = um;
}
#Override
public String execute() throws Exception {
User u = new User();
u.setUsername(username);
u.setPassword(password);
if(um.exists(u)) {
return "fail";
}
um.add(u);
return "success";
}
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 getPassword2() {
return password2;
}
public void setPassword2(String password2) {
this.password2 = password2;
}
}
Today, I check my code again, and found en error code in register.jsp page code, like this:
<body>
<form method="post" action="user.Action">
UserName:<input type="text" name="username"><br>
Password:<input type="text" name="password"><br>
Password2:<input type="password" name="password2"><br>
<input type="submit" value="Login"/>
</form>
Change the upper case "user.Action" to lower case "user.action", then struts action can work.
<body>
<form method="post" action="user.action">
UserName:<input type="text" name="username"><br>
Password:<input type="text" name="password"><br>
Password2:<input type="password" name="password2"><br>
<input type="submit" value="Login"/>
</form>

Update one column does not works

I want to update one column of my database. The column name is status and the type is Enum('waiting' , 'accepted' , 'rejected')
I want to update this column when I click on link:
Accept
Reject
Vacation.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.terafast.tem.model">
<class name="Vacation" table="vacations" dynamic-update="true">
<id name="id" column="REQUEST_ID">
<generator class="native" />
</id>
<property name="user" column="USER_ID" />
<property name="reason" column="REASON" />
<property name="duration" column="HOW_LONG" />
<property name="status" column="STATUS" />
<property name="start" type="date" column="START_DATE" />
<property name="created" type="date" column="CREATED_AT" />
</class>
</hibernate-mapping>
Controller
#RequestMapping(value = "/requests/action")
public String statuHandler(HttpServletRequest request, Model model) {
int id = Integer.parseInt(request.getParameter("id"));
String status = request.getParameter("a");
vacationDao.actionStatus(id, status);
return "redirect:/admin/requests";
I can successfully get these two GET values. (id , a). My VacationDAOImpl:
#Override
#Transactional
public void actionStatus(int id, String action) {
Session session = sessionFactory.openSession();
Query q = session.createQuery("from Vacation where id = :reqid ");
q.setParameter("reqid", id);
Vacation vacation = (Vacation) q.list().get(0);
vacation.setStatus(action);
session.update(vacation);
}
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<mvc:annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<mvc:resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<context:component-scan base-package="com.terafast.tem" />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="employeeDao" class="com.terafast.tem.dao.EmployeeDAOImpl">
<constructor-arg>
<ref bean="sessionFactory" />
</constructor-arg>
</bean>
<bean id="vacationDoa" class="com.terafast.tem.dao.VacationDAOImpl">
<constructor-arg>
<ref bean="sessionFactory" />
</constructor-arg>
</bean>
</beans>
I have seen this approach in this tutorial.
When I click on links, everything looks good. But the column value does not change. Could someone explain this problem?

Spring MVC portlet in Liferay 6.2, Model properties are null upon form post

I've tried to clone a Spring MVC Portlet project but upon posting the form todo properties are all null.
Repo is available on Github.
Here is the Controller code
#Controller
#RequestMapping("VIEW")
public class ToDoListController {
#RenderMapping
public String view() {
return "list";
}
#ActionMapping
public void save(#Valid ToDo toDo, BindingResult result, #CookieValue("JSESSIONID") String jsessionid,
PortletSession session, ModelMap modelMap) {
if (!result.hasErrors()) {
// could use entityManager to persist; put in session for this example
List<ToDo> toDos = (List<ToDo>) session.getAttribute("toDos");
if (toDos == null) {
toDos = new ArrayList<ToDo>();
}
toDos.add(toDo);
session.setAttribute("toDos", toDos);
modelMap.put("msg", String.format("You added a TODO: %s", toDo.getTitle()));
}
}
#ModelAttribute
private ToDo loadModel() {
return new ToDo();
}
}
Here is the View:
<%# page contentType="text/html" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="portlet" uri="http://java.sun.com/portlet_2_0" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<c:if test="${msg ne null}">
<div class="portlet-msg-success"><c:out value="${msg}" /></div>
</c:if>
<portlet:actionURL var="save" />
<form:form modelAttribute="toDo" action="${save}" method="POST">
<fieldset>
<legend>Add a TODO</legend>
<div>
<form:label path="title" cssStyle="display:block">Title:</form:label>
<form:input path="title" />
<form:errors path="title" cssClass="portlet-msg-error" />
</div>
<div>
<form:label path="due" cssStyle="display:block">Due (MM/DD/YYYY):</form:label>
<form:input path="due" />
<form:errors path="due" cssClass="portlet-msg-error" />
</div>
<div>
<form:label path="description" cssStyle="display:block">Description:</form:label>
<form:textarea path="description" />
<form:errors path="description" cssClass="portlet-msg-error" />
</div>
<div>
<input type="submit" value="Save" />
</div>
</fieldset>
</form:form>
And here is the Context:
<?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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<mvc:annotation-driven validator="validator" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="cache" value="true" />
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
<bean id="annotationMethodHandlerAdapter"
class="org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="webBindingInitializer">
<bean id="configurableWebBindingInitializer"
class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="validator">
<ref bean="validator" />
</property>
</bean>
</property>
</bean>
</beans>
=====================================================================
Update:
Here is the working version: https://github.com/jzinedine/FirstPortlet
You need to set <requires-namespaced-parameters>false</requires-namespaced-parameters> in your liferay-portlet.xml when using Spring MVC with Liferay 6.2. It is explained on Liferay 6.2 documentation at the end of this page.

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.

Can't use #Autowired in desktop application

i am trying to use spring in desktop application, but i am facing a problem with autowiring in action methods of my JPanel.
i am loading the applicationContext in my main method as follows:
public static void main(String[] args) {
new ClassPathXmlApplicationContext(
"classpath:/META-INF/spring/applicationContext.xml");
MainFrame frame = new MainFrame();
Signup signup = new Signup();
frame.add(signup);
frame.setResizable(false);
frame.setTitle("Please input your data");
frame.setBounds(100, 100, 450, 180);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
and i can see that it's loaded with no problems.
my panel code:
#Component
public class Signup extends JPanel {
#Autowired
private UserDao userDao;
public Signup() {
JButton btn_submit = new JButton("Submit");
btn_submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
registerUser();
}
});
}
private void registerUser() {
User newUser = new User();
newUser.setName(username);
newUser.setSalary(salary);
userDao.addUser(newUser);
}
}
the context:component-scan is configured properly, and i am using context:annotation-config too but i always gets NullPointerException in userDao.addUser(newUser);
which means that the Dependency Injection is not working as it should.
please advise how to fix this issue.
UPDATE: applicationContext.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:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="${project.groupId}" />
<context:annotation-config />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="propertyPlaceholderConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:messages/application.properties</value>
</list>
</property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="${project.groupId}.domain" />
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.DerbyDialect
hibernate.show_sql=false
hibernate.format_sql=false
hibernate.hbm2ddl.auto=validate
</value>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.apache.derby.jdbc.EmbeddedDriver" />
<property name="url" value="jdbc:derby:test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
</beans>
If you are going to configure Spring in a desktop environment, then you must be the one to work with the ApplicationContext.
For example, if you want to get a hold of your Signup class that you have posted here, you would do something like this in your main method:
public static void main(String[] args) {
ApplicationContext appContext = new ClassPathXmlApplicationContext(
"classpath:/META-INF/spring/applicationContext.xml");
Signup signup = appContext.getBean(Signup.class);
//use signup here...
}
Using new Signup() to get a new instance of the Signup class, which won't work the way you want, because you want it to be a Spring managed class! (Actually, you could get it to work that way, but that is beyond my answer here)

Resources