案例二:使用控制器进行请求处理
- 创建类,实现Controller接口
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
public class HelloController implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
String username = request.getParameter("username");
ModelAndView mv = new ModelAndView();
mv.setViewName("hello.jsp");
mv.addObject("username",username);
return mv;
}
}
ModelAndView
1)控制器处理方法的返回值如果为 ModelAndView, 则其既包含视图信息,也包含模型数据信息
2)添加模型数据:
MoelAndView addObject(String attributeName, Object attributeValue)
ModelAndView addAllObject(Map<String, ?> modelMap)
3)设置视图:
void setView(View view)
void setViewName(String viewName)
- 在springmvc.xml中,设置请求url到Controller的映射
<bean name="/hello.action" class="com.yy.controller.HelloController"></bean>
- 测试,通过在地址栏中输入:/hello.action