org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver handleHttpRequestMethodNotSupported - spring

Hi I am getting following error in spring MVC PUT example
Aug 14, 2017 12:28:57 PM org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver handleHttpRequestMethodNotSupported
WARNING: Request method 'PUT' not supported
on following form
<form:form action="../${user.id}" method="PUT" commandName="user">
<div class="form-group">
<label for="txtUserName">User-name</label>
<form:input path="userName" class="form-control" id="txtUserName"
placeholder="User Name" />
</div>
<div class="form-group">
<label for="txtName">First Name</label>
<form:input path="name" class="form-control" id="txtName"
placeholder="Full Name" />
</div>
<div class="form-group">
<label for="calDob">Date of Birth</label>
<form:input path="dateOfBirth" class="form-control" id="calDob"
placeholder="dd/MM/yyyy" />
</div>
<input type="hidden" name="_method" value="PUT">
<input type="submit" class="btn btn-success" value="SAVE">
</form:form>
with controller
#GetMapping(path = "/{id}/edit")
public String editUser(#PathVariable(value = "id") Long id, Model model) {
model.addAttribute("user", userService.findById(id));
return "user/edit";
}
#PutMapping(path = "/{id}/edit")
public String updateUser(#PathVariable(value = "id") long id, #ModelAttribute("user") User user, Model model) {
userService.updateUser(user);
model.addAttribute("user", userService.findById(id));
LOG.info("" + user.toString());
return "redirect:/users/" + id;
}
with following web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>httpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
<async-supported>true</async-supported>
</filter>
<filter-mapping>
<filter-name>httpMethodFilter</filter-name>
<servlet-name>appServlet</servlet-name>
</filter-mapping>
<filter>
<filter-name>httpPutFormFilter</filter-name>
<filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>httpPutFormFilter</filter-name>
<servlet-name>appServlet</servlet-name>
</filter-mapping>
can you please guide me how to solve this error.
And if you need more information, let me know.
Thanks :)
EDIT User.java
public class User {
private Long id;
private String name;
private String userName;
private String password;
private Date dateOfBirth;
public User() {
}
public User(Long id, String name, String userName, String password, Date dateOfBirth) {
super();
this.id = id;
this.name = name;
this.userName = userName;
this.password = password;
this.dateOfBirth = dateOfBirth;
}
//getters setters ommitted
}

Your put mapping expects 'edit' in the end #PutMapping(path = "/{id}/edit") but your form's action <form:form action="../${user.id}" does not have the edit so the controller can't intercept the action.

Related

