发表于: 2017-04-22 20:26:10
2 1220
【说明】今天上午详细了解了一下frontcontroller(despacherservlet)的加载和处理流程,对springmvc有了更深的认识; 下午做了controller层的实现;晚上稍微做了一下总结和规划
一:今日完成
1)springmvc的请求模型
首先是用户所有的http请求都会请求到dispatcherServlet,然后把请求交给 控制器(controller),同时在初始化dispatcherServlet 也会附带处理其他的工作,例如初始化 view解析器 主题theme 等。
附上一张图片
2)controller 方法传值方法
方法1:在参数中加一个model,直接把值放进去就可以了
@RequestMapping(value = "/hello",method = RequestMethod.GET)
public String hello(Model model){
// 在jsp中直接用EL访问hello即可
model.addAttribute("hello","world1");
// 默认的key是参数类型
model.addAttribute("world2");
return "hello";
}
在对应的jsp中可以如下获取
<h1 style="text-align: center">Hello World!${hello}----${string}</h1
方法2;使用ModelAndView
@RequestMapping(value = "/hello",method = RequestMethod.GET)
public ModelAndView hello(){
ModelAndView model = new ModelAndView();
//设置返回视图名称
model.setViewName("hello");
//传值
model.addObject("hello","world1");
//传值
model.addObject("world2");
return model;
}
3)request方法
request.getSchema()可以返回当前页面使用的协议,http 或是 https;
request.getServerName()可以返回当前页面所在的服务器的名字;
request.getServerPort()可以返回当前页面所在的服务器使用的端口,就是80;
request.getContextPath()可以返回当前页面所在的应用的名字;
4)删除cookies的方法
要删除Cookie需要创建一个同名的Cookie,将它的maxAge属性设置为0,
并在HttpServletResponse中添加一个新的cookie.
Cookie cookie = new Cookie("userName", "");
cookie.setMaxAge(0);
response.addCookie(cookie);
5)jsp servlet 直接跳转的几种方式
JSP跳转到Servlet
1、相对路径
如href=”servlet/TestServlet”
如果写成”/servlet/TestServlet”会报错,因为第一个’/’表示的是【服务器根目录:http://localhost:8080/】
2、绝对路径
通过内置成员变量path实现,如href=”<%=path%>/servlet/TestServlet”。
这里的path得到的是项目根目录,如【http://localhost:8080/Servlet002_GetFormDemo】
Servlet跳转JSP
1、请求重定向:
response.sendRedirect(request.getContextPath()+”/xxx.jsp”);
这里通过request.getContextPath()方法获得项目根目录
2、服务器内部转发:
request.getRequestDispatcher(“../xxx.jsp”).forward(req,resp);
二:明日计划
复习前面的东西,有些东西之前明明应该掌握的。
开始任务六
三:疑难问题
获取basepath的必要性
四:思考总结
页面跳转流程是有点绕的,感觉还可以再简化一下。
评论