I am working on spring. I have the controller AdminProduitsController (code below) that doesn't load the correct view. It should load a page called produits.jsp.Instead of that, it loads the page categories.jsp of an other controller called AdminCategorieController. The two controllers belongs to the same package.
The pages produits.jsp and categories.jsp are in the same directory.
AdminProduitsController
#Controller
#RequestMapping(value="/adminProd")
public class AdminProduitsController {
#Autowired
private IAdminProduitsMetier metier;
#RequestMapping(value="/index")
public String home(Model model)
{
model.addAttribute("produits",metier.listProduits());
model.addAttribute("categories",metier.listCategories());
model.addAttribute("produit", new Produit());
return "produits";
}
}
AdminCategorieController
#Controller
#RequestMapping(value = "/adminCat")
public class AdminCategorieController implements HandlerExceptionResolver{
#Autowired
IAdminCategoriesMetier metier;
#RequestMapping(value="/index")
public String home(Model model)
{
model.addAttribute("categorie",new Categorie());
model.addAttribute("categories",metier.listCategories());
return "categories";
}
}
Here is the configuration file servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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">
<annotation-driven />
<resources mapping="/resources/**" location="/resources/" />
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="org.aaronlbk.eboutique" />
<beans:bean name="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<beans:property name="maxUploadSize" value="100000"></beans:property>
</beans:bean>
</beans:beans>
The jsp files are strictly differents.
categories.jsp
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="f"%>
<head>
<!-- .getContextPath() contexte du projet -->
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/resources/css/style1.css">
<link href="<c:url value="/resources/css/style1.css" />" rel="stylesheet">
</head>
<body>
<div id="formCat" class="cadre">
<f:form modelAttribute="categorie" action="saveCat" method="post"
enctype="multipart/form-data">
<table class="tab1">
<tr>
<td>ID categorie</td>
<td><f:input path="idCategorie" />
<td><f:errors path="idCategorie" cssclass="errors"></f:errors></td>
</tr>
<tr>
<td>Nom categorie</td>
<td><f:input path="nomCategorie" />
<td><f:errors path="nomCategorie" cssclass="errors"></f:errors></td>
</tr>
</table>
</f:form>
</div>
</body>
produits.jsp
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="f"%>
<head>
<link href="<c:url value="/resources/css/style1.css" />" rel="stylesheet">
</head>
<body>
<div id="formProd" class="cadre">
<f:form modelAttribute="produit" action="saveProd" method="post"
enctype="multipart/form-data">
<table class="tab1">
<tr>
<td>ID Produit</td>
<td><f:input path="idProduit" />
<td><f:errors path="idProduit" cssclass="errors"></f:errors></td>
</tr>
<tr>
<td>Catégorie</td>
<td><f:select path="categorie.idCategorie" items="${categories}" itemValue="idCategorie" itemLabel="nomCategorie"/>
<td><f:errors path="designation" cssclass="errors"></f:errors></td>
</tr>
</table>
</f:form>
</div>
</body>
Why can cause the controller AdminProduitsController to return the page of an other controller ?
Can you please share the URL you are hitting to call the controller ?
May be you can try ModelAndView("viewname")
#RequestMapping(value="/index")
public ModelAndView home(Model model)
{
model.addAttribute("produits",metier.listProduits());
model.addAttribute("categories",metier.listCategories());
model.addAttribute("produit", new Produit());
return new ModelAndView("produits");
}
Related
I got next problem with my application. I want to internationalize my pages. On first page I have problem, because app translate only first variable. Firstly i added messages_en.properties in src/main/resources.
addGame.form.gameId.label = Game ID
addGame.form.gameName.label = Game name
addGame.form.gamePlatform.label = Game platform
addGame.form.gamePrice.label = Game price
addGame.form.gameDescription.label = Game description
addGame.form.gameCategory.label = Game category
addGame.form.gamesInStock.label = Games in stock
addGame.form.condition.label = Game condition
addGame.form.gameImage.label = Game image
Next step was add choice of language in addGame.jsp. It's work good.
<div class="pull-right" style="padding-right:50px">
angielski
</div>
Next step in DispatcherServlet-context.xml added one bean.
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="pl"/>
</bean>
And in same file
<mvc:interceptors>
<bean class= "org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="language"/>
</bean>
</mvc:interceptors>
And last what i do was added language to GameController like this.
#InitBinder
public void initialiseBinder(WebDataBinder binder) {
binder.setDisallowedFields("unitsInOrder", "discontinued");
binder.setAllowedFields("gameId", "gameName", "gamePrice", "gameDescription","gamePlatform", "gameCategory", "gamesInStock", "gameImage", "language");
}
Screen from page
On screenshot you can see my page after click English language. its changing only first variable. Could you tell me why?
Mine code. You can see messages_en.properties up. This is DispatcherServlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven enable-matrix-variables="true"
validator="validator" />
<context:annotation-config />
<mvc:resources mapping="/resource/**" location="/resources/" />
<context:component-scan base-package="com.kk.gamestore" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10240000" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages" />
</bean>
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="json" value="application/json;charset=UTF-8" />
<entry key="xml" value="application/xml;charset=UTF-8" />
<entry key="html" value="text/html;charset=UTF-8" />
</map>
</property>
<property name="defaultViews">
<list>
<ref bean="jsonView" />
<ref bean="xmlView" />
</list>
</property>
</bean>
<bean id="jsonView"
class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
<property name="prettyPrint" value="true" />
</bean>
<bean id="xmlView"
class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>com.kk.gamestore.domain.Game</value>
</list>
</property>
</bean>
</constructor-arg>
</bean>
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="validationMessageSource" ref="messageSource" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="pl" />
</bean>
<mvc:interceptors>
<bean class="com.kk.gamestore.interceptor.PerformanceMonitorInterceptor" />
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property value="language" name="paramName"/>
</bean>
<bean class="com.kk.gamestore.interceptor.AuditingInterceptor" />
<bean class="com.kk.gamestore.interceptor.PromoCodeInterceptor">
<property name="promoCode" value="PROMOGRY" />
<property name="errorRedirect" value="invalidPromoCode" />
<property name="offerRedirect" value="games" />
</bean>
</mvc:interceptors>
</beans>
There is GameController. I added position language in method - setAllowedFields
package com.kk.gamestore.controller;
import java.io.File;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.MatrixVariable;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.kk.gamestore.domain.Game;
import com.kk.gamestore.exception.GameNotFoundException;
import com.kk.gamestore.service.GameService;
#RequestMapping("/games")
#Controller
public class GameController {
#Autowired
private GameService gameService;
#RequestMapping
public String Welcome(Model model) {
model.addAttribute("games", gameService.getAllGames());
return "games";
}
#RequestMapping("/all")
public String allGames(Model model) {
model.addAttribute("games", gameService.getAllGames());
return "games";
}
#RequestMapping("/{platform}")
public String getGamesByPlatform(Model model, #PathVariable("platform") String gamePlatform) {
model.addAttribute("games", gameService.getGamesByPlatform(gamePlatform));
return "games";
}
#RequestMapping("/filter/{ByCriteria}")
public String getGamesByFilter(#MatrixVariable(pathVar="ByCriteria")
Map<String,List<String>> filterParams, Model model){
model.addAttribute("games", gameService.getGamesByFilter(filterParams));
return "games";
}
#RequestMapping("/game")
public String getGamesById(#RequestParam("id") String gameId, Model model){
Game game = gameService.getGameById(gameId);
model.addAttribute("game", game);
return "game";
}
#RequestMapping(value = "/add", method = RequestMethod.GET)
public String getAddNewGameForm(Model model) {
Game newGame = new Game();
model.addAttribute("newGame", newGame);
return "addGame";
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String processAddNewGameForm(#ModelAttribute("newGame") #Valid Game gameToBeAdded, BindingResult result, HttpServletRequest request) {
if(result.hasErrors()) {
return "addGame";
}
String[] suppressedFields = result.getSuppressedFields();
if (suppressedFields.length > 0) {
throw new RuntimeException("Próba wiązania niedozwolonych pól: " + StringUtils.arrayToCommaDelimitedString(suppressedFields));
}
MultipartFile gameImage = gameToBeAdded.getGameImage();
String rootDirectory = request.getSession().getServletContext().getRealPath("/");
if (gameImage!=null && !gameImage.isEmpty()) {
try {
gameImage.transferTo(new File(rootDirectory+"resources\\images\\"+gameToBeAdded.getGameId() + ".png"));
} catch (Exception e) {
throw new RuntimeException("Blad podczas zapisu okladki gry.", e);
}
}
gameService.addGame(gameToBeAdded);
return "redirect:/games";
}
#InitBinder
public void initialiseBinder(WebDataBinder binder) {
binder.setAllowedFields("gameId", "gameName", "gamePrice", "gameDescription","gamePlatform", "gameCategory", "gamesInStock", "gameImage", "condition" , "language");
}
#ExceptionHandler(GameNotFoundException.class)
public ModelAndView handleError(HttpServletRequest req, GameNotFoundException exception) {
ModelAndView mav = new ModelAndView();
mav.addObject("invalidGameId", exception.getGameId());
mav.addObject("exception", exception);
mav.addObject("url", req.getRequestURL()+"?"+req.getQueryString());
mav.setViewName("gameNotFound");
return mav;
}
#RequestMapping("/invalidPromoCode")
public String invalidPromoCode() {
return "invalidPromoCode";
}
}
And AddGame.jsp
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%#page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet"
href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<title>Gry</title>
</head>
<body>
<section>
<div class="jumbotron">
<div class="container">
<h1>Gry</h1>
<p>Dodaj gry</p>
</div>
wyloguj
<div class="pull-right" style="padding-right:50px">
<a href="?language=pl" >polski</a>|<a href="?language=en" >angielski</a>
</div>
</div>
</section>
<section class="container">
<form:form modelAttribute="newGame" class="form-horizontal" enctype="multipart/form-data">
<form:errors path="*" cssClass="alert alert-danger" element="div"/>
<fieldset>
<legend>Dodaj nową grę</legend>
<div class="form-group">
<label class="control-label col-lg-2 col-lg-2" for="gameId">
<spring:message code="addGame.form.gameId.label"/>
</label>
<div class="col-lg-10">
<form:input id="gameId" path="gameId" type="text" class="form:input-large" />
<form:errors path="gameId" cssClass="text-danger"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2 col-lg-2" for="gameName">Nazwa</label>
<div class="col-lg-10">
<form:input id="gameName" path="gameName" type="text" class="form:input-large" />
<form:errors path="gameName" cssClass="text-danger"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2 col-lg-2" for="gamePrice">Cena</label>
<div class="col-lg-10">
<form:input id="gamePrice" path="gamePrice" type="text" class="form:input-large" />
<form:errors path="gamePrice" cssClass="text-danger"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2" for="gamePlatform">Platforma Gry</label>
<div class="col-lg-10">
<form:radiobutton path="gamePlatform" value="PS4" />
Playstation 4
<form:radiobutton path="gamePlatform" value="XBOX ONE" />
Xbox One
<form:radiobutton path="gamePlatform" value="PS3" />
Playstation 3
<form:radiobutton path="gamePlatform" value="XBOX 360" />
Xbox 360
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2 col-lg-2" for="gameCategory">Kategoria</label>
<div class="col-lg-10">
<form:input id="gameCategory" path="gameCategory" type="text" class="form:input-large" />
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2 col-lg-2" for="gamesInStock">Liczba gier w magazynie</label>
<div class="col-lg-10">
<form:input id="gamesInStock" path="gamesInStock" type="text" class="form:input-large" />
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2" for="gameDescription">Opis</label>
<div class="col-lg-10">
<form:textarea id="gameDescription" path="gameDescription" rows="2"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2" for="condition">Stan</label>
<div class="col-lg-10">
<form:radiobutton path="condition" value="New" />
Nowy
<form:radiobutton path="condition" value="Old" />
Używany
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2" for="gameImage">
<spring:message code="addProdcut.form.gameImage.label"/>
</label>
<div class="col-lg-10">
<form:input id="gameImage" path="gameImage" type="file" class="form:input-large" />
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<input type="submit" id="btnAdd" class="btn btn-primary" value="Dodaj" />
</div>
</div>
</fieldset>
</form:form>
</section>
</body>
</html>
I haven't idea what i doing wrong. Button of changing language working well, but it's translate only first variable no more. On screen you can see en version (not default) and it changed only first variable and next variable name its from default lang. I haven't problems in console when running application just one warning like this.
WARNING: [SetContextPropertiesRule]{Context} Setting property 'source' to 'org.eclipse.jst.jee.server:gamestoreCOPIED' did not find a matching property.
#EDIT:
Hi, after few days coding and repairing errors im back there. I got new informations.
PROBLEM : Application working good.
Locale change button working good. After click on this button application generate link (if english button click: http://localhost:8080/gamestore/games/add?language=en or if polish: add?language=pl)
and language are changing.
When i want change it on english language it translate me only first word of messages_en.properties. When i make english language default - its same situation - only first word its changing.
In console 0 errors only one warning but its nothing in this topic.
Problem is when i try change language on english or use on default english its change only first line of messages_en.properties.
If i change ResourceBundleMessageSource for ReloadableResourceBundleMessageSource(with changing classpath and make it good)
nothing changed.
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
I need this line.
<mvc:annotation-driven enable-matrix-variables="true"
So i can't make mine app with HandlerMapping. But if i do it its not working.
I read a lot of informations and trying find answer in network but nothing work. Anyone got similiar problems in past?
I am using Spring MVC (3.2.2.RELEASE) and Spring Security (3.2.2.RELEASE).
I'm trying to do a basic login using spring security, but every time I receive an exception 'HTTP Status 405 - Request method 'POST' not supported'. I already tried searching for similar issues but I was not able to find any solutions.
Following is my code:
login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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" />
</head>
<body>
<c:if test="${not empty error}">
<div>
<p style="color: red;">${error}</p>
</div>
</c:if>
<c:if test="${not empty message}">
<div>
<p style="color: red;">${message}</p>
</div>
</c:if>
<c:url var="loginUrl" value="/login" />
<form action="${loginUrl}" method="post">
<div>
<table>
<tr>
<td><label for="username">Email</label></td>
<td><input type="text" id="nombre" name="nombre" placeholder="Enter Name" required></td>
</tr>
<tr>
<td><label for="password">Password</label></td>
<td><input type="password" id="password" name="password" placeholder="Enter Password" required></td>
</tr>
</table>
</div>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
<div>
<input type="submit" value="Log In">
</div>
</form>
</body>
</html>
SecurityConfig.java
package com.bitacora.config;
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login").defaultSuccessUrl("/bitacora")
.failureUrl("/login?error")
.usernameParameter("nombre").passwordParameter("password")
.and()
.logout()
.logoutSuccessUrl("/login?logout").permitAll()
.and()
.csrf();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("123").roles("USER", "ADMIN");
}
}
MvcWebApplicationInitializer.java
package com.it2.config.core;
public class MvcWebApplicationInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { SecurityConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
SecurityWebApplicationInitializer.java
package com.bitacora.config.core;
public class SecurityWebApplicationInitializer extends
AbstractSecurityWebApplicationInitializer {
public SecurityWebApplicationInitializer() {
super(SecurityConfig.class);
}
}
LoginController.java
package com.bitacora.controller;
#Controller
public class LoginController extends HttpServlet {
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView loginPage(#RequestParam(value = "error",required = false) String error) {
ModelAndView model = new ModelAndView();
if (error != null) {
model.addObject("error", "Invalid Email OR Password");
}
model.setViewName("login");
return model;
}
}
bitacora-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.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.xsd">
<context:component-scan base-package="com.bitacora" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:resources mapping="/img/**" location="/img/" />
<mvc:resources mapping="/css/**" location="/css/" />
<mvc:annotation-driven />
<import resource="classpath://Spring.xml"/>
</beans>
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>BitacoraWEB</display-name>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>bitacora</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>bitacora</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Because your service(Controller) login operation is a get operation but your UI (view) is sending a post request
#RequestMapping(value = "/login", method = RequestMethod.GET)
you should change this to
#RequestMapping(value = "/login", method = RequestMethod.POST)
keep your UI (View) as is ( which is with method="post")
<form:form id="loginForm" method="post" action="${loginUrl}"
modelAttribute="loginBean">
You are posting your login information to /login, but the default login processing URL in Spring Security 3.2 is /j_spring_security_check.
Change in your form:
<c:url var="loginUrl" value="/j_spring_security_check" />
Or set login processing URL explicit:
.formLogin()
.loginProcessingUrl("/login")
...
How to do that when submiting my form at JSP page it will not reload? Here is user sending message and AJAX script (its in my jsp) get back all messages for user. But when i send message (do POST method) it refreshing my page that take some time to loading all messages with AJAX.
Help pls!!!
This is my JSP page
<%# page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://www.springframework.org/security/tags"
prefix="security"%>
<%#taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Сообщения | Haine and Vold</title>
<link rel="shortcut icon" href="<c:url value="/resources/faviicon/iconHV.ico"/>" type="image/x-icon">
<link href="<c:url value="/resources/bootstrap/bootstrap.css"/>"
rel="stylesheet" type="text/css">
<link href="<c:url value="/resources/CSS/styles.css"/>" rel="stylesheet"
type="text/css">
<link href="<c:url value="/resources/CSS/tableMessFixedHeader.css"/>" rel="stylesheet"
type="text/css">
<script src="<c:url value="/resources/Angular/angular.min.js"/>"></script>
</head>
<body>
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed"
data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span> <span
class="icon-bar"></span> <span class="icon-bar"></span> <span
class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Haine and Vold</a>
</div>
<div class="collapse navbar-collapse"
id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="dropdown"><a href="#" class="dropdown-toggle"
data-toggle="dropdown" role="button" aria-expanded="false"><spring:message
code="label.menuprofile" /><span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="/haine/user"><spring:message
code="label.menuprofile" /></a></li>
<li><a href="/haine/user/updateinfo"><spring:message
code="label.menusettinginfo" /></a></li>
</ul></li>
<li><a href="/haine/user/messages"><spring:message
code="label.menumessages" /> (${allUserMess})</a></li>
<li><a href="/haine/user/search"><spring:message
code="label.menusearch" /></a></li>
<li class="dropdown"><a href="#" class="dropdown-toggle"
data-toggle="dropdown" role="button" aria-expanded="false"><spring:message
code="label.menuinformation" /><span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="/haine/user/rules"><spring:message
code="label.menurules" /></a></li>
<li class="divider"></li>
<li><a href="/haine/user/feedback"><spring:message
code="label.menusendfeedback" /></a></li>
</ul></li>
<security:authorize ifAnyGranted="ROLE_ADMIN">
<li class="dropdown"><a href="#" class="dropdown-toggle"
data-toggle="dropdown" role="button" aria-expanded="false"><spring:message
code="label.menuadministration" /><span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="/haine/admin"><spring:message
code="label.menuadminpanel" /></a></li>
<li><a href="/haine/admin/feedbacklist"><spring:message
code="label.menufeedbacks" />(${countOfFeedbacks})</a></li>
<li><a href="/haine/admin/newusers"><spring:message
code="label.newusers" />(${countOfNewUsers})</a></li>
</ul></li>
</security:authorize>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="?locale=ru"><img
src="<c:url value="/resources/languageicons/rus.png"/>"
alt="Russian Language" title="Сменить язык интерфейса на русский"></a>
</li>
<li><a href="?locale=en"><img
src="<c:url value="/resources/languageicons/usa.png"/>"
alt="USA Language" title="Change interface language to american"></a>
</li>
</ul>
<c:url var="logoutUrl" value="/j_spring_security_logout" />
<form class="navbar-form navbar-right" action="${logoutUrl}"
method="post">
<button class="btn btn-default" type="submit">
<spring:message code="label.logoutbutton" />
</button>
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
</form>
</div>
</div>
</nav>
<div class="container">
<img class="img-responsive logo" src="/haine/resources/logo.jpg">
</div>
<br>
<div class="scrollTableMessages" id="mess">
</div>
<form:form method="POST" modelAttribute="message"
accept-charset="utf-8" ng-app="vandh" ng-controller="validateCtrl"
name="messageForm" novalidation="true">
<form:textarea path="text" class="form-control" rows="1"
id="message" ng-model="message" required="true"></form:textarea>
<div style="color: black"
ng-show="messageForm.message.$dirty && messageForm.message.$invalid">
<span ng-show="messageForm.message.$error.required"><spring:message
code="label.entermessage" /></span>
</div>
<br>
<div class="text-center">
<button class="btn btn-success" type="submit"><spring:message
code="label.sendmessage"/></button>
</div>
</form:form>
<script>
var app = angular.module('vandh', []);
app.controller('validateCtrl', function($scope) {
$scope.message = '';
});
</script>
</body>
<script src="<c:url value="/resources/Jquery/jquery-2.1.4.min.js"/>"
type="text/javascript"></script>
<script src="<c:url value="/resources/bootstrap/bootstrap.js"/>"
type="text/javascript"></script>
<script>
</script>
<script>
var oldC = 0, newC = -1;
function getMessages() {
$.ajax({
type : 'GET',
url : '/haine/user/countofmess/${iddialog}',
success : function(rs)
{
newC = rs;
if(oldC != newC)
{
$.ajax({
type : 'GET',
url : '/haine/user/mess/${iddialog}',
success : function(r)
{
$('#mess').html(r);
document.getElementById("mess").scrollTop = 9999;
console.log(r);
},
error : function(r) {
alert(r);
}
});
oldC = newC;
}
},
error : function(rs) {
alert(rs);
}
});
}
setInterval(getMessages, 1000);
</script>
</html>
And this is my controller
#RequestMapping(value = "/user/messages/{iddialog}", method = RequestMethod.POST)
public String messages(#ModelAttribute("message") Message message, #RequestParam(value = "text") String text,
#PathVariable(value = "iddialog") int iddialog, Model model, Principal principal) {
if(checkingMessage(text)!=true)
{
sendMessage(iddialog, text, principal.getName());
System.out.println("message sent!");
return "messagesWithUser";
}
else
{
return "redirect:/user/messages";
}
}
It depends on your Spring version.
if you are using Spring 3, JQuery you could do someting like this:
JSP
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!doctype html>
<html lang="es" >
<head></head>
<body>
Your Name: <input type='text' id='name'>
<button id='send-button'>Send</button>
<div id='state-bar'></div>
<script>
window.onload=function() {
var stateBar=$("#state-bar");
var name=$("#name");
var sendButton=$("#send-button");
sendButton.click(function( event ) {
var parameters={
name: name.val()
};
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parameters),
dataType: "json",
url: "myPage.htm",
success: function (data) {
stateBar.html(data.response);
}, error: function(data){
stateBar.html("Server Error.");
}
});
});
}
</script>
<script src="resources/js/jquery.js"></script>
</body>
Controller Class
package com.company.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
public class TestController {
#RequestMapping(value="/testPage.htm",method=RequestMethod.GET)
public String testPage(){
return "testPage";
}
#RequestMapping(value="/myPage.htm",method=RequestMethod.POST)
#ResponseBody
public MyPageResponse myPage(#RequestBody MyPageModel myPageModel){
MyPageResponse res= new MyPageResponse();
res.setResponse("Your name is : "+myPageModel.getName());
return res;
}
}
Input VO
package com.company.controllers;
public class MyPageModel {
private String name="";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Output VO
package com.company.controllers;
public class MyPageResponse {
private String response="";
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
}
web.xml
<servlet>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
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:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:component-scan base-package="com.company" />
<mvc:interceptors>
<bean id="webContentInterceptor" class="org.springframework.web.servlet.mvc.WebContentInterceptor">
<property name="cacheSeconds" value="0"/>
<property name="useExpiresHeader" value="true"/>
<property name="useCacheControlHeader" value="true"/>
<property name="useCacheControlNoStore" value="true"/>
</bean>
</mvc:interceptors>
<mvc:annotation-driven />
<!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
It's happening because the default action for a submit button is sending the request as a normal request (not ajax).
You have to change your form to:
<form onsubmit="return false;" class="navbar-form navbar-right" action="${logoutUrl}"
method="post">
<button onclick="function_ajax_to_send_form()" class="btn btn-default" type="submit">
<spring:message code="label.logoutbutton" />
</button>
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
</form>
Below are my pages, please do help.
home.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>Insert title here</title>
<link type="text/css" rel="stylesheet" href="css/homepage.css">
<link type="text/css" rel="stylesheet" href="css/datepickerJqueryUI.css">
<script src="js/homepage.js"></script>
<script src="js/jquery.js"></script>
<script src="js/jquery-1.7.1.min.js"></script>
<script src="js/jquery.datepicker.min.js"></script>
<script>
$(function() {
$( "#datepickerDeparture" ).datepicker();
});
$(function() {
$( "#datepickerReturn" ).datepicker();
})
</script>
</head>
<body>
<div class="headerBackground">
<!-- Headers for Logo and menu items -->
<div class="header">
<div class="logo"></div>
<div class="menu">
Menu List Items
</div>
</div>
</div>
<!-- Division for items between the logo header and footer -->
<div class="body">
<!-- Division for search -->
<div class="searchBox" >
<form action="search" method="get" name="searchBus">
<div class="searchLeavingFrom">Leaving from : <input type="text" name="from" class="txtBox"><h6 id="leavingFrom" class="errorMsg"></h6></div>
<div class="searchGoingTo">Going To :<input type="text" name="destination" class="txtBox"><h6 id="destination" class="errorMsg"></h6></div>
<div class="searchDepartOn">Depart On:<input type = "text" name="departureDate" class="txtBox" id="datepickerDeparture"><h6 id="departure" class="errorMsg"></h6></div>
<div class="searchReturn">Return On:<input type = "text" name="returnDate" class="txtBox" id="datepickerReturn"></div>
<div><input type="button" name="search" value="Search Buses" class="searchBtn" onClick="validateForm()"></div>
</form>
</div>
</div>
<!-- Division for footer -->
<div>
</div>
</body>
</html>
web.xml
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>TicketStore</display-name>
<welcome-file-list>
<welcome-file>home.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>TicketStore</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/TicketStore-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<!--- my servlet mapping if we put as .jsp it doesnt run at all i mean homepage doesnt display at all-->
</servlet>
<servlet-mapping>
<servlet-name>TicketStore</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
TicketStore-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean
class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />
<bean name="search" id="search" class="com.ticketgoose.controller.SearchDetails">
<property name="formView" value="home" />
<property name="successView" value="searchBuses" />
</bean>
<!-- Register the Customer.properties -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
SearchDetails.java
package com.ticketgoose.controller;
import com.ticketgoose.form.SearchForm;
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.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
#Controller
#SessionAttributes
public class SearchDetails {
#RequestMapping (value = "/search", method = RequestMethod.GET)
public String addContact(#ModelAttribute("searchDetails")
SearchForm searchDetails, BindingResult result){
System.out.println("From:" + searchDetails.getFrom() +
" To:" + searchDetails.getDestination());
return "redirect:searchBus.html";
}
#RequestMapping("/searchBus")
public ModelAndView showContacts() {
return new ModelAndView("searchDetails", "command", new SearchForm());
}
}
searchBuses.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Success Page</title>
</head>
<body>
User Details
<hr>
From : ${user.name}
To : ${user.gender}
Date of jourey: ${user.country}
Return journey: ${user.aboutYou}
</body>
</html>
This is my form:
SearchForm.java
package com.ticketgoose.form;
import java.sql.Date;
public class SearchForm {
String from;
String destination;
Date departureDate;
Date returnDate;
//getter setters
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getDestination() {
return destination;
}
public void getDestination(String Destination) {
this.destination = Destination;
}
public Date getDepartureDate() {
return departureDate;
}
public void setDepartureDate(Date departureDate) {
this.departureDate = departureDate;
}
public Date getReturnDate() {
return returnDate;
}
public void setReturnDate(Date returnDate) {
this.returnDate = returnDate;
}}
Please help me solve this, I couldn't figure out the problem at all.
Is you application running under an application context on the web server?
Try this:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<form action="<c:url value="/search" />" method="get" name="searchBus">
The action of form say action="search" :
<form action="search" method="get" name="searchBus">
But, in your web.xml your mapping for spring is *.do :
<servlet-mapping>
<servlet-name>TicketStore</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
Change action="search" by action="search.do"
or change the mapping by ( not recommended )
<servlet-mapping>
<servlet-name>TicketStore</servlet-name>
<url-pattern>*</url-pattern>
</servlet-mapping>
I try to configure facebook integration. But i did't recive accesToken properly. I recieved null. Logger show me variables AccesToken and UserID and it null.
so here my config.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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.1.xsd">
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="customArgumentResolver" ref="facebookWebArgResolver" />
</bean>
<bean id="facebookWebArgResolver"
class="org.springframework.social.facebook.FacebookWebArgumentResolver">
<constructor-arg name="apiKey" value="${facebook.appId}"/>
</bean>
</beans>
And this is my callback controller with FacebookProvider and jsp page.
#Controller
public class SocialTutorial {
private static final Logger LOG = Logger.getLogger(SocialTutorial.class);
#Autowired
FacebookProvider facebookProvider;
#RequestMapping(value = "/connect/facebook", method = RequestMethod.POST)
public String connectAccountToFacebook(#FacebookAccessToken String accessToken, #FacebookUserId String facebookUserId) {
LOG.error("HERE facebook authnticate:" + accessToken + " And user id:" + facebookUserId);
return "redirect:/pages/social.jsp";
}
}
Provider
#Repository("facebookProvider")
public class FacebookProvider {
#Value("${facebook.appId}")
private String apiKey;// = "240362226072898";
#Value("${facebook.appSecret}")
private String appSecret;// = " ";
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String getAppSecret() {
return appSecret;
}
public void setAppSecret(String appSecret) {
this.appSecret = appSecret;
}
public FacebookTemplate createTemplate(String accesToken) {
return new FacebookTemplate(accesToken);
}
}
JSP page
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib prefix='c' uri='http://java.sun.com/jstl/core_rt'%>
<%# taglib prefix="sec"
uri="http://www.springframework.org/security/tags"%>
<%# taglib
uri="http://www.springframework.org/spring-social/facebook/tags"
prefix="facebook"%>
<%# page contentType="text/html;charset=UTF-8" language="java"%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Update Status</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"
type="text/javascript"></script>
</head>
<body>
Logout
<h2>Services</h2>
<!-- FACEBOOK -->
<c:if test="${connectedToFacebook}">
Connected to Facebook as <c:out
value="${facebookProfile.firstName }" />
<c:out value="${facebookProfile.lastName }" />
</c:if>
<c:if test="${!connectedToFacebook}">
<%/* Connect to Facebook */ %>
<form id="fb_signin" action="<c:url value="/connect/facebook" />"
method="post">
<div class="formInfo"></div>
<div id="fb-root"></div>
<p>
<fb:login-button perms="email,publish_stream,offline_access"
onlogin="$('#fb_signin').submit();" v="2" length="long">Connect to Facebook</fb:login-button>
</p>
</form>
<facebook:init />
</c:if>
<br />
</body>
</html>
Try this. It should work for you:
FacebookConnectionFactory connectionFactory =
new FacebookConnectionFactory("clientId", "clientSecret");
OAuth2Operations oauthOperations = connectionFactory.getOAuthOperations();
OAuth2Parameters params = new OAuth2Parameters();
params.setRedirectUri("https://my-callback-url");
String authorizeUrl = oauthOperations.buildAuthorizeUrl(GrantType.AUTHORIZATION_CODE, params);
response.sendRedirect(authorizeUrl);
// upon receiving the callback from the provider:
AccessGrant accessGrant = oauthOperations.exchangeForAccess(authorizationCode, "https://my-callback-url", null);
Connection<Facebook> connection = connectionFactory.createConnection(accessGrant);
For more information try this.