提交弹簧形式时404错误

时间:2014-12-19 17:16:14

标签: spring forms spring-mvc http-status-code-404

我在尝试在Spring中提交表单时遇到了一些问题。每次我尝试我都会收到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 / admin / news / save HTTP / 1.1主机:myserver:8080接受:   text / html的,应用/ XHTML + xml的,应用/ XML; Q = 0.9,图像/ WEBP, / 的; Q = 0.8   Accept-Encoding:gzip,deflate,sdch Accept-Language:   en-US,en; q = 0.8,es; q = 0.6 Cookie:   JSESSIONID = 2A3446E8A0A42C49B0ECF8EE2C38C917 DNT:1 Referer:   myserver:8080 / admin用户代理: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,   必须重新验证内容 - 语言:内容长度:1000   内容类型:text / html; charset = UTF-8日期:星期五,2014年12月19日17:11:24   GMT到期:0 Pragma:无缓存服务器:Apache-Coyote / 1.1   X-Content-Type-Options:nosniff X-Frame-Options:DENY   X-XSS-Protection:1;模式=块

有什么想法吗?

编辑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};
}

}

编辑2:

以下是网址的映射:

  

INFO - questMappingHandlerMapping - 映射   “{[/管理/消息/保存],方法= [POST],则params = [],标题= [],消耗= [],产生= [],定制= []}”   到公共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)

2 个答案:

答案 0 :(得分:1)

您的错误消息中的请求显示:

  

GET / admin / news / save HTTP / 1.1主机:myserver:8080接受:

它应该是一个POST,因为你只配置了你的controller / admin / news / save来处理POST

  

@RequestMapping(value =“/ save”,method = RequestMethod.POST)

您确定列出了正确的错误消息吗?您的jsp / html代码看起来是正确的,您如何提交表单?

答案 1 :(得分:0)

原来这个问题是由配置错误引起的。我不得不重写应用程序初始化程序以使其工作,但我还不确定问题是什么。这是新的初始化程序:

public class WebAppInitializer implements WebApplicationInitializer {

    private static final String CHARACTER_ENCODING_FILTER_ENCODING = "UTF-8";
    private static final String CHARACTER_ENCODING_FILTER_NAME = "characterEncoding";
    private static final String CHARACTER_ENCODING_FILTER_URL_PATTERN = "/*";

    private static final String DISPATCHER_SERVLET_NAME = "dispatcher";
    private static final String DISPATCHER_SERVLET_MAPPING = "/";

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(ApplicationContext.class);

        configureDispatcherServlet(servletContext, rootContext);
        EnumSet<DispatcherType> dispatcherTypes = EnumSet.of(DispatcherType.REQUEST,     DispatcherType.FORWARD);
        configureCharacterEncodingFilter(servletContext, dispatcherTypes);
        servletContext.addListener(new ContextLoaderListener(rootContext));
    }

    private void configureDispatcherServlet(ServletContext servletContext, WebApplicationContext rootContext) {
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
                DISPATCHER_SERVLET_NAME,
                new DispatcherServlet(rootContext)
        );
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping(DISPATCHER_SERVLET_MAPPING);
    }

    private void configureCharacterEncodingFilter(ServletContext servletContext, EnumSet<DispatcherType> dispatcherTypes) {
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding(CHARACTER_ENCODING_FILTER_ENCODING);
        characterEncodingFilter.setForceEncoding(true);
        FilterRegistration.Dynamic characterEncoding = servletContext.addFilter(CHARACTER_ENCODING_FILTER_NAME, characterEncodingFilter);
        characterEncoding.addMappingForUrlPatterns(dispatcherTypes, true, CHARACTER_ENCODING_FILTER_URL_PATTERN);
    }

}