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

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.

Related

Spring custom login form issue with Spring Security 4.0.2

I am using Spring MVC 4.2, Hibernate 4.2.20, Apache Tiles 3.0.5 & Spring Security 4.0.2.
Well, my project was running well until I tried to use CUSTOM login page and it fails.
Please look at below page when it works with in-built login.
Now when I tried to use CUSTOM login page I get below error and nothing specific error in the console.
I am NOT sure what could be wrong. Please look at further info below.
Project Structure
My Jars under /lib folder
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>SpringMVCHibernateProject</display-name>
<!-- global variables -->
<context-param>
<param-name>appRootPath</param-name>
<param-value>SpringMVCHibernateProject</param-value>
</context-param>
<!-- front controller -->
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>
org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
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"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.0.xsd">
<!-- default page to show when app starts -->
<!-- <mvc:view-controller path="/" view-name="Home"/> --> <!-- this is one way; another way defined in the HomeController.java (preferred) -->
<!-- essentially sets you your Spring context to allow for dispatching requests to Controllers -->
<mvc:annotation-driven />
<!-- used to load static resources like css, js etc... -->
<mvc:default-servlet-handler/>
<!-- automatically wire values into properties, methods, and constructors. -->
<context:annotation-config/>
<!-- scan for components like #Controller, #Repository, #Service, #Component etc...-->
<context:component-scan base-package="au.com.snh.*" />
<!-- spring view resolver bean....commented out in favour of Apache Tiles -->
<!--
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
-->
<!-- apache tiles...template framework -->
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
<bean id="tilesViewResolver" class="org.springframework.web.servlet.view.tiles3.TilesViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles3.TilesView
</value>
</property>
<property name="order" value="0" />
</bean>
<!-- load database properties file -->
<context:property-placeholder location="classpath:database.properties"/>
<!-- declare beans -->
<bean id="regionDao" class="au.com.snh.dao.RegionDaoImpl" />
<bean id="regionService" class="au.com.snh.service.RegionServiceImpl" />
<!-- declare datasource bean -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${db.driver}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.user}" />
<property name="password" value="${db.pwd}" />
</bean>
<!-- hibernate -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="au.com.snh.model" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- resource bundles -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/propertybundle/common"/>
</bean>
<!-- spring secruity -->
<security:http auto-config="true" use-expressions="false">
<security:intercept-url pattern="/**" access="ROLE_USER" />
<security:form-login
login-page="/login"
login-processing-url="/j_spring_security_check"
authentication-failure-url="/login?error"
username-parameter="username"
password-parameter="password"
/>
<security:logout logout-success-url="/login?logout"/>
<security:csrf/>
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<security:user name="hitesh" password="hitesh123" authorities="ROLE_USER" />
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
</beans>
tiles.xml (Apache tiles)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN"
"http://tiles.apache.org/dtds/tiles-config_3_0.dtd">
<tiles-definitions>
<definition name="base" template="/WEB-INF/views/tiles/Template.jsp">
<put-attribute name="title" value="" />
<put-attribute name="header" value="/WEB-INF/views/tiles/Header.jsp" />
<put-attribute name="body" value="" />
<put-attribute name="footer" value="/WEB-INF/views/tiles/Footer.jsp" />
</definition>
<definition name="login" extends="base">
<put-attribute name="title" value="Welcome to Spring MVC and Hibernate World!" />
<put-attribute name="body" value="/WEB-INF/views/login.jsp" />
</definition>
<definition name="Home" extends="base">
<put-attribute name="title" value="Welcome to Spring MVC and Hibernate World!" />
<put-attribute name="body" value="/WEB-INF/views/Home.jsp" />
</definition>
<!-- Location Views -->
<definition name="LocationList" extends="base">
<put-attribute name="title" value="Location List" />
<put-attribute name="body" value="/WEB-INF/views/LocationList.jsp" />
</definition>
<definition name="LocationAddEdit" extends="base">
<put-attribute name="title" value="Add/Edit Location" />
<put-attribute name="body" value="/WEB-INF/views/LocationAddEdit.jsp" />
</definition>
<!-- Region Views -->
<definition name="RegionList" extends="base">
<put-attribute name="title" value="Regions" />
<put-attribute name="body" value="/WEB-INF/views/RegionList.jsp" />
</definition>
<definition name="RegionAdd" extends="base">
<put-attribute name="title" value="Add Region" />
<put-attribute name="body" value="/WEB-INF/views/RegionAdd.jsp" />
</definition>
<definition name="RegionEdit" extends="base">
<put-attribute name="title" value="Edit Region" />
<put-attribute name="body" value="/WEB-INF/views/RegionEdit.jsp" />
</definition>
<!-- Student Admission Views -->
<definition name="AdmissionForm" extends="base">
<put-attribute name="title" value="Edit Region" />
<put-attribute name="body" value="/WEB-INF/views/AdmissionForm.jsp" />
</definition>
<definition name="AdmissionFormSuccess" extends="base">
<put-attribute name="title" value="Edit Region" />
<put-attribute name="body" value="/WEB-INF/views/AdmissionFormSuccess.jsp" />
</definition>
</tiles-definitions>
SecurityController.java
package au.com.snh.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class SecurityController {
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login(#RequestParam(value = "error", required = false) String error, #RequestParam(value = "logout", required = false) String logout) {
System.out.println("login() start =>");
ModelAndView model = new ModelAndView();
if (error != null) {
model.addObject("error", "Invalid username and password!");
}
if (logout != null) {
model.addObject("msg", "You've been logged out successfully.");
}
model.setViewName("login");
System.out.println("login() start <=");
return model;
}
}
My Custom Login Form
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<div id="pageHeading">Login with Username and Password</div>
<div id="bodyContent">
<c:if test="${not empty error}">
<div class="error">${error}</div>
</c:if>
<c:if test="${not empty msg}">
<div class="msg">${msg}</div>
</c:if>
<form name='loginForm' action="<c:url value='j_spring_security_check' />" method='POST'>
<table>
<tr>
<td>Username:</td>
<td><input type='text' id="username" name='username' value=''></td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' id="password" name='password' /></td>
</tr>
<tr>
<td colspan='2'>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
<input name="submit" type="submit" value="Login" />
</td>
</tr>
</table>
</form>
</div>
<script language="javascript">
document.getElementById("username").focus();
</script>
Can someone please tell me what could be wrong?
Looking forward to getting some help.
Thanks - Hitesh
Your login page is now a normal page displayed through DispatcherServlet instead of being generated by a Spring Security filter. So it must be accessible to non authenticated user. Currently, your security configuration requires a ROLE_USER for all pages... including /login. So here is what happens:
you make a request for any page before being authenticated
spring security detects that and redirect to /login page
browser sends a request for /login page without being authenticated
spring security detects that and redirect to /login page !
You must allow all accesses to /login page in dispatcher-servlet.xml:
<!-- spring secruity -->
<security:http auto-config="true" use-expressions="false">
<security:intercept-url pattern="/login"
access="IS_AUTHENTICATED_FULLY,IS_AUTHENTICATED_ANONYMOUSLY" />
<security:intercept-url pattern="/**" access="ROLE_USER" />
...
alternatively, you can create a dedicated security zone for /login fully by-passing security:
<!-- spring secruity -->
<security:http pattern = "/login*" security="none">
<security:http auto-config="true" use-expressions="false">
<security:intercept-url pattern="/**" access="ROLE_USER" />
...
It is not redirecting properly
Try to add the default-target-url
<security:form-login login-page="/login" default-target-url="/" authentication-failure-url="/login?error=true" />

