内置对象
在Spring MVC里面所有的操作都是以方法的形式出现的,但是如果说在开发里面需要使用到内置对象,只有ServletContext,HttpServeletRequest,HttpServletResponse,HttpSession四个内置对象.
这四个内置对象实际上只有两个:HttpServletRequeset,HttpServletResponse.
范例:使用内置对象
@RequestMapping("inner")
public ModelAndView inner(HttpServletRequest request,HttpServletResponse response){
return null;
}
取得了request对象就相当于取得了application和session对象
@RequestMapping("inner")
public ModelAndView inner(HttpServletRequest request,HttpServletResponse response) throws IOException{
ServletContext application =request.getServletContext();
HttpSession session=request.getSession();
System.out.println("绝对路径:"+application.getRealPath("/"));
System.out.println("session id:"+session.getId());
response.getWriter().print("<h1>www.baidu.com</h1>");
return null;
}
但是现在可以根据用户自己的选择来实现内置对象的定义,这种形式的代码是最方便的
而在日后的开发之中如果使用到Ajax的话,则就不需要返回ModelAndView,那么就表示不进行跳转
定义安全访问目录
在整个WEB项目里面WEB-INF目录是最安全的,但是如果按照最原始的开发就会出现一个问题,每一个保存在WEB-INF目录下的JSP都需要编写映射路径,这样的难度实在是太高了,所以在Spring里面考虑到了这类问题,提供了一个专门的类:org.springframework.web.servlet.view.InternalResourceViewResolver,它需要在applicationContext文件里面进行配置.
现在将保存在根目录下的index.jsp直接保存在WEB-INF目录下
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
在以后程序使用ModelAndView设置跳转路径的时候不需要设置这些前缀和后缀了
范例:在Action里面利用资源配置
@RequestMapping("message_insertPre")
public ModelAndView insertPre(){
ModelAndView mav=new ModelAndView("/messge_index");
return mav;
}
此时的完成的页面路径:/WEB-INF/index.jsp;
资源文件问题
在项目里面资源文件的重要性,几乎所有的信息的取得以及跳转路径的取得都会利用资源文件实现配置.在Spring里面也同样可以实现国际化的资源读取.
范例:建立两个文件--Message_zh_CN.properties
info.msg=欢迎访问:www.baidu.com!!!{0}
Pages_zh_CN.properties
message.insert.action=/message_insert
如果要想实现资源文件的读取操作,则必须使用一个专门的资源文件读取类
org.springframework.context.support.ResourceBundleMessageSource
范例:在applicationContext.xml文件里面配置资源读取
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<array>
<value>Message</value>
<value>Pages</value>
</array>
</property>
</bean>
资源文件的访问核心永远是ResourceBundle类,所以访问的时候一定不要加上后缀,并且不需要加上指定的Local数据,随后可以在需要它的Action上使用依赖注入的方式进行对象的设置.
范例:在Action里面注入Resource对象
@Resource
private MessageSource messageSource;
@RequestMapping("message_insertPre")
public ModelAndView insertPre(){
System.out.println("属性内容:"+this.messageSource.getMessage("info.msg",new Object[]{"啦啦啦"},null));
System.out.println("属性内容:"+this.messageSource.getMessage("message.insert.action",null,null));
ModelAndView mav=new ModelAndView("index");
return mav;
}
像资源的读取对象操作,以及出现过的转换器,在实际的使用过程之中都应该在Action的统一父类中执行操作