Spring security j_spring_security_check call gives 404 not found error [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I am trying to create a login authentication with spring security. I am receiving a 404 not found error for my login url /knowledgeBase/j_spring_security_check. I have correctly defined my custom filter and my url in the security xml. Also I added a security filter in the web xml file. I am calling this url via an ajax request by serializing the form data. I had this code working in another project seuccessfully but now I am getting this error. What might be the cause?
This is security.xml file
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Disabled Security for Static Resources -->
<global-method-security pre-post-annotations="enabled" secured-annotations="enabled"/>
<http pattern="/static/**" security="none"/>
<beans:bean id="shaPasswordEncoder" class="org.springframework.security.authentication.encoding.ShaPasswordEncoder">
<beans:constructor-arg value="256"/>
</beans:bean>
<beans:bean id="userService" class="com.gsu.knowledgebase.service.UserService"/>
<!-- Ajax Aware Handler -->
<beans:bean id="authEntryPoint"
class="com.gsu.knowledgebase.spring.AjaxAwareLoginUrlAuthenticationEntryPoint"
scope="singleton">
<beans:constructor-arg name="loginFormUrl" value="/knowledge-base"/>
</beans:bean>
<http authentication-manager-ref="authenticationManager" entry-point-ref="authEntryPoint"
pattern="/knowledge-base/**"
use-expressions="true" disable-url-rewriting="true">
<custom-filter position="BASIC_AUTH_FILTER" ref="loginFilter"/>
<logout logout-success-url="/knowledge-base" invalidate-session="true" delete-cookies="JSESSIONID"
logout-url="/knowledgeBase/j_spring_security_logout"/>
<intercept-url pattern="/knowledge-base/" access="permitAll"/>
<intercept-url pattern="/knowledge-base/memory"
access="hasRole('ADMIN') || hasRole('MODERATOR') || hasRole('USER')"/>
<access-denied-handler error-page="/knowledge-base/error/403"/>
<session-management session-authentication-error-url="/knowledge-base/error/sessionExpired"/>
</http>
<!-- ************************** -->
<authentication-manager id="authenticationManager">
<authentication-provider user-service-ref="userService">
<password-encoder ref="shaPasswordEncoder"/>
</authentication-provider>
</authentication-manager>
<beans:bean id="loginFilter"
class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
<beans:property name="authenticationManager" ref="authenticationManager"/>
<beans:property name="filterProcessesUrl" value="/knowledgeBase/j_spring_security_check"/>
<beans:property name="authenticationSuccessHandler">
<beans:bean class="com.gsu.knowledgebase.spring.AuthenticationSuccessHandler"/>
</beans:property>
<beans:property name="authenticationFailureHandler">
<beans:bean class="com.gsu.knowledgebase.spring.AuthenticationFailureHandler"/>
</beans:property>
</beans:bean>
<!-- ************************** -->
</beans:beans>
This is web.xml file :
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring Web MVC Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/applicationContext.xml,
/WEB-INF/spring/security.xml
</param-value>
</context-param>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<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>
<servlet>
<servlet-name>main</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>knowledge-base</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/servlets/knowledge-base-dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>main</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>main</servlet-name>
<url-pattern>/visual/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>knowledge-base</servlet-name>
<url-pattern>/knowledge-base/*</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
This is my login form :
<form id="login-form">
<div class="form-group">
<label>Username</label>
<input type="text" class="form-control" name="j_username" ng-model="username"
placeholder="Your username">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="j_password" class="form-control" ng-model="password"
placeholder="Password">
</div>
<div class="form-check">
<!--<input type="checkbox" class="form-check-input" id="exampleCheck1">-->
<!--<label class="form-check-label">Check me out</label>-->
</div>
<span class="validation-message" style="display:none;">{{validationMessage}}</span>
<span class="success-message" style="display:none;">{{successMessage}}</span>
<input type="button" class="btn btn-default blue" value="Log in"
ng-click="login()">
</form>
And this is how I call the j_spring_security_check url via ajax :
$.ajax({
type: "POST",
url: 'knowledgeBase/j_spring_security_check',
data: jQuery("#login-form").serialize(), // serializes the form's elements.
success: function (data) {
window.location = "/knowledge-base/memory";
},
error: function (data, textStatus, jqXHR) {
if (data.status == 410) {
} else if (data.status == 409) {
} else if (data.status == 406) {
} else {
}
$scope.$digest();
printError(textStatus);
}
});
But I receive a 404 not found error.
UPDATE :
After solving this, I had trouble with my UserService. It does not recognize the autowired dependencies that are defined within it. I tried both using Autowired annotation directly on the variable and on the constructor separately. knowledgbaseDao is null in the loadUserByUsername. On startup, constructors of this class is called 3 times. Each creates different objects. First one is created using the default empty constructor. Other two is created using the autowired constructor and assigns knowledgebaseDao the correct class. When userservice is called from login page it uses the first UserService class and a null pointer exception is thrown. Here is my code :
#Component("userService")
public class UserService implements UserDetailsService {
private static final Logger logger = LoggerFactory.getLogger(UserService.class);
private KnowledgeBaseDao knowledgeBaseDao;
public UserService(){
System.out.println();
}
#Autowired
public UserService(KnowledgeBaseDao knowledgeBaseDao) {
this.knowledgeBaseDao = knowledgeBaseDao;
}
public UserDetails loadUserByUsername(String login) throws AuthenticationException {
logger.info("UserDetails Database Service : " + login);
// check user exists in database
User user = knowledgeBaseDao.findUserByEmail(login);
if (user == null) {
logger.warn("User({}) does not exist in system", login);
throw new UsernameNotFoundException("There is no user with this username.");
}
boolean containsLoginRole = checkLoginRole(user);
if (!containsLoginRole) {
throw new UsernameNotFoundException("Access denied.");
}
if ((user.getStatus() == null || user.getStatus() == 0)) {
throw new UsernameNotFoundException("User is not confirmed");
}
//boolean enabled = user.getStatus() == AccountStatus.ACTIVE;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
if (user.getLoginTryCount() != null && user.getLoginTryCount() >= 3) {
accountNonLocked = false;
}
return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), true, accountNonExpired,
credentialsNonExpired, accountNonLocked, this.getAuthorities(user.getRoleId()));
}
public Collection<? extends GrantedAuthority> getAuthorities(Collection<Role> roleList) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (Role role : roleList) {
authorities.add(new SimpleGrantedAuthority(role.getName()));
}
return authorities;
}
public Collection<? extends GrantedAuthority> getAuthorities(Long roleId) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority(Constants.ROLE_NAME(roleId.intValue())));
return authorities;
}
private boolean checkLoginRole(User user) {
if (user.getRoleId() == 0) {
return false;
}
if (user.getRoleId() == Constants.ROLE_ADMIN
|| user.getRoleId() == Constants.ROLE_MODERATOR
|| user.getRoleId() == Constants.ROLE_USER) {
return true;
} else {
return false;
}
}
}
Are you sure /knowledgeBase is the root servlet context url? I think it is knowledge-base .. so in this case the correct url the make login request should be /knowledge-base/knowledgeBase/j_spring_security_check try doing a post via postman

Getting MissingServletRequestParameterException during File upload

My Controller looks like this
#RequestMapping (value = { "/link_multiple" } , method =
RequestMethod.POST)
public ModelAndView linkMultipleVideo(
#RequestParam ("csv_file") final MultipartFile file) {
Here is my freemarker template
<input type="file" class="csv_file" name="csv_file" id="csv_file" accept=".csv"/>
<a class="file-link" href="javascript:void(0);">Choose File</a>
<span class='input-file-select'></span>
</div>
I have also added Multipart Resolver configuration to
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="2097152"/>
</bean>
Also added below filter in web.xml
<filter>
<filter-name>multipartFilter</filter-name>
<filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>multipartFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Below is the Exception that i am getting.
org.springframework.web.bind.MissingServletRequestParameterException: Required MultipartFile parameter 'csv_file' is not present
[tomcat:launch] at org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.handleMissingValue(RequestParamMethodArgumentResolver.java:255)
[tomcat:launch] at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:95)
[tomcat:launch] at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:79)
[tomcat:launch] at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:157)
[tomcat:launch] at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:124)
[tomcat:launch] at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
I got it to work by Removing filter from web.xml.
<filter>
<filter-name>multipartFilter</filter-name>
<filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>multipartFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

Two servlets in xml with spring mvc in netbeans

I'm practicing how to include ajax in spring-mvc with an example that I took from Internet but it doesn't work. I think that the problem is that I'm not able to run two servlets in the same xml but i don't know how to solve it.
Here is my xml code:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>JsonServlet</servlet-name>
<servlet-class>controladores.JsonServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>JsonServlet</servlet-name>
<url-pattern>/JsonServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>
</web-app>
This is my jsp code with javascript:
<html>
<head>
<title>AJAX in Servlet using JQuery and JSON</title>
<script src="js/jquery-1.11.1.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$('#sports').change(function(event) {
var sports = $("select#sports").val();
$.get('JsonServlet', {
sportsName : sports
}, function(response) {
var select = $('#player');
select.find('option').remove();
$.each($(foo), function(index, value) {
$('<option>').val(value).text(value).appendTo(select);
});
});
});
});
</script>
</head>
<body>
<h3>AJAX in Servlet using JQuery and JSON</h3>
Select Favorite Sports:
<select id="sports">
<option>Select Sports</option>
<option value="Football">Football</option>
<option value="Cricket">Cricket</option>
</select>
<br /> <br />
Select Favorite Player:
<select id="player">
<option>Select Player</option>
</select>
</body>
</html>
And this is my controller:
public class JsonServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String sportsName = request.getParameter("sportsName");
List<String> list = new ArrayList<String>();
String json = null;
if (sportsName.equals("Football")) {
list.add("Lionel Messi");
list.add("Cristiano Ronaldo");
list.add("David Beckham");
list.add("Diego Maradona");
} else if (sportsName.equals("Cricket")) {
list.add("Sourav Ganguly");
list.add("Sachin Tendulkar");
list.add("Lance Klusener");
list.add("Michael Bevan");
} else if (sportsName.equals("Select Sports")) {
list.add("Select Player");
}
json = new Gson().toJson(list);
response.setContentType("application/json");
response.getWriter().write(json);
}
}
When I try to put only the JsonServlet appears this error: invalid path was requested.
And when I try to run the two servlets at the same time the application never goes through the controller.
Why you are using spring dispatcherServlet, but write the raw servlet by yourself?

PrimePush chat is not working

my target is on page load to subscribe two users in chat (teacher and student), and they can send messages to each others, so here's what i did:
1- BackingBean:
package com.myapp.beans;
import org.primefaces.context.RequestContext;
import org.primefaces.push.PushContext;
import org.primefaces.push.PushContextFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.ocpsoft.pretty.faces.annotation.URLMapping;
import com.xeno.xenoTemplate.utils.constants.Pages;
#Component("chatBean")
#Scope("view")
#URLMapping(id = Pages.CHAT, pattern = "/chat", viewId = "/faces/pages/users/chat.xhtml")
public class ChatView {
private final PushContext pushContext = PushContextFactory.getDefault()
.getPushContext();
private String privateMessage;
private String privateUser;
private final static String CHANNEL = "/chat/";
private String student = "student";
private String teacher = "teacher";
private boolean pageLoaded;
private boolean studentLoggedIn;
private boolean teacherLoggedIn;
public void preRender() {
System.out.println("########### preRender CHAT BEAN #########");
if (!pageLoaded) { // invoked first time page loaded
System.out.println("########### Invoking PreRender Code #########");
if (!studentLoggedIn) {
System.out.println("########## STUDENT LOG IN ##########");
RequestContext.getCurrentInstance().execute(
"subscriber.connect('/" + student + "')");
studentLoggedIn = true;
}
if (!teacherLoggedIn) {
System.out.println("########## TEACHER LOG IN ##########");
RequestContext.getCurrentInstance().execute(
"subscriber.connect('/" + teacher + "')");
teacherLoggedIn = true;
}
pageLoaded = true;
}
}
public void sendPrivate() {
System.out.println("######### SEND PRIVATE ##########");
pushContext.push(CHANNEL + privateUser, "[PM] " + "PRIVATE" + ": "
+ privateMessage);
privateMessage = null;
}
public void setTeacher(String teacher) {
this.teacher = teacher;
}
public String getTeacher() {
return teacher;
}
public void setStudent(String student) {
this.student = student;
}
public String getStudent() {
return student;
}
public void setStudentLoggedIn(boolean studentLoggedIn) {
this.studentLoggedIn = studentLoggedIn;
}
public boolean isStudentLoggedIn() {
return studentLoggedIn;
}
public void setTeacherLoggedIn(boolean teacherLoggedIn) {
this.teacherLoggedIn = teacherLoggedIn;
}
public boolean isTeacherLoggedIn() {
return teacherLoggedIn;
}
public String getPrivateUser() {
return privateUser;
}
public void setPrivateUser(String privateUser) {
this.privateUser = privateUser;
}
public String getPrivateMessage() {
return privateMessage;
}
public void setPrivateMessage(String privateMessage) {
this.privateMessage = privateMessage;
}
}
and in the JSF page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ice="http://www.icesoft.com/icefaces/component"
xmlns:p="http://primefaces.org/ui"
xmlns:pretty="http://ocpsoft.com/prettyfaces"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:sec="http://www.springframework.org/security/tags"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<h:head>
<title>Chat</title>
</h:head>
<h:body>
<ui:composition template="/pages/template/commonLayout.xhtml">
<ui:define name="content">
<f:event type="preRenderView" listener="#{chatBean.preRender}" />
<h:form id="form">
<p:fieldset id="container" legend="PrimeChat" toggleable="true">
<h:panelGroup>
<h:panelGrid columns="2" columnClasses="publicColumn,usersColumn"
style="width:400px;">
<p:outputPanel style="height: 100px;" id="public" layout="block"
styleClass="ui-corner-all ui-widget-content chatlogs" />
<h:panelGroup id="users" styleClass="usersList">
<p:commandButton id="private_send" title="Chat" icon="ui-icon-comment"
oncomplete="pChat.show()" update=":form:privateChatContainer">
<f:setPropertyActionListener value="#{chatBean.student}"
target="#{chatBean.privateUser}" />
</p:commandButton>
#{chatBean.student}
</h:panelGroup>
</h:panelGrid>
</h:panelGroup>
</p:fieldset>
<!-- Private Chat Dialog -->
<p:dialog widgetVar="pChat" header="Private Chat" modal="true"
showEffect="fade" hideEffect="fade">
<h:panelGrid id="privateChatContainer" columns="2"
columnClasses="vtop,vtop">
<p:outputLabel for="pChatInput"
value="To: #{chatBean.privateUser}" />
<p:inputTextarea id="pChatInput"
value="#{chatBean.privateMessage}" rows="5" cols="30" />
<p:spacer />
<p:commandButton value="Send"
actionListener="#{chatBean.sendPrivate}"
oncomplete="pChat.hide()" />
</h:panelGrid>
</p:dialog>
</h:form>
<p:socket onMessage="handleMessage" channel="/chat"
autoConnect="false" widgetVar="subscriber" />
<script type="text/javascript">
function handleMessage(data) {
alert('handleMessage');
var chatContent = $(PrimeFaces
.escapeClientId('form:public'));
chatContent.append(data + '<br />');
chatContent.scrollTop(chatContent.height());
}
</script>
</ui:define>
</ui:composition>
</h:body>
</html>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_3_0.xsd"
version="3.0">
<display-name>MyAPP</display-name>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:META-INF/spring/applicationContext.xml
classpath:META-INF/spring/applicationSecurity.xml
</param-value>
</context-param>
<context-param>
<param-name>javax.faces.FACELETS_LIBRARIES</param-name>
<param-value>
/WEB-INF/springsecurity.taglib.xml;/WEB-INF/utils.taglib.xml
</param-value>
</context-param>
<context-param>
<param-name>javax.faces.FACELETS_SKIP_COMMENTS</param-name>
<param-value>false</param-value>
</context-param>
<!-- -->
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<welcome-file-list>
<welcome-file>/</welcome-file>
</welcome-file-list>
<context-param>
<description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>
<context-param>
<param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
<param-value>resources.application</param-value>
</context-param>
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>sessionFactory</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
<dispatcher>ERROR</dispatcher>
</filter-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>
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
<dispatcher>ERROR</dispatcher>
</filter-mapping>
<!--
<filter>
<filter-name>Pretty Filter</filter-name>
<filter-class>com.ocpsoft.pretty.PrettyFilter</filter-class>
<init-param>
<param-name>logLevel</param-name>
<param-value>ERROR</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Pretty Filter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
<dispatcher>ERROR</dispatcher>
</filter-mapping>
-->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/error</location>
</error-page>
<error-page>
<error-code>400</error-code>
<location>/error</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/pageNotFound</location>
</error-page>
<!-- PrimePush Servlet -->
<servlet>
<servlet-name>Push Servlet</servlet-name>
<servlet-class>org.primefaces.push.PushServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<init-param>
<param-name>org.atmosphere.cpr.broadcasterCacheClass</param-name>
<param-value>org.atmosphere.cache.HeaderBroadcasterCache</param-value>
</init-param>
<init-param>
<param-name>org.atmosphere.cpr.broadcasterClass</param-name>
<param-value>org.atmosphere.cpr.DefaultBroadcaster</param-value>
</init-param>
<init-param>
<param-name>org.atmosphere.cpr.broadcastFilterClasses</param-name>
<param-value>org.atmosphere.client.TrackMessageSizeFilter</param-value>
</init-param>
<init-param>
<param-name>org.atmosphere.cpr.sessionSupport</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Push Servlet</servlet-name>
<url-pattern>/primepush/*</url-pattern>
</servlet-mapping>
</web-app>
i am using the following jars:
JSF 2.1.10
PrimeFaces 4.0-SNAPSHOT
Tomcat 7.0.32
atmosphere-runtime 1.0.1
HEADERS
Request URL:http://localhost:8080/MyAPP/chat
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:application/xml, text/xml, */*; q=0.01
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:282
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:JSESSIONID=2BB4298A4E291CCCBB80EE3A4A5624BC
Faces-Request:partial/ajax
Host:localhost:8080
Origin:http://localhost:8080
Referer:http://localhost:8080/PrimeTemplate/chat
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11
X-Requested-With:XMLHttpRequest
Form Dataview URL encoded
javax.faces.partial.ajax:true
javax.faces.source:form:j_idt31
javax.faces.partial.execute:#all
form:j_idt31:form:j_idt31
form:form
form:j_idt24:
form:container_collapsed:false
form:pChatInput:aaaaaaaaaaaa
javax.faces.ViewState:5079906166114901626:-433970771510989466
Response Headersview source
Cache-Control:no-cache
Content-Length:190
Content-Type:text/xml;charset=UTF-8
Date:Thu, 18 Oct 2012 10:40:04 GMT
Server:Apache-Coyote/1.1
X-Powered-By:JSF/2.0
RESPONSE:
<?xml version='1.0' encoding='UTF-8'?>
<partial-response><changes><update id="javax.faces.ViewState"><![CDATA[5079906166114901626:-433970771510989466]]></update></changes></partial-response>
ISSUE:
i can open the chat window for the student and type a chat message then press enter, the code gets in the sendPrivate bean method, but the JS handleMessage function is not called and hence the private message is not displayed in the JSF page, i get no errors in browser console.
please advise how to fix that.
Try to add following jars to your lib folder (if you havent already done that):
atmosphere-compat-tomcat-1.0.1.jar
atmosphere-compat-tomcat7-1.0.1.jar
Also have in mind that if you are connected as STUDENT to the "student" channel and if you are pushing message to "teacher" channel, only teacher's channel will receive a message.
To test your chat, you need to login as student in one browser and as teacher in another browser. In this case, when you push message as student to the teacher in one browser, teacher in another browser will receive the message.

Spring MVC 3.0 mapping extension

I would like to have my Spring MVC application mapped to the following extension *html for jsp and *.action for controllers.
this is for login page:
#RequestMapping(value="/login.html", method=RequestMethod.GET)
public ModelAndView login(){
ModelAndView mv = new ModelAndView("login/login");
//omitted
return mv;
}
and this is for action:
#RequestMapping(value="/login.action", method=RequestMethod.POST)
public ModelAndView actionSignUp(#Valid User user){
//omitted
return mv;
}
and jsp is simple:
<form:form method="POST" action="/login.action" commandName="user" >
<form:input path="userName" id="userName" /><br />
<form:input path="password" id="password"/><br />
<input id ="login" type="submit" value="Login"></input>
</form:form>
my web.xml is the following:
<display-name>SpringMVC</display-name>
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
<servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
I have no problem to get /login.html, but I have a problem with POST request on /login.action
I'm getting
HTTP Status 404 - /login.action
Why my mapping for *.action is not working?
Can I map two different extensions *html and *.action ?
The action method in your form was defined as action="/login.action". The / makes the url relative to your domain. You should notice that the form posted to a url similar to http://localhost:8080/login.action which should be http://localhost:8080/[context root]/[sub dir if defined]/login.action
I recon that removing the '/' will fix it.

Resources