在web项目中,可以使用ServletContextListener监听web项目的启动,我们可以在web应用启动时,就加载spring配置文件,创建应用上下文对象ApplicationContext,再将其存储到最大的域ServletContext域中,这样就可以在任何位置从域中获得ApplicationContext对象。
配置全局初始化参数
<context-param>
<param-name>contextLoaderListener</param-name>
<param-value>applicationContext.xml</param-value>
</context-param>
String contextLoaderListener = servletContext.getInitParameter(“contextLoaderListener”);
ApplicationContext app = new ClassPathXmlApplicationContext(contextLoaderListener);
配置监听器
servletContext.setAttribute("app",app);
spring集成web环境:
配置ContextLoaderListener监听器
使用WebApplicationContextUtils获取应用上下文对象
springmvc快速入门:
需求:客户端发起请求,服务器端接受请求,执行逻辑并进行页面跳转
开发步骤:
1导入springmvc相关坐标
2配置springmvc核心控制器DispathcerServlet
@RequestMapping
用于建立请求URL和处理请求方法之间的对应关系
参数:
value:用于指定请求的url
method:请求方式
params:用于指定请求参数的限制条件
例如:params={“user”}:请求参数必须有user
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
springmvc的数据响应:
回写数据:
1,直接返回字符串:将需要回写的字符串直接返回,但此时需要通过@ResponseBody注解告知springmvc框架,方法返回直接在http响应体中返回
使用json转换工具将对象转换成字符串
ObjectMapper objectMapper = new ObjectMapper();
String s = objectMapper.writeValueAsString(user);
同时在pom.xml导入json的jar包
:
com.fasterxml.jackson.core
jackson-core
2.9.0
com.fasterxml.jackson.core
jackson-databind
2.9.0
com.fasterxml.jackson.core
jackson-annotations
2.9.0
2,返回对象或者集合:
在mvc.xml中配置处理器适配器,加载json
1 配置处理器适配器,配置json
2配置mvc的注解驱动,自动配置json
mvc:annotation-driven/
同时在mvc.xml中引入mvc的命名空间。
请求数据:
获得集合类型参数
当使用ajax提交时,可以指定contentType为json形式,那么在方法参数位置 使用@RequestBody可以直接接收集合数据无需使用POJO进行封装。
并且在mvc.xml中配置
<mvc:resources mapping="/js/**" location="/js/"></mvc:resources>
跟上面一样的作用,交由tomcat进行资源匹配
mvc:default-servlet-handler/
参数绑定注解@RequestParam
当请求的参数名称与Controller的业务方法参数不一致时,就需要@RequestParam注解显示的绑定
获取restful风格的参数
restful风格的请求是使用“url+请求方式”,表示一次请求目的地,http协议里面四个表示操作方式的动词如下:
GET:用于获取资源
POST:用于新建资源
PUT:用于更新资源
DELECT:用于删除资源
例如:
/user/1 GET:得到id等于1的user
客户端:http://localhost:8080/uu/ss15/houliie
@RequestMapping("/ss15/{username}")
@ResponseBody
public void save15(@PathVariable(“username”) String username) {
System.out.println(username);
}
自定义类型转换器:
1定义转换器实现Converter接口
2在配置文件中声明转换器
在中引用转换器
获得请求头:
@RequestHeader
相当于web阶段的request.getHeader(name)
@CookieValue(value = “JSESSIONID”) String jsessionId
过滤器与拦截器的区别:
适用范围:过滤器可以在任何javaweb项目中存在,拦截器只能在springmvc框架中使用。
拦截范围:过滤器配置/*时,可以对所有要访问的资源拦截,拦截器只会拦截访问的控制方法,如果是其他静态资源不会拦截。
RequestContextHolder的使用
RequestContextHolder顾名思义,持有上下文的Request容器.使用是很简单的,具体使用如下:
ServletRequestAttributes attributes =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
此代码用于获取request对象。
853

被折叠的 条评论
为什么被折叠?



