Jsp ViewResolver在基于java配置的spring应用程序中不起作用

时间:2015-04-04 13:15:45

标签: java spring jsp controller web-application-project

我在Spring Application中只有基于Java的配置。我创建了用户实体和Dao来查找/创建用户。 控制器有两个GET方法 - 一个用于用户,一个用于用户列表,一个POST方法 - 用于创建/编辑用户。

在Tomcat 7服务器上运行后,它会出现404错误并显示“请求的资源不可用。”

Dispatcher servlet在SpringWebAppInitializer.class中配置:

public class SpringWebAppInitializer  implements WebApplicationInitializer {

 @Override
 public void onStartup(ServletContext servletContext) throws ServletException {

    AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
    appContext.register(ApplicationContextConfig.class);

    servletContext.addListener(new ContextLoaderListener(appContext));

    AnnotationConfigWebApplicationContext dispatcherContext =  new AnnotationConfigWebApplicationContext();
    dispatcherContext.register(DispatcherServlet.class);

    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("SpringDispatcher", new DispatcherServlet(dispatcherContext));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");    
    }
}

视图解析器在ApplicationContextConfig.class中定义:

@Configuration
@ComponentScan("pl.wybornie.entity")
@EnableTransactionManagement
public class ApplicationContextConfig extends WebMvcConfigurerAdapter {

@Bean(name = "viewResolver")
public InternalResourceViewResolver getViewResolver() {

    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setPrefix("/WEB-INF/pages/");
    viewResolver.setSuffix(".jsp");
    return viewResolver;
    }
 //other configuration beans...
}

userList和userForm的Jsp文件位于WebContent项目的文件夹下:/ WEB-INF / pages / user / *。jsp

负责制作视图的控制器粘贴在下面:

@Controller
@SessionAttributes({"user"})
public class UserController {

@Autowired
private UserDao userDao;

@RequestMapping(value = "/user_list.html", method = RequestMethod.GET)
public String list(Model model, HttpServletRequest request) {
    model.addAttribute("userList", userDao.usersList());

    return "user/userList";
}

@RequestMapping(value = "/create.html", method = RequestMethod.GET)
public String edit(@RequestParam(value="id", required=false) Long id, Model model) {
    User user = userDao.findOrCreate(id);       
    model.addAttribute("user", user);
    return "user/userForm";
}

@RequestMapping(method = RequestMethod.POST)
public String submitForm(@ModelAttribute("user") User user, BindingResult bindingResult, HttpServletRequest request, Model model) {

    userDao.saveOrUpdate(user);

    return "redirect:user_list.html";
}

  public void setUserDao(UserDao userDao) {
    this.userDao = userDao;
  }
}

1 个答案:

答案 0 :(得分:3)

  

您的课程应该扩展WebMvcConfigurerAdapter类。

@Configuration
@ComponentScan("pl.wybornie.entity")
@EnableWebMvc
public class ApplicationContextConfig extends WebMvcConfigurerAdapter{


}