How does Spring know which view is to be returned?

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

Spring Basic authentication

Hi I have some login form configuration for authentication and i want to replace my simple login form by
response.setHeader("WWW-Authenticate", "Basic realm=\"/\"");
response.setStatus(401);
response.setHeader("Location", url);
to behave like this form and used spnegoAuthenticationProcessingFilter:
<div id="login-box">
<h3>Login with Username and Password</h3>
<c:if test="${not empty error}">
<div class="error">${error}</div>
</c:if>
<c:if test="${not empty msg}">
<div class="msg">${msg}</div>
</c:if>
<form name='loginForm' action="<c:url value='j_spring_security_check' />" method='POST'>
<table>
<tr>
<td>User:</td>
<td><input type='text' name='j_username' value=''></td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='j_password' /></td>
</tr>
<tr>
<td colspan='2'><input name="submit" type="submit" value="submit" /></td>
</tr>
</table>
</form>
</div>
This is my spring security configuration:
<?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:sec="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd">
<sec:http entry-point-ref="spnegoEntryPoint" auto-config="false" >
<sec:intercept-url pattern="/login*" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<sec:intercept-url pattern="/**" access="ROLE_USER" />
<sec:custom-filter ref="spnegoAuthenticationProcessingFilter" position="BASIC_AUTH_FILTER" />
<sec:form-login login-page="/login" default-target-url="/hello" always-use-default-target="true"/>
</sec:http>
<bean id="spnegoEntryPoint" class="org.springframework.security.extensions.kerberos.web.SpnegoEntryPoint" />
<bean id="spnegoAuthenticationProcessingFilter" class="org.springframework.security.extensions.kerberos.web.SpnegoAuthenticationProcessingFilter">
<property name="authenticationManager" ref="authenticationManager" />
</bean>
<sec:authentication-manager alias="authenticationManager">
<sec:authentication-provider ref="kerberosAuthenticationProvider"/>
</sec:authentication-manager>
<!-- Login form auth -->
<bean id="kerberosAuthenticationProvider" class="org.springframework.security.extensions.kerberos.KerberosAuthenticationProvider">
<property name="kerberosClient">
<bean class="org.springframework.security.extensions.kerberos.SunJaasKerberosClient">
<property name="debug" value="true" />
</bean>
</property>
<property name="userDetailsService" ref="dummyUserDetailsService" />
</bean>
<bean class="org.springframework.security.extensions.kerberos.GlobalSunJaasKerberosConfig">
<property name="debug" value="true" />
<property name="krbConfLocation" value="/apps/bin/krb5/krb5.conf" />
</bean>
<bean id="dummyUserDetailsService" class="com.web.ldap.DummyUserDetailsService"/>
</beans>
This is possible ?
I do this by that
<sec:http>
<sec:intercept-url pattern="/**" access="ROLE_USER" />
<sec:http-basic entry-point-ref="spnegoEntryPoint"/>
<!-- <sec:custom-filter ref="spnegoAuthenticationProcessingFilter" position="BASIC_AUTH_FILTER" /> -->
</sec:http>
but now i don't have spnegoAuthenticationProcessingFilter working...
If i uncomment custom-filter my application will not work

