我有以下用户控制器:
@RequestMapping("/user")
public class UserController {
private static final String ID = "id";
private final Log logger = LogFactory.getLog(getClass());
private UserManager um;
@Autowired
public void setUserManager(UserManager userManager) {
this.um = userManager;
}
@RequestMapping(method = RequestMethod.GET)
public ModelAndView showUser(HttpServletRequest request) {
User user = null;
String id = (String) request.getParameter(ID);
if (id == null) {
String message = "Cannot find user id";
logger.error(message);
return new ModelAndView("WEB-INF/jsp/error.jsp", "message", message);
}
try {
user = (User) um.getUserByUserId(Integer.parseInt(id));
} catch (Exception e) {
String message = "Cannot find user with id: " + id;
logger.error(message);
return new ModelAndView("WEB-INF/jsp/error.jsp", "message", message);
}
logger.info("Returning user view for user id: " + id);
return new ModelAndView("WEB-INF/jsp/user.jsp", "user", user);
}
@RequestMapping(value = "/new", method = RequestMethod.GET)
public ModelAndView getNewUserForm(Model model) {
logger.info("Get new user form");
return new ModelAndView("WEB-INF/jsp/userForm.jsp", "user", new User());
}
我的所有视图文件都在WEB-INF / jsp /
中当我尝试转到页面时:localhost:8080 / myapp / user.htm一切正常但是当我尝试转到:localhost:8080 / myapp / user / new.htm我收到错误404页面未找到。
这个代码执行的原因是因为我看到了日志:
@RequestMapping(value = "/new", method = RequestMethod.GET)
public ModelAndView getNewUserForm(Model model) {
logger.info("Get new user form");
return new ModelAndView("WEB-INF/jsp/userForm.jsp", "user", new User());
}
在404错误页面上是信息: /myapp/user/WEB-INF/userForm.jsp not foud
这是我的问题。如何将其更改为:/myapp/WEB-INF/userForm.jsp?我的请求映射应该怎么办?
答案 0 :(得分:0)
看一下关于控制器和返回类型的Spring Documentation。 那里有很好的例子,你可以看到很多方法可以使用控制器方法。
在您的情况下,您无需指定视图的完整路径。只是视图名称没问题。
@RequestMapping(value = "/new", method = RequestMethod.GET)
public ModelAndView getNewUserForm(Model model) {
logger.info("Get new user form");
return new ModelAndView("userForm", "user", new User());
}
你甚至可以这样做。 Spring允许多种可能性。文档概述了所有这些:
@RequestMapping(value = "/new", method = RequestMethod.GET)
public String getNewUserForm(Model model) {
logger.info("Get new user form");
model.addAttribute("user", new User());
return "userForm";
}
另外,请确保已配置View Resolver。 您可以从文档中看到您需要这样的东西。
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>