一、springmvc基础入门,创建一个helloworld程序
1.首先,导入springmvc需要的jar包。
2.添加web.xml配置文件中关于springmvc的配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<!--configure the setting of springmvcdispatcherservlet and configure the mapping--> <servlet> <servlet-name>springmvc</servlet-name> <servlet- class >org.springframework.web.servlet.dispatcherservlet</servlet- class > <init-param> <param-name>contextconfiglocation</param-name> <param-value>classpath:springmvc-servlet.xml</param-value> </init-param> <!-- <load-on-startup> 1 </load-on-startup> --> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> |
3.在src下添加springmvc-servlet.xml配置文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
<?xml version= "1.0" encoding= "utf-8" ?> <beans xmlns= "http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/xmlschema-instance" xmlns:context= "http://www.springframework.org/schema/context" xmlns:mvc= "http://www.springframework.org/schema/mvc" xsi:schemalocation="http: //www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http: //www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http: //www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <!-- scan the package and the sub package --> <context:component-scan base- package = "test.springmvc" /> <!-- don't handle the static resource --> <mvc: default -servlet-handler /> <!-- if you use annotation you must configure following setting --> <mvc:annotation-driven /> <!-- configure the internalresourceviewresolver --> <bean class = "org.springframework.web.servlet.view.internalresourceviewresolver" id= "internalresourceviewresolver" > <!-- 前缀 --> <property name= "prefix" value= "/web-inf/jsp/" /> <!-- 后缀 --> <property name= "suffix" value= ".jsp" /> </bean> </beans> |
4.在web-inf文件夹下创建名为jsp的文件夹,用来存放jsp视图。创建一个hello.jsp,在body中添加“hello world”。
5.建立包及controller,如下所示
6.编写controller代码
1
2
3
4
5
6
7
8
9
|
@controller @requestmapping ( "/mvc" ) public class mvccontroller { @requestmapping ( "/hello" ) public string hello(){ return "hello" ; } } |
7.启动服务器,键入 http://localhost:8080/项目名/mvc/hello
二、配置解析
1.dispatcherservlet
dispatcherservlet是前置控制器,配置在web.xml文件中的。拦截匹配的请求,servlet拦截匹配规则要自已定义,把拦截下来的请求,依据相应的规则分发到目标controller来处理,是配置spring mvc的第一步。
2.internalresourceviewresolver
视图名称解析器
3.以上出现的注解
@controller 负责注册一个bean 到spring 上下文中
@requestmapping 注解为控制器指定可以处理哪些 url 请求
三、springmvc常用注解
@controller
负责注册一个bean 到spring 上下文中
@requestmapping
注解为控制器指定可以处理哪些 url 请求
@requestbody
该注解用于读取request请求的body部分数据,使用系统默认配置的httpmessageconverter进行解析,然后把相应的数据绑定到要返回的对象上 ,再把httpmessageconverter返回的对象数据绑定到 controller中方法的参数上
@responsebody
该注解用于将controller的方法返回的对象,通过适当的httpmessageconverter转换为指定格式后,写入到response对象的body数据区
@modelattribute
在方法定义上使用 @modelattribute 注解:spring mvc 在调用目标处理方法前,会先逐个调用在方法级上标注了@modelattribute 的方法
在方法的入参前使用 @modelattribute 注解:可以从隐含对象中获取隐含的模型数据中获取对象,再将请求参数 –绑定到对象中,再传入入参将方法入参对象添加到模型中
@requestparam
在处理方法入参处使用 @requestparam 可以把请求参 数传递给请求方法
@pathvariable
绑定 url 占位符到入参
@exceptionhandler
注解到方法上,出现异常时会执行该方法
@controlleradvice
使一个contoller成为全局的异常处理类,类中用@exceptionhandler方法注解的方法可以处理所有controller发生的异常
四、自动匹配参数
1
2
3
4
5
6
|
//match automatically @requestmapping ( "/person" ) public string toperson(string name, double age){ system.out.println(name+ " " +age); return "hello" ; } |
五、自动装箱
1.编写一个person实体类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
package test.springmvc.model; public class person { public string getname() { return name; } public void setname(string name) { this .name = name; } public int getage() { return age; } public void setage( int age) { this .age = age; } private string name; private int age; } |
2.在controller里编写方法
1
2
3
4
5
6
|
//boxing automatically @requestmapping ( "/person1" ) public string toperson(person p){ system.out.println(p.getname()+ " " +p.getage()); return "hello" ; } |
六、使用initbinder来处理date类型的参数
1
2
3
4
5
6
7
8
9
10
11
12
13
|
//the parameter was converted in initbinder @requestmapping ( "/date" ) public string date(date date){ system.out.println(date); return "hello" ; } //at the time of initialization,convert the type "string" to type "date" @initbinder public void initbinder(servletrequestdatabinder binder){ binder.registercustomeditor(date. class , new customdateeditor( new simpledateformat( "yyyy-mm-dd" ), true )); } |
七、向前台传递参数
1
2
3
4
5
6
7
8
9
|
//pass the parameters to front-end @requestmapping ( "/show" ) public string showperson(map<string,object> map){ person p = new person(); map.put( "p" , p); p.setage( 20 ); p.setname( "jayjay" ); return "show" ; } |
前台可在request域中取到"p"
八、使用ajax调用
1
2
3
4
5
6
7
8
9
|
//pass the parameters to front-end using ajax @requestmapping ( "/getperson" ) public void getperson(string name,printwriter pw){ pw.write( "hello," +name); } @requestmapping ( "/name" ) public string sayhello(){ return "name" ; } |
前台用下面的jquery代码调用
1
2
3
4
5
6
7
|
$(function(){ $( "#btn" ).click(function(){ $.post( "mvc/getperson" ,{name:$( "#name" ).val()},function(data){ alert(data); }); }); }); |
九、在controller中使用redirect方式处理请求
1
2
3
4
5
|
//redirect @requestmapping ( "/redirect" ) public string redirect(){ return "redirect:hello" ; } |
十、文件上传
1.需要导入两个jar包
2.在springmvc配置文件中加入
1
2
3
4
|
<!-- upload settings --> <bean id= "multipartresolver" class = "org.springframework.web.multipart.commons.commonsmultipartresolver" > <property name= "maxuploadsize" value= "102400000" ></property> </bean> |
3.方法代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
@requestmapping (value= "/upload" ,method=requestmethod.post) public string upload(httpservletrequest req) throws exception{ multiparthttpservletrequest mreq = (multiparthttpservletrequest)req; multipartfile file = mreq.getfile( "file" ); string filename = file.getoriginalfilename(); simpledateformat sdf = new simpledateformat( "yyyymmddhhmmss" ); fileoutputstream fos = new fileoutputstream(req.getsession().getservletcontext().getrealpath( "/" )+ "upload/" +sdf.format( new date())+filename.substring(filename.lastindexof( '.' ))); fos.write(file.getbytes()); fos.flush(); fos.close(); return "hello" ; } |
4.前台form表单
1
2
3
4
|
<form action= "mvc/upload" method= "post" enctype= "multipart/form-data" > <input type= "file" name= "file" ><br> <input type= "submit" value= "submit" > </form> |
十一、使用@requestparam注解指定参数的name
1
2
3
4
5
6
7
8
9
10
|
@controller @requestmapping ( "/test" ) public class mvccontroller1 { @requestmapping (value= "/param" ) public string testrequestparam( @requestparam (value= "id" ) integer id, @requestparam (value= "name" )string name){ system.out.println(id+ " " +name); return "/hello" ; } } |
十二、restful风格的sringmvc
1.restcontroller
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
@controller @requestmapping ( "/rest" ) public class restcontroller { @requestmapping (value= "/user/{id}" ,method=requestmethod.get) public string get( @pathvariable ( "id" ) integer id){ system.out.println( "get" +id); return "/hello" ; } @requestmapping (value= "/user/{id}" ,method=requestmethod.post) public string post( @pathvariable ( "id" ) integer id){ system.out.println( "post" +id); return "/hello" ; } @requestmapping (value= "/user/{id}" ,method=requestmethod.put) public string put( @pathvariable ( "id" ) integer id){ system.out.println( "put" +id); return "/hello" ; } @requestmapping (value= "/user/{id}" ,method=requestmethod.delete) public string delete( @pathvariable ( "id" ) integer id){ system.out.println( "delete" +id); return "/hello" ; } } |
2.form表单发送put和delete请求
在web.xml中配置
1
2
3
4
5
6
7
8
9
|
<!-- configure the hiddenhttpmethodfilter,convert the post method to put or delete --> <filter> <filter-name>hiddenhttpmethodfilter</filter-name> <filter- class >org.springframework.web.filter.hiddenhttpmethodfilter</filter- class > </filter> <filter-mapping> <filter-name>hiddenhttpmethodfilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> |
在前台可以用以下代码产生请求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<form action= "rest/user/1" method= "post" > <input type= "hidden" name= "_method" value= "put" > <input type= "submit" value= "put" > </form> <form action= "rest/user/1" method= "post" > <input type= "submit" value= "post" > </form> <form action= "rest/user/1" method= "get" > <input type= "submit" value= "get" > </form> <form action= "rest/user/1" method= "post" > <input type= "hidden" name= "_method" value= "delete" > <input type= "submit" value= "delete" > </form> |
十三、返回json格式的字符串
1.导入以下jar包
2.方法代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
@controller @requestmapping ( "/json" ) public class jsoncontroller { @responsebody @requestmapping ( "/user" ) public user get(){ user u = new user(); u.setid( 1 ); u.setname( "jayjay" ); u.setbirth( new date()); return u; } } |
十四、异常的处理
1.处理局部异常(controller内)
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@exceptionhandler public modelandview exceptionhandler(exception ex){ modelandview mv = new modelandview( "error" ); mv.addobject( "exception" , ex); system.out.println( "in testexceptionhandler" ); return mv; } @requestmapping ( "/error" ) public string error(){ int i = 5 / 0 ; return "hello" ; } |
2.处理全局异常(所有controller)
1
2
3
4
5
6
7
8
9
10
|
@controlleradvice public class testcontrolleradvice { @exceptionhandler public modelandview exceptionhandler(exception ex){ modelandview mv = new modelandview( "error" ); mv.addobject( "exception" , ex); system.out.println( "in testcontrolleradvice" ); return mv; } } |
3.另一种处理全局异常的方法
在springmvc配置文件中配置
1
2
3
4
5
6
7
8
|
<!-- configure simplemappingexceptionresolver --> <bean class = "org.springframework.web.servlet.handler.simplemappingexceptionresolver" > <property name= "exceptionmappings" > <props> <prop key= "java.lang.arithmeticexception" >error</prop> </props> </property> </bean> |
error是出错页面
十五、设置一个自定义拦截器
1.创建一个myinterceptor类,并实现handlerinterceptor接口
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public class myinterceptor implements handlerinterceptor { @override public void aftercompletion(httpservletrequest arg0, httpservletresponse arg1, object arg2, exception arg3) throws exception { system.out.println( "aftercompletion" ); } @override public void posthandle(httpservletrequest arg0, httpservletresponse arg1, object arg2, modelandview arg3) throws exception { system.out.println( "posthandle" ); } @override public boolean prehandle(httpservletrequest arg0, httpservletresponse arg1, object arg2) throws exception { system.out.println( "prehandle" ); return true ; } } |
2.在springmvc的配置文件中配置
1
2
3
4
5
6
7
|
<!-- interceptor setting --> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path= "/mvc/**" /> <bean class = "test.springmvc.interceptor.myinterceptor" ></bean>gt; </mvc:interceptor> </mvc:interceptors> |
3.拦截器执行顺序
十六、表单的验证(使用hibernate-validate)及国际化
1.导入hibernate-validate需要的jar包
(未选中不用导入)
2.编写实体类user并加上验证注解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
public class user { public int getid() { return id; } public void setid( int id) { this .id = id; } public string getname() { return name; } public void setname(string name) { this .name = name; } public date getbirth() { return birth; } public void setbirth(date birth) { this .birth = birth; } @override public string tostring() { return "user [id=" + id + ", name=" + name + ", birth=" + birth + "]" ; } private int id; @notempty private string name; @past @datetimeformat (pattern= "yyyy-mm-dd" ) private date birth; } |
ps:@past表示时间必须是一个过去值
3.在jsp中使用springmvc的form表单
1
2
3
4
5
6
|
<form:form action= "form/add" method= "post" modelattribute= "user" > id:<form:input path= "id" /><form:errors path= "id" /><br> name:<form:input path= "name" /><form:errors path= "name" /><br> birth:<form:input path= "birth" /><form:errors path= "birth" /> <input type= "submit" value= "submit" > </form:form> |
ps:path对应name
4.controller中代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
@controller @requestmapping ( "/form" ) public class formcontroller { @requestmapping (value= "/add" ,method=requestmethod.post) public string add( @valid user u,bindingresult br){ if (br.geterrorcount()> 0 ){ return "adduser" ; } return "showuser" ; } @requestmapping (value= "/add" ,method=requestmethod.get) public string add(map<string,object> map){ map.put( "user" , new user()); return "adduser" ; } } |
ps:
1.因为jsp中使用了modelattribute属性,所以必须在request域中有一个"user".
2.@valid 表示按照在实体上标记的注解验证参数
3.返回到原页面错误信息回回显,表单也会回显
5.错误信息自定义
在src目录下添加locale.properties
1
2
3
4
5
|
notempty.user.name=name can't not be empty past.user.birth=birth should be a past value datetimeformat.user.birth=the format of input is wrong typemismatch.user.birth=the format of input is wrong typemismatch.user.id=the format of input is wrong |
在springmvc配置文件中配置
1
2
3
4
|
<!-- configure the locale resource --> <bean id= "messagesource" class = "org.springframework.context.support.resourcebundlemessagesource" > <property name= "basename" value= "locale" ></property> </bean> |
6.国际化显示
在src下添加locale_zh_cn.properties
1
2
|
username=账号 password=密码 |
locale.properties中添加
1
2
|
username=user name password=password |
创建一个locale.jsp
1
2
3
4
|
<body> <fmt:message key= "username" ></fmt:message> <fmt:message key= "password" ></fmt:message> </body> |
在springmvc中配置
1
2
|
<!-- make the jsp page can be visited --> <mvc:view-controller path= "/locale" view-name= "locale" /> |
让locale.jsp在web-inf下也能直接访问
最后,访问locale.jsp,切换浏览器语言,能看到账号和密码的语言也切换了
十七、压轴大戏--整合springioc和springmvc
1.创建一个test.springmvc.integrate的包用来演示整合,并创建各类
2.user实体类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
public class user { public int getid() { return id; } public void setid( int id) { this .id = id; } public string getname() { return name; } public void setname(string name) { this .name = name; } public date getbirth() { return birth; } public void setbirth(date birth) { this .birth = birth; } @override public string tostring() { return "user [id=" + id + ", name=" + name + ", birth=" + birth + "]" ; } private int id; @notempty private string name; @past @datetimeformat (pattern= "yyyy-mm-dd" ) private date birth; } |
3.userservice类
1
2
3
4
5
6
7
8
9
10
|
@component public class userservice { public userservice(){ system.out.println( "userservice constructor...\n\n\n\n\n\n" ); } public void save(){ system.out.println( "save" ); } } |
4.usercontroller
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@controller @requestmapping ( "/integrate" ) public class usercontroller { @autowired private userservice userservice; @requestmapping ( "/user" ) public string saveuser( @requestbody @modelattribute user u){ system.out.println(u); userservice.save(); return "hello" ; } } |
5.spring配置文件
在src目录下创建springioc的配置文件applicationcontext.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
<?xml version= "1.0" encoding= "utf-8" ?> <beans xmlns= "http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http: //www.springframework.org/schema/beans http: //www.springframework.org/schema/beans/spring-beans.xsd http: //www.springframework.org/schema/util http: //www.springframework.org/schema/util/spring-util-4.0.xsd http: //www.springframework.org/schema/context http: //www.springframework.org/schema/context/spring-context.xsd " xmlns:util= "http://www.springframework.org/schema/util" xmlns:p= "http://www.springframework.org/schema/p" xmlns:context= "http://www.springframework.org/schema/context" > <context:component-scan base- package = "test.springmvc.integrate" > <context:exclude-filter type= "annotation" expression= "org.springframework.stereotype.controller" /> <context:exclude-filter type= "annotation" expression= "org.springframework.web.bind.annotation.controlleradvice" /> </context:component-scan> </beans> |
在web.xml中添加配置
1
2
3
4
5
6
7
8
|
<!-- configure the springioc --> <listener> <listener- class >org.springframework.web.context.contextloaderlistener</listener- class > </listener> <context-param> <param-name>contextconfiglocation</param-name> <param-value>classpath:applicationcontext.xml</param-value> </context-param> |
6.在springmvc中进行一些配置,防止springmvc和springioc对同一个对象的管理重合
1
2
3
4
5
6
7
|
<!-- scan the package and the sub package --> <context:component-scan base- package = "test.springmvc.integrate" > <context:include-filter type= "annotation" expression= "org.springframework.stereotype.controller" /> <context:include-filter type= "annotation" expression= "org.springframework.web.bind.annotation.controlleradvice" /> </context:component-scan> |
十八、springmvc详细运行流程图
十九、springmvc与struts2的区别
1、springmvc基于方法开发的,struts2基于类开发的。springmvc将url和controller里的方法映射。映射成功后springmvc生成一个handler对象,对象中只包括了一个method。方法执行结束,形参数据销毁。springmvc的controller开发类似web service开发。
2、springmvc可以进行单例开发,并且建议使用单例开发,struts2通过类的成员变量接收参数,无法使用单例,只能使用多例。
3、经过实际测试,struts2速度慢,在于使用struts标签,如果使用struts建议使用jstl。