SpringMVC 学习笔记
2016-08-30 11:02
190 查看
1.jar
2.web.xml
里配置dispatcherServlet
例:
<!-- The frontcontroller of this Spring Web application, responsible for handling allapplication requests -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>-->
<load-on-startup>1</load-on-startup>
</servlet>
<!--Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
默认MVC.xml
为[springDispatcherServlet]-servlet.xml
,位于WEB-INF下
可以通过初始化contextConfigLocation重新配置他的名字及位置
3.MVC.xml里配置视图解析器
<beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix"value="/WEB-INF/pages/" />
<property name="suffix"value=".jsp" />
</bean>
<!--
扫描controller的包
-->
<context:component-scanbase-package="com.chenj.app"></context:component-scan>
4.测试
importorg.springframework.web.servlet.ModelAndView;
//importorg.springframework.web.portlet.ModelAndView;
注ModelAndView的包不要导错
@Controller
publicclass test {
@RequestMapping("/hello")
publicModelAndView helloword(HttpServletRequest req,HttpServletResponse resp){
System.out.println("1111111111111111");
ModelAndViewmv = new ModelAndView();
mv.addObject("name", "朱锃亮");
mv.setViewName("helloword");
returnmv;
}
}
5.数据处理
5.1 url
传得参数和处理方法的参数一致即可
5.2
如果不一致
在方法参数前用@RequestParam("URL参数名")
5.3
方法参数如果是对象的话,URL传参只要是对象的属性名称就行
5.4
显示到前台,两种方法(ModelAndView
、ModeMap)
注:ModeMap
是写在方法参数中的,两者不同的是ModelAndView需要视图解析器,ModeMap不需要
6.乱码
在web.xml里配置过滤器,只能过滤POST的请求,GET请求需要改变TOMCAT的配置或自己编写编码过滤器
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
----------------------------------------------------------------------------------------------------------------
自定义编码过滤器
publicclass CharactorFilter implements Filter {
Stringencoding = null;
publicvoid destroy() {
encoding= null;
}
publicvoid doFilter(ServletRequest request, ServletResponse response, FilterChainchain)
throwsIOException, ServletException {
if(encoding != null){
request.setCharacterEncoding(encoding); //设置request的编码格式
response.setContentType("text/html;charset="+encoding); //设置response字符编码
}
chain.doFilter(request, response); //传递给下一个过滤器
}
publicvoid init(FilterConfig filterConfig) throws ServletException {
encoding =filterConfig.getInitParameter("encoding"); //获取初始化参数
}
}
7.restful风格
方法参数前得加@PathVariable
例:
@RequestMapping("/hello/{name}")
public ModelAndView helloword(HttpServletRequestreq,HttpServletResponse resp,@PathVariable String name){
/…
}
8.文件上传
5.1 jar
commons-fileupload
commons-io
5.2
配置MVC.xml
例:
<beanid="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<propertyname="defaultEncoding" value="utf-8"></property>
<propertyname="maxUploadSize"value="10485760000"></property>
<propertyname="maxInMemorySize" value="40960"></property>
</bean>
5.3java代码
@RequestMapping("/upload")
publicString fileupload(@RequestParam("file") CommonsMultipartFilefile,HttpServletRequest req) throws IOException{
Stringpath = req.getRealPath("/fileupload");
InputStreamis =file.getInputStream();
OutputStreamos = new FileOutputStream(new File(path,file.getOriginalFilename()));
intlen = 0;
byte[]buffer = new byte[400];
while((len=is.read(buffer))!=-1){
os.write(buffer,0, len);
}
os.close();
is.close();
return"helloword";
}
6.springMVC
处理JSON数据
<!--
启动Springmvc注解驱动 -->
<m
f2af
vc:annotation-driven/>
<!--返回json
方法一需要导入 fastjson.jar包-->
<!--<mvc:annotation-driven>
<mvc:message-convertersregister-defaults="false">
避免IE执行AJAX时,返回JSON出现下载文件
<beanid="fastJsonHttpMessageConverter"class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<propertyname="supportedMediaTypes">
<list>
这里顺序不能反,一定先写text/html,不然ie下出现下载提示
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven> -->
<!--
返回json
方法二需要导入jackson-annotations.jar,jackson-core.jar,jackson-databind.jar-->
<beanclass="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
<beanclass="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<propertyname="messageConverters">
<list>
<beanclass="org.springframework.http.converter.StringHttpMessageConverter">
<propertyname="supportedMediaTypes">
<list>
<value>text/html; charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
<beanclass="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<propertyname="supportedMediaTypes">
<list>
<value>text/html; charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>
7.拦截器
7.1实现HandlerInterceptor
publicclass MyInterceptor implements HandlerInterceptor{
//在DispatcherServlet处理后执行
@Override
publicvoid afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Objectarg2, Exception arg3)
throwsException {
//TODO Auto-generated method stub
}
//在请求处理的方法执行后执行
@Override
publicvoid postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2,ModelAndView arg3)
throwsException {
System.out.println("-----处理之后------");
}
//在请求处理方法前执行
@Override
publicboolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Objectarg2) throws Exception {
System.out.println("-----处理之前------");
returntrue;
}
}
7.2配置拦截器
<mvc:interceptors>
<mvc:interceptor>
<mvc:mappingpath="/**"/>
<beanclass="com.chenj.app.interceptor.MyInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
7.3拦截需要登录页面案例
---------------------------------------------------------------拦截器代码
publicclass LoginInterceptor implements HandlerInterceptor{
//不需要拦截的页面
privateList<String> allowedPass;
publicList<String> getAllowedPass() {
returnallowedPass;
}
publicvoid setAllowedPass(List<String> allowedPass) {
this.allowedPass= allowedPass;
}
@Override
publicvoid afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Objectarg2, Exception arg3)
throwsException {
//TODO Auto-generated method stub
}
@Override
publicvoid postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2,ModelAndView arg3)
throwsException {
//TODO Auto-generated method stub
}
@Override
publicboolean preHandle(HttpServletRequest req, HttpServletResponse resp, Objectarg2) throws Exception {
Stringurl = req.getRequestURL().toString();
Objectuser = req.getSession().getAttribute("user");
//如果已登录放行
if(user!= null) return true;
//不需要拦截的页面放行
for(Stringtemp:allowedPass){
if(url.endsWith(temp)){
returntrue;
}
}
//拦截下的页面跳转登录页面
req.getRequestDispatcher("/WEB-INF/pages/login.jsp").forward(req,resp);
returnfalse;
}
}
---------------------------------------------------------------配置
<mvc:interceptors>
<mvc:interceptor>
<mvc:mappingpath="/**"/>
<beanclass="com.chenj.app.interceptor.LoginInterceptor">
<!--不需要被拦截的请求,采用属性注入-->
<propertyname="allowedPass">
<list>
<value>login.do</value>
</list>
</property>
</bean>
</mvc:interceptor>
</mvc:interceptors>
---------------------------------------------------------------控制器
@Controller
publicclass UserController {
@RequestMapping("/login")
publicString login(User user,HttpSession session){
if("chenj".equals(user.getName())&& "12345".equals(user.getPassword())){
session.setAttribute("user",user);
return"forward:/WEB-INF/pages/index.jsp";
}
return"forward:/WEB-INF/pages/login.jsp";
}
@RequestMapping("/add")
publicString add(){
System.out.println("add");
return"forward:/WEB-INF/pages/index.jsp";
}
}
---------------------------------------------------------------页面JSP
<formaction="login.do" method="POST">
用户名:<inputtype="text" name="name"><br>
密码:<inputtype="password" name="password"><br>
<inputtype="submit" value="submit">
</form>
2.web.xml
里配置dispatcherServlet
例:
<!-- The frontcontroller of this Spring Web application, responsible for handling allapplication requests -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>-->
<load-on-startup>1</load-on-startup>
</servlet>
<!--Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
默认MVC.xml
为[springDispatcherServlet]-servlet.xml
,位于WEB-INF下
可以通过初始化contextConfigLocation重新配置他的名字及位置
3.MVC.xml里配置视图解析器
<beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix"value="/WEB-INF/pages/" />
<property name="suffix"value=".jsp" />
</bean>
<!--
扫描controller的包
-->
<context:component-scanbase-package="com.chenj.app"></context:component-scan>
4.测试
importorg.springframework.web.servlet.ModelAndView;
//importorg.springframework.web.portlet.ModelAndView;
注ModelAndView的包不要导错
@Controller
publicclass test {
@RequestMapping("/hello")
publicModelAndView helloword(HttpServletRequest req,HttpServletResponse resp){
System.out.println("1111111111111111");
ModelAndViewmv = new ModelAndView();
mv.addObject("name", "朱锃亮");
mv.setViewName("helloword");
returnmv;
}
}
5.数据处理
5.1 url
传得参数和处理方法的参数一致即可
5.2
如果不一致
在方法参数前用@RequestParam("URL参数名")
5.3
方法参数如果是对象的话,URL传参只要是对象的属性名称就行
5.4
显示到前台,两种方法(ModelAndView
、ModeMap)
注:ModeMap
是写在方法参数中的,两者不同的是ModelAndView需要视图解析器,ModeMap不需要
6.乱码
在web.xml里配置过滤器,只能过滤POST的请求,GET请求需要改变TOMCAT的配置或自己编写编码过滤器
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
----------------------------------------------------------------------------------------------------------------
自定义编码过滤器
publicclass CharactorFilter implements Filter {
Stringencoding = null;
publicvoid destroy() {
encoding= null;
}
publicvoid doFilter(ServletRequest request, ServletResponse response, FilterChainchain)
throwsIOException, ServletException {
if(encoding != null){
request.setCharacterEncoding(encoding); //设置request的编码格式
response.setContentType("text/html;charset="+encoding); //设置response字符编码
}
chain.doFilter(request, response); //传递给下一个过滤器
}
publicvoid init(FilterConfig filterConfig) throws ServletException {
encoding =filterConfig.getInitParameter("encoding"); //获取初始化参数
}
}
7.restful风格
方法参数前得加@PathVariable
例:
@RequestMapping("/hello/{name}")
public ModelAndView helloword(HttpServletRequestreq,HttpServletResponse resp,@PathVariable String name){
/…
}
8.文件上传
5.1 jar
commons-fileupload
commons-io
5.2
配置MVC.xml
例:
<beanid="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<propertyname="defaultEncoding" value="utf-8"></property>
<propertyname="maxUploadSize"value="10485760000"></property>
<propertyname="maxInMemorySize" value="40960"></property>
</bean>
5.3java代码
@RequestMapping("/upload")
publicString fileupload(@RequestParam("file") CommonsMultipartFilefile,HttpServletRequest req) throws IOException{
Stringpath = req.getRealPath("/fileupload");
InputStreamis =file.getInputStream();
OutputStreamos = new FileOutputStream(new File(path,file.getOriginalFilename()));
intlen = 0;
byte[]buffer = new byte[400];
while((len=is.read(buffer))!=-1){
os.write(buffer,0, len);
}
os.close();
is.close();
return"helloword";
}
6.springMVC
处理JSON数据
<!--
启动Springmvc注解驱动 -->
<m
f2af
vc:annotation-driven/>
<!--返回json
方法一需要导入 fastjson.jar包-->
<!--<mvc:annotation-driven>
<mvc:message-convertersregister-defaults="false">
避免IE执行AJAX时,返回JSON出现下载文件
<beanid="fastJsonHttpMessageConverter"class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<propertyname="supportedMediaTypes">
<list>
这里顺序不能反,一定先写text/html,不然ie下出现下载提示
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven> -->
<!--
返回json
方法二需要导入jackson-annotations.jar,jackson-core.jar,jackson-databind.jar-->
<beanclass="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
<beanclass="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<propertyname="messageConverters">
<list>
<beanclass="org.springframework.http.converter.StringHttpMessageConverter">
<propertyname="supportedMediaTypes">
<list>
<value>text/html; charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
<beanclass="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<propertyname="supportedMediaTypes">
<list>
<value>text/html; charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>
7.拦截器
7.1实现HandlerInterceptor
publicclass MyInterceptor implements HandlerInterceptor{
//在DispatcherServlet处理后执行
@Override
publicvoid afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Objectarg2, Exception arg3)
throwsException {
//TODO Auto-generated method stub
}
//在请求处理的方法执行后执行
@Override
publicvoid postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2,ModelAndView arg3)
throwsException {
System.out.println("-----处理之后------");
}
//在请求处理方法前执行
@Override
publicboolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Objectarg2) throws Exception {
System.out.println("-----处理之前------");
returntrue;
}
}
7.2配置拦截器
<mvc:interceptors>
<mvc:interceptor>
<mvc:mappingpath="/**"/>
<beanclass="com.chenj.app.interceptor.MyInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
7.3拦截需要登录页面案例
---------------------------------------------------------------拦截器代码
publicclass LoginInterceptor implements HandlerInterceptor{
//不需要拦截的页面
privateList<String> allowedPass;
publicList<String> getAllowedPass() {
returnallowedPass;
}
publicvoid setAllowedPass(List<String> allowedPass) {
this.allowedPass= allowedPass;
}
@Override
publicvoid afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Objectarg2, Exception arg3)
throwsException {
//TODO Auto-generated method stub
}
@Override
publicvoid postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2,ModelAndView arg3)
throwsException {
//TODO Auto-generated method stub
}
@Override
publicboolean preHandle(HttpServletRequest req, HttpServletResponse resp, Objectarg2) throws Exception {
Stringurl = req.getRequestURL().toString();
Objectuser = req.getSession().getAttribute("user");
//如果已登录放行
if(user!= null) return true;
//不需要拦截的页面放行
for(Stringtemp:allowedPass){
if(url.endsWith(temp)){
returntrue;
}
}
//拦截下的页面跳转登录页面
req.getRequestDispatcher("/WEB-INF/pages/login.jsp").forward(req,resp);
returnfalse;
}
}
---------------------------------------------------------------配置
<mvc:interceptors>
<mvc:interceptor>
<mvc:mappingpath="/**"/>
<beanclass="com.chenj.app.interceptor.LoginInterceptor">
<!--不需要被拦截的请求,采用属性注入-->
<propertyname="allowedPass">
<list>
<value>login.do</value>
</list>
</property>
</bean>
</mvc:interceptor>
</mvc:interceptors>
---------------------------------------------------------------控制器
@Controller
publicclass UserController {
@RequestMapping("/login")
publicString login(User user,HttpSession session){
if("chenj".equals(user.getName())&& "12345".equals(user.getPassword())){
session.setAttribute("user",user);
return"forward:/WEB-INF/pages/index.jsp";
}
return"forward:/WEB-INF/pages/login.jsp";
}
@RequestMapping("/add")
publicString add(){
System.out.println("add");
return"forward:/WEB-INF/pages/index.jsp";
}
}
---------------------------------------------------------------页面JSP
<formaction="login.do" method="POST">
用户名:<inputtype="text" name="name"><br>
密码:<inputtype="password" name="password"><br>
<inputtype="submit" value="submit">
</form>
相关文章推荐
- 《Spring3.X企业应用开发实战》学习笔记--SpringMVC
- springMVC学习笔记之入门案例
- springMVC学习笔记四(数据类型转换和数据验证)
- ★SpringMVC学习笔记(1) 总记 学习资料
- springMVC学习笔记五(拦截器详解)
- springMVC学习笔记五(拦截器详解)
- SpringMVC学习笔记--解决乱码问题
- springMVC学习笔记四(数据类型转换和数据验证)
- SpringMVC学习笔记(5) 启用(优化)注解+静态资源访问
- springMVC学习笔记二(dispatcherServlet)
- springMVC学习笔记--初识springMVC
- SpringMVC学习笔记二
- SpringMVC学习笔记一
- springMVC学习笔记二(dispatcherServlet)
- springMVC学习笔记一(hello world)
- springMVC学习笔记之实战演练
- SpringMVC学习笔记三
- 学习笔记--SpringMVC 3.1下返回json时中文显示乱码问题的解决方案
- SpringMVC学习笔记(3) 框架配置+HelloWorld(非注解版)
- springMVC学习笔记六(注解方式实现控制器)