1 所需jar包
项目结构如下:
2 web.xml配置文件的内容如下:
<?xmlversion="1.0"encoding="utf-8"?>
<web-appversion="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
xsi:schemalocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class>
</servlet>
<servlet-mapping>
<!-- struts用/*,springmvc不能用/*方式,配置的url-pattern如:*.xxx
-->
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
3 springmvc-servlet.xml的内容如下:
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemalocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">
<context:component-scanbase-package="com.rl.controller"/>
<bean
class="org.springframework.web.servlet.view.internalresourceviewresolver">
<propertyname="prefix"value="/web-inf/jsp/"/>
<propertyname="suffix"value=".jsp"/>
</bean>
<!--文件上传的视图解析器
id一定是multipartresolver,不能随便定义
<beanid="multipartresolver"
class="org.springframework.web.multipart.commons.commonsmultipartresolver">
<!--文件上传的最大值,以字节为单位
<propertyname="maxuploadsize"value="1024000"></property>
<mvc:interceptors>
<mvc:interceptor>
<!-- path:指定要拦截的范围。语法:/(根目录)test/**,所有拦截/**
<mvc:mappingpath="/**"/>
<beanclass="com.rl.interceptor.myinterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
</beans>
4 test1controller.java的内容如下:
package com.rl.controller;
import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.requestmapping;
@controller
@requestmapping("/test1") //当前controller的namespace,防止不同的controller中方名重复的问题
public class test1controller {
/**
*
浏览器中的访问地址是:http://localhost:8080/springmvc2/test1/toajax.do
* @return
*/
@requestmapping("/toajax.do")
public string toajax() {
return "ajax";
}
}
5 testcontroller的内容如下:
import java.io.ioexception;
import java.io.printwriter;
import java.sql.date;
import java.text.simpledateformat;
import java.util.hashmap;
import java.util.map;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import org.springframework.beans.propertyeditors.customdateeditor;
import org.springframework.ui.model;
import org.springframework.web.bind.servletrequestdatabinder;
import org.springframework.web.bind.annotation.initbinder;
import org.springframework.web.bind.annotation.requestmethod;
import org.springframework.web.servlet.modelandview;
import com.rl.model.person;
import com.rl.model.user;
@requestmapping("test")
//当前controller的namespace,防止不同controller中方法名重复的问题
public class testcontroller {
public testcontroller() {
system.out.println("controller被创建....");
* desc:返回值类型是string,含义是modelandview中的viewname
* @requestmapping:请求方法的映射,内容最好和方法名称一致
* @author
涂作权
@requestmapping("/hello.do")
public string hello() {
return "index";
* desc:httpservletrequest可以直接定义在方法的参数列表中来使用
* @param request
@requestmapping("/getparam.do")
public string getparam(httpservletrequest request) {
string name = request.getparameter("name");
system.out.println(name);
* desc:在参数的列表中来直接定义要接收的参数,参数名(形象)一定要
和请求中传递的参数名(实参)一致,数据类型会自动的转换,如果数据
类型转换出错会报400错误???
* @param name
* @param id
* @param age
* @param address
* @param birthday
@requestmapping("/getparam1.do")
public string getparam1(string name, integer id, integer age,
string address, date birthday) {
system.out.println("姓名:"
+ name + " id:" + id.getclass() + " 年龄:"
+ age + "
地址: " + address + "生日:" + birthday);
* desc:多选的接收在参数列表中定义数组来接收,参数名(形参)一定要和请求中传递的参数名(实参)一致,数据类型会自动的转换,
如果以字符串来接收的话会接收到一个以逗号分隔的一个字符串
* @param favor
@requestmapping("/getparam2.do")
public string getparam2(string[] favor) {
system.out.println(favor);
for (string fa : favor) {
system.out.println(fa);
}
* desc:接收实体对象,直接在参数列表中定义要接收的实体类就可以了,每次访问的时候springmvc会自动创建相关参数的实体对象,对象中
的属性值是通过请求传递过来并且注入到对象中
* @param person
* @param user
@requestmapping("/getparambyobj.do")
public string getparambyobj(person person, user user, string name) {
system.out.println(person);
system.out.println(user);
不建议使用 desc:返回值类型定义成modelandview,把数据和视图注入到modelandview中返回即可
* @throws exception
@requestmapping("/returndata.do")
public modelandview returndata() throws exception {
person p = new person();
p.setid(1);
p.setname("zhangsan");
p.setage(22);
p.setaddress("beijing");
p.setbirthday(new simpledateformat("yyyy-mm-dd").parse("2013-08-05"));
map<string, object> map = new hashmap<string, object>();
//
相当于request.setattribute("person", p);
map.put("person", p);
return new modelandview("index", map);
不建议使用 desc:返回值是string类型:viewname,参数是map,是modelandview中
map,不是接收参数的。
* @param map
@requestmapping("/returndata1.do")
public string returndata1(map<string, object> map) throws exception {
在参数列表中定义model来给页面返回数据 desc:建议使用
* @param model
@requestmapping("/returndata2.do")
public string returndata2(model model) throws exception {
model.addattribute("person", p);
* desc:method=requestmethod.post该方法只能使用method指定的请求方式来指定
@requestmapping(value = "/getparambyobjwithmethod.do", method = requestmethod.post)
public string getparambyobjwithmethod(person person) {
return "success";
* desc:在参数列表中直接来定义httpservletresponse,并且方法的返回值要定义void为ajax提供调用
* @param response
@requestmapping("/ajax.do")
public void ajax(string name, httpservletresponse response) {
string result = "hello" + name;
try {
response.getwriter().write(result);
} catch (ioexception e) {
e.printstacktrace();
* desc:直接在参数列表中来定义printwriter建议使用
* @param out
@requestmapping("/ajax1.do")
public void ajax1(string name, printwriter out){
string result = "hello " + name;
out.write(result);
public string toajax(){
在同一个controller中重定向语法 return后面
redirect:当前
*
controller中方法的@requestmapping的值
@requestmapping("/redirecttoajax.do")
public string redirecttoajax(){
return "redirect:toajax.do";
* controller之间的重定向redirect:后面要有"/",代表从项目的根目录开始
@requestmapping("/redirecttoajax1.do")
public string redirecttoajax1(){
return "redirect:/test1/toajax.do";
单纯的转发
@requestmapping("/toform.do")
public string toform(){
return "form";
用于转换数据类型
* @param binder
@initbinder
public void initbinder(servletrequestdatabinder binder){
binder.registercustomeditor(date.class,
new customdateeditor(new simpledateformat("yyyy-mm-dd"), true));
6 uploadcontroller的内容如下:
import java.io.file;
import java.io.fileoutputstream;
import java.io.outputstream;
import java.util.date;
import java.util.random;
import org.springframework.web.multipart.multipartfile;
import org.springframework.web.multipart.multiparthttpservletrequest;
@requestmapping("/upload")
//当前controller的namespace,防止不同controller中方法名重复的问题
public class uploadcontroller {
@requestmapping("/uploadpic.do")
public string uploadpic(person person, httpservletrequest request)
throws exception {
把request转换成multiparthttpservletrequest
multiparthttpservletrequest mr = (multiparthttpservletrequest) request;
获得文件,这里的pic是表单中的file字段对应的属性名称
multipartfile mf = mr.getfile("pic");
获得文件的字节数组
byte[] fbyte = mf.getbytes();
获得当前时间的最小精度
string filename = new simpledateformat("yyyymmddhhmmsssss")
.format(new date());
追加三位随机数
random random = new random();
for (int i = 0; i < 3; i++) {
filename = filename + random.nextint(10);
获得原始文件名
string orifilename = mf.getoriginalfilename();
获得后缀名
string suffix = orifilename.substring(orifilename.lastindexof("."));
拿到服务器的根目录
string realpath = request.getsession().getservletcontext()
.getrealpath("/");
创建文件输出流
outputstream out = new fileoutputstream(new file(realpath + "/upload/"
+ filename + suffix));
out.write(fbyte);
out.flush();
out.close();
public void initbinder(servletrequestdatabinder binder) {
binder.registercustomeditor(date.class, new customdateeditor(
new simpledateformat("yyyy-mm-dd"), true));
7 myinterceptor的内容如下:
package com.rl.interceptor;
import org.springframework.web.servlet.handlerinterceptor;
public class myinterceptor implements handlerinterceptor{
执行时机:在视图解析器解析完毕之后,页面一旦报错异常会抛到该方法中,
* try{}catch后面的finally,用于系统监控
public void aftercompletion(httpservletrequest arg0,
httpservletresponse arg1, object arg2, exception ex)
system.out.println("aftercompletion...................");
system.out.println("----------------------------------");
ex.printstacktrace();
执行时机:controller执行完毕,视图解析器解析之前来执行
注意:此案例中如果是测试异步,这里的mv是null,此处会报错。
解决办法是注释掉springmvc-servlet.xml中的拦截器的配置内容
public void posthandle(httpservletrequest arg0, httpservletresponse arg1,
object arg2, modelandview mv) throws exception {
map<string, object> map = mv.getmodel();
map.put("test", "append something...");
system.out.println("posthandle...");
返回值数据类型是布尔类型:true放行, false是阻止访问
执行时机:controller执行之前
最常用的应用场景就是权限的拦截
public boolean prehandle(httpservletrequest arg0, httpservletresponse arg1,
object obj) throws exception {
system.out.println("prehandle...");
system.out.println(obj.getclass().getname());
return true;
8 person的内容如下:
package com.rl.model;
publicclass
person {
integer
id;
string
name;
age;
address;
date
birthday;
/**
*
@return the id
*/
public
integer getid() {
returnid;
}
@param id the id to set
publicvoid
setid(integer id) {
this.id
= id;
@return the name
string getname() {
returnname;
@param name the name to set
setname(string name) {
this.name
= name;
@return the age
integer getage() {
returnage;
@param age the age to set
setage(integer age) {
this.age
= age;
@return the address
string getaddress() {
returnaddress;
@param address the address to set
setaddress(string address) {
this.address
= address;
@return the birthday
date getbirthday() {
returnbirthday;
@param birthday the birthday to set
setbirthday(date birthday) {
this.birthday
= birthday;
9 user的内容如下
user {
@override
string tostring() {
return"user
[id=" +id
+", name=" +name
+"]";
10 ajax.jsp的内容如下:
<%@page
language="java"import="java.util.*"pageencoding="utf-8"%>
<%
string path = request.getcontextpath();
string basepath = request.getscheme()+"://"+request.getservername()+":"+request.getserverport()+path+"/";
%>
<!doctypehtml
public "-//w3c//dtd html 4.01 transitional//en">
<html>
<head>
<basehref="<%=basepath%>">
<title>my
jsp 'index.jsp' starting page</title>
<metahttp-equiv="pragma"content="no-cache">
<metahttp-equiv="cache-control"content="no-cache">
<metahttp-equiv="expires"content="0">
<metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">
<metahttp-equiv="description"content="this
is my page">
<scripttype="text/javascript"src="js/jquery.js"></script>
<scripttype="text/javascript">
$(function(){
$("#mybutton").click(function(){
console.log("test");
varmytext
= $("#mytext").val();
$.ajax({
url:"test/ajax1.do",
type:"post",
datatype:"text",
data:{
name:mytext
},
success:function(responsetext){
alert(responsetext);
error:function(){
alert("system
error");
}
});
});
});
</script>
</head>
<body>
<inputtype="text"id="mytext"/>
<inputid="mybutton"type="button"value="click"/>
</body>
</html>
11 form.jsp的内容如下:
jsp 'form.jsp' starting page</title>
<formaction="upload/uploadpic.do"method="post"enctype="multipart/form-data">
id:<inputname="id"type="text"/><br>
name:<inputname="name"type="text"/><br>
age:<inputname="age"type="text"/><br>
address:<inputname="address"type="text"/><br>
birthday:<inputname="birthday"type="text"/><br>
pic:<inputtype="file"name="pic"/><br>
<inputvalue="submit"type="submit"/>
</form>
12 index.jsp的内容如下:
<%@taglib
uri="http://java.sun.com/jsp/jstl/fmt"prefix="fmt"%>
<h1>${person.id}</h1>
<h1>${person.name}</h1>
<h1>${person.age}</h1>
<h1>${person.address}</h1>
<h1><fmt:formatdatevalue="${person.birthday
}"pattern="yyyy-mm-dd"/></h1>
<h1>${test
}</h1>
13 success.jsp的内容如下:
jsp 'success.jsp' starting page</title>
success<br>