Spring MVC local is not getting changed when clicking local changing link

Below is my Spring context file, But when try to change local lang, It is not switching up....I did lot of search on google + refer other question on stackoverflow, but nothing is useful.. Most of places it suggestion to add <mvc:interceptors> tag around bean tag localeChangeInterceptor.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
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">
<mvc:resources mapping="/css/**" location="/css/" />
<mvc:annotation-driven />
<context:annotation-config />
<context:component-scan base-package="com.technicalkeeda.controller" />
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="fr" />
</bean>
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
<bean id="handlerMapping"
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<ref bean="localeChangeInterceptor" />
</property>
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<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">
<servlet>
<servlet-name>springexamples</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springexamples</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springexamples-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file> index.jsp </welcome-file>
</welcome-file-list>
</web-app>
Index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Title Here</title>
<link type="text/css" href="<%=request.getContextPath() %>/css/bootstrap.css" rel="stylesheet"/>
</head>
<body>
<div class="container-fluid">
<h2>Select Your Language</h2>
<div class="row-fluid">
<div class="span12">
English French
</div>
</div>
<div class="row-fluid">
<div class="span12">
<fieldset>
<legend><spring:message code="employee.form.title" text="default text" /></legend>
<form class="form-horizontal" method="post" action='employee/add.htm' name="employeeForm" id="employeeForm">
<div class="control-group">
<label class="control-label">First Name</label>
<div class="controls">
<input type="text" name="firstName" id="firstName" title="First Name" value="">
</div>
</div>
<div class="control-group">
<label class="control-label">Last Name</label>
<div class="controls">
<input type="text" name="lastName" id="lastName" title="Last Name" value="">
</div>
</div>
<div class="control-group">
<label class="control-label">Email</label>
<div class="controls">
<input type="text" name="email" id="email" title="Email" value="">
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Submit</button>
<button type="button" class="btn">Cancel</button>
</div>
</form>
</fieldset>
</div>
</div>
</div>
</body>
</html>
You are using <mvc:annotation-driven /> then you also have to use the namespace to register your interceptors. Use <mvc:interceptors /> to register your interceptors instead of declaring (another unused) DefaultAnnotationHandlerMapping.
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
</mvc:interceptors>
Another thing <context:annotation-config /> is already implied due to the use of <context:component-scan />.
Sorry, I haven't got enough credits to comment, but as M.Denim pointed, it is likely that you have your index.jsp outside WEB-INF folder.
You can move your index.jsp into your WEB-INF/jsp/ folder and in your configuration add a static view for rendering without the need for an explicit controller with:
<mvc:view-controller path="/" view-name="index"/>
The whole thing would be:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
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">
<context:component-scan base-package="com.technicalkeeda.controller" />
<!-- Turns on support for mapping requests to Spring MVC #Controller methods
Also registers default Formatters and Validators for use across all #Controllers -->
<mvc:annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources -->
<mvc:resources location="/, classpath:/META-INF/web-resources/" mapping="/resources/**"/>
<!-- Allows for mapping the DispatcherServlet to "/" by forwarding static resource
requests to the container's default Servlet -->
<mvc:default-servlet-handler/>
<!-- Register "global" interceptor beans to apply to all registered HandlerMappings -->
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" p:paramName="lang"/>
</mvc:interceptors>
<!-- Selects a static view for rendering without the need for an explicit controller -->
<mvc:view-controller path="/" view-name="index"/>
<bean class="org.springframework.context.support.ReloadableResourceBundleMessageSource" id="messageSource" p:basenames="classpath:messages" p:fallbackToSystemLocale="false"/>
<!-- Store preferred language configuration in a cookie -->
<bean class="org.springframework.web.servlet.i18n.CookieLocaleResolver" id="localeResolver" p:cookieName="locale"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>

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.

Resources