У меня возникли проблемы с попыткой отправить форму весной. Каждый раз, когда я пытаюсь, я получаю ошибку 404. Это мой контроллер:404 ошибка при отправке формы весны
@Controller
@RequestMapping("/admin/news")
public class NewsController {
@Autowired
private NewsService newsService;
@RequestMapping(value = "/create", method = RequestMethod.GET)
public String createNews(Model model) {
return "admin.news.create";
}
@RequestMapping(value = "/list", method = RequestMethod.GET)
public ModelAndView listNews(Model model) {
return listNews(1);
}
@RequestMapping(value = "/list/{pageIndex}", method = RequestMethod.GET)
public ModelAndView listNewsPage(@PathVariable int pageIndex) {
return listNews(pageIndex);
}
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String saveNews(@Valid NewsDto newsDto, BindingResult bindingResult, Model model) {
if (!bindingResult.hasErrors()) {
newsService.save(newsDto);
model.addAttribute("created", true);
model.addAttribute("news", newsDto);
}
return "admin.news.create";
}
private ModelAndView listNews(int pageIndex) {
ModelAndView modelAndView = new ModelAndView("admin.news.list");
Page page = newsService.findAll(pageIndex);
modelAndView.addObject("page", page);
return modelAndView;
}
@ModelAttribute("news")
private NewsDto newsDtoModel() {
return new NewsDto();
}
}
И это форма (я использую Apache Tiles):
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="spring" %>
<div id="page-header">
<h3>Create a news</h3>
</div>
<div id="page-content">
<div class="panel">
<div class="panel-heading">
News creation form
</div>
<div class="panel-content">
<spring:form method="post" commandName="news" action="save">
<spring:input path="title" class="u-full-width" type="text" placeholder="Title of the news" required="true" />
<spring:errors path="title" cssClass="validation-error" />
<spring:textarea path="text" class="u-full-width" placeholder="News text" required="true" />
<spring:errors path="text" cssClass="validation-error" />
<input class="button-primary" type="submit" value="Submit" />
</spring:form>
</div>
</div>
</div>
Я прочитал и перепробовал все решения, которые я нашел в SO родственный с этой ошибкой без везения, и я также пробовал все возможные комбинации маршрутов в действии формы, но я всегда получаю эту ошибку 404. Вот заголовок:
GET/админ/Новости/сохранить HTTP/1.1 Host: MYSERVER: 8080 Accept: текст/HTML, приложение/XHTML + XML, приложение/XML; д = 0,9, изображение/WebP , /; д = 0,8 Accept-Encoding: GZIP, выкачать, SDCH Accept-Language: ан-США, ан; Q = 0,8, ES; д = 0,6 Печенье: JSESSIONID = 2A3446E8A0A42C49B0ECF8EE2C38C917 ДНТ: 1 Referer: MyServer: 8080/админ User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64 ) AppleWebKit/537,36 (KHTML, как Gecko) Chrome/39.0.2171.95 Safari/537,36
HTTP/1.1 404 Not Found Cache-Control: no-cache, no-store, max-age = 0, must-revalidate Content-Language: en Content-Length: 1000 Content-Type: text/html; charset = UTF-8 Дата: Пт, 19 Дек 2014 17:11:24 GMT Истекает: 0 Pragma: no-cache Сервер: Apache-Coyote/1.1 X-Content-Type-Options: nosniff X-Frame-Options: DENY X-XSS-Protection: 1; режим = блок
Любая идея?
EDIT 1: Я добавлю здесь свои конфиги.
ApplicationContext:
@Configuration
@ComponentScan("com.davidmogar.alsa")
@PropertySource("classpath:application.properties")
@Import({WebMvcContext.class, PersistenceContext.class, SecurityContext.class})
public class ApplicationContext {
private static final String MESSAGE_SOURCE_BASE_NAME = "i18n/messages";
@Bean
MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename(MESSAGE_SOURCE_BASE_NAME);
messageSource.setUseCodeAsDefaultMessage(true);
return messageSource;
}
@Bean
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
WebAppInitializer:
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
private static final String CHARACTER_ENCODING_FILTER_ENCODING = "UTF-8";
private static final String DISPATCHER_SERVLET_MAPPING = "/";
@Override
protected WebApplicationContext createRootApplicationContext() {
WebApplicationContext context = super.createRootApplicationContext();
// ConfigurableEnvironment env = (ConfigurableEnvironment) context.getEnvironment();
// env.setActiveProfiles();
return context;
}
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{ApplicationContext.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
@Override
protected String[] getServletMappings() {
return new String[]{DISPATCHER_SERVLET_MAPPING};
}
@Override
protected Filter[] getServletFilters() {
DelegatingFilterProxy delegatingFilterProxy = new DelegatingFilterProxy();
delegatingFilterProxy.setTargetBeanName("springSecurityFilterChain");
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding(CHARACTER_ENCODING_FILTER_ENCODING);
characterEncodingFilter.setForceEncoding(true);
OpenEntityManagerInViewFilter openEntityManagerInViewFilter = new OpenEntityManagerInViewFilter();
HiddenHttpMethodFilter hiddenHttpMethodFilter = new HiddenHttpMethodFilter();
return new Filter[]{delegatingFilterProxy, characterEncodingFilter, openEntityManagerInViewFilter,
hiddenHttpMethodFilter};
}
}
EDIT 2:
Здесь отображение URL:
INFO - questMappingHandlerMapping - сопоставлено «{[/ admin/news/save], methods = [POST], params = [], headers = [], consumes = [], производит = [], custom = []} " на public java.lang.String com.davidmogar.alsa.web.admin.news.NewsController.saveNews (com.davidmogar.alsa.dto.news.NewsDto, org.springframework.validation.BindingResult, org .springframework.ui.Model)
hows your web.xml ищет? – SMA
@almasshaikh Я не использую web.xml. Я добавил некоторые файлы конфигурации в OP. –
Вы могли бы проверить, сохраняет ли он объект? GET to/create работает нормально? –