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>