spring系列SpringMVC-創(chuàng)新互聯(lián)

概念

SpringMVC是一種基于Java實(shí)現(xiàn)MVC模型的輕量級(jí)Web框架。

創(chuàng)新互聯(lián)建站從2013年創(chuàng)立,先為大柴旦等服務(wù)建站,大柴旦等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為大柴旦企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。創(chuàng)建web工程(Maven結(jié)構(gòu)) 設(shè)置tomcat服務(wù)器插件

tomcat7進(jìn)行g(shù)et請(qǐng)求時(shí)會(huì)有中文亂碼問題(8.5版本后沒有這個(gè)問題)這里要配置字符集:

?

?org.apache.tomcat.maven

? tomcat7-maven-plugin

?2.1

?

80

/

UTF-8

?

?

導(dǎo)包

provided是為了避免沖突

spring-webmvc坐標(biāo)自動(dòng)依賴spring相關(guān)坐標(biāo)

javax.servlet

javax.servlet-api

3.1.0

provided

org.springframework

spring-webmvc

5.2.10.RELEASE

當(dāng)發(fā)送json數(shù)據(jù)時(shí)要導(dǎo)這個(gè)包:

com.fasterxml.jackson.core

jackson-databind

2.9.0

代碼

@Configuration初始化SpringMVC環(huán)境(同Spring環(huán)境)

@ComponentScan加載SpringMVC對(duì)應(yīng)的bean

在spring3.0后web-inf下的web.xml就可以被配置類替代了。

//spring不是一定要定義,寫出來只是為了便于理解后面的bean多次加載問題

//@Configuration

//@ComponentScan

//public class SpringConfig {

//}

@Configuration

@ComponentScan("com.xxz.controller")

public class SpringMvcConfig {

}

創(chuàng)建SpringMVC控制器類(等同于Servlet功能)

SpringMVC中,/save這樣的映射是放在一起統(tǒng)一管理的,并不是放在每一個(gè)bean里自己管理。

@ResponseBody在這里必須加,得告訴前端我給你的是body里的數(shù)據(jù),而不是要跳轉(zhuǎn)到哪個(gè)資源路徑,如果返回的是字符串,那直接給前端,如果是對(duì)象或集合,那就轉(zhuǎn)成json這種前端能識(shí)別的數(shù)據(jù)格式。功能由我們前面導(dǎo)入的json相關(guān)包的HttpMessageConvert接口定義。

@Controller

@RequestMapping("/user")

public class UserController { ? ?

@RequestMapping("/save") ? ?

@ResponseBody ? ?

public String save(@ ){ ? ? ? ?

?????System.out.println("user save ..."); ? ? ? ?

?????return "{'info':'springmvc'}"; ? ?

}

}

createServletApplicationContext()是指定SpringMVC的容器,new AnnotationConfigWebApplicationContext();是創(chuàng)建SpringMVC的容器,

getServletMappings是指定進(jìn)入web的容器中的請(qǐng)求中,哪些請(qǐng)求走SpringMVC,而/就表示全部

createRootApplicationContext()創(chuàng)建非SpringMVC的的容器對(duì)象,這里就是spring容器。

public class ServletContainersInitConfig extends AbstractDispatcherServletInitializer { ? ? ????????protected WebApplicationContext createServletApplicationContext() { ? ? ? ? ????????????????AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); ? ? ? ?

?????ctx.register(SpringMvcConfig.class); ? ? ? ?

?????return ctx; ? ?

} ? ?

protected String[] getServletMappings() { ? ? ? ?

?????return new String[]{"/"}; ? ?

} ? ?

protected WebApplicationContext createRootApplicationContext() { ? ? ? ?

//AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); ? ? ? ?

? //ctx.register(SpringConfig.class); ? ? ? ?

? //return ctx; ? ?

}

}

簡(jiǎn)化寫法:

public class ServletContainersInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer{ ? ?

protected Class[] getServletConfigClasses() { ? ? ? ?

?????return new Class[]{SpringMvcConfig.class}; ? ?

} ? ?

protected String[] getServletMappings() { ? ? ? ?

?????return new String[]{"/"}; ? ?

} ? ?

protected Class[] getRootConfigClasses() { ? ? ? ?

?????return new Class[]{SpringConfig.class}; ? ?

}

// 配字符編碼過濾器,解決post請(qǐng)求中文參數(shù)亂碼問題。? ??

protected Filter[] getServletFilters() { ? ? ? ?

?????CharacterEncodingFilter filter = new CharacterEncodingFilter(); ? ? ? ? ????????????????filter.setEncoding("utf-8"); ? ? ? ?

?????return new Filter[]{filter};? ? //多個(gè)過濾器用,分隔就行

}

}

運(yùn)行

找到Idea上面的Application處,搜mavan,在下方填command line寫tomcat,選run選項(xiàng)的。

拓展 bean重復(fù)加載問題

spring和SpringMVC都指定了componentscan,都指定了掃描包,都會(huì)把bean加載出來,當(dāng)一個(gè)bean在兩個(gè)范圍中時(shí),都會(huì)加載一遍。

所以要想辦法避免,最簡(jiǎn)單的非代碼方式是將兩config類挪位置,比如本來在com.xxx,那么可以挪到com或com的上一級(jí)。

代碼手段:

在spring容器中,采取過濾器的方式,采用注解過濾的方式,過濾掉帶@Controller的文件

@Configuration

@ComponentScan(value = "com.itheima", ? ?

excludeFilters = @ComponentScan.Filter( ? ? ? ?

?????type = FilterType.ANNOTATION, ? ? ? ?

?????classes = Controller.class ? ?

)

)

public class SpringConfig {

}

請(qǐng)求參數(shù)接收問題 地址欄后面拼接的參數(shù):

普通參數(shù):接口參數(shù)名與請(qǐng)求的參數(shù)一致的自動(dòng)映射接收

POJO類型參數(shù):bean屬性名與請(qǐng)求的參數(shù)一致的自動(dòng)映射接收

嵌套POJO類型參數(shù):請(qǐng)求參數(shù)采取bean對(duì)象成員屬性.對(duì)象成員屬性的方式請(qǐng)求

? 如果在嵌套關(guān)系中,被引用的對(duì)象成員名為A,那就是A.A的對(duì)象成員屬性

數(shù)組類型參數(shù):請(qǐng)求的參數(shù)名多寫幾個(gè)就行

接口的接收方法(String[] names)

集合類型參數(shù):框架看到List以為是個(gè)引用類型,要幫我們創(chuàng)建對(duì)象,但List是接口,沒有構(gòu)造,所以會(huì)報(bào)init錯(cuò)誤,前面加上@RequestParam讓框架直接裝數(shù)據(jù)就行了,不在這里進(jìn)行對(duì)象創(chuàng)建。

接口的接收方法(@RequestParam Listnames)

日期數(shù)據(jù):?date=2088/08/08&date1=2088-08-18&date2=2088/08/28 8:08:08??

yyyy/MM/dd格式是默認(rèn)可以接收的,所以直接:接口的接收方法(Date date)

另外的不是,要加:@DateTimeFormat,由spring-core的Convert接口定義的方法:

接口的接收方法(@DateTimeFormat(pattern = "yyyy-MM-dd") Date date1)

接口的接收方法(@DateTimeFormat(pattern = "yyyy/MM/dd HH:mm:ss") Date date2)

body中的json請(qǐng)求數(shù)據(jù):

postman中的位置:body/raw/json

@EnableWebMvc作用是將請(qǐng)求的json轉(zhuǎn)成對(duì)象(自動(dòng)類型轉(zhuǎn)換)

@Configuration

@ComponentScan("com.itheima.controller")

@EnableWebMvc

public class SpringMvcConfig {

}

接收請(qǐng)求中的json數(shù)據(jù):@RequestBody

接口的接收方法(@RequestBody Listnames)

接口的接收方法(@RequestBody Pojo pojp)

接口的接收方法(@RequestBody Listlist)

@RequestBody與@RequestParam區(qū)別 :

@RequestParam用于接收url地址傳參,表單傳參【application/x-www-form-urlencoded】 @RequestBody用于接收json數(shù)據(jù)【application/json】

非json格式數(shù)據(jù),選用@RequestParam接收請(qǐng)求參數(shù)。

后面開發(fā)以json格式數(shù)據(jù)為主,@RequestBody應(yīng)用范圍更廣。

響應(yīng) 響應(yīng)文本數(shù)據(jù)

@ResponseBody不加的話,返回的字符串會(huì)被當(dāng)做跳轉(zhuǎn)地址

@RequestMapping("/toText")

@ResponseBody

public String toText(){

? System.out.println("返回純文本數(shù)據(jù)");

? return "response text";

}

響應(yīng)POJO對(duì)象

@RequestMapping("/toJsonPOJO")

@ResponseBody

public User toJsonPOJO(){

? System.out.println("返回json對(duì)象數(shù)據(jù)");

? User user = new User();

? user.setName("xxz");

? user.setAge(15);

? return user;

}

響應(yīng)POJO集合對(duì)象

@RequestMapping("/toJsonList")

@ResponseBody

public ListtoJsonList(){

? System.out.println("返回json集合數(shù)據(jù)");

? User user1 = new User();

? user1.setName("名字");

? user1.setAge(15);

? User user2 = new User();

? user2.setName("名字");

? user2.setAge(12);

? ListuserList = new ArrayList();

? userList.add(user1);

? userList.add(user2);

? return userList;

}

REST風(fēng)格

原來訪問路徑形式:

? http://localhost/user/getById?id=1

? http://localhost/user/saveUser

REST風(fēng)格訪問路徑形式:

? http://localhost/user/1

? http://localhost/user

隱藏了接口的部分信息(請(qǐng)求方式和參數(shù)名),更加簡(jiǎn)潔。

多種請(qǐng)求方式如GET、PUT、POST等,對(duì)同一個(gè)路徑的請(qǐng)求還可以用來訪問不同的接口。

案例

在Controller中定義方法時(shí)設(shè)定http請(qǐng)求方式"和請(qǐng)求請(qǐng)求參數(shù)(路徑變量

@Controller

public class UserController {

? //當(dāng)前請(qǐng)求方法為POST,表示REST風(fēng)格中的添加操作

? @RequestMapping(value = "/users",method = RequestMethod.POST)

? @ResponseBody

? public String save(){

? System.out.println("user save...");

? return "{'module':'user save'}";

? }

? //當(dāng)前請(qǐng)求方法為DELETE,表示REST風(fēng)格中的刪除操作

? //@PathVariable注解用于綁定路徑參數(shù)與處理器方法形參間的關(guān)系,并且占位符名稱與方法形參名稱相同

? @RequestMapping(value = "/users/{id}",method = RequestMethod.DELETE)

? @ResponseBody

? public String delete(@PathVariable Integer id){

? System.out.println("user delete..." + id);

? return "{'module':'user delete'}";

? }

? //當(dāng)前請(qǐng)求方法為PUT,表示REST風(fēng)格中的修改操作

? @RequestMapping(value = "/users",method = RequestMethod.PUT)

? @ResponseBody

? public String update(@RequestBody User user){

? System.out.println("user update..."+user);

? return "{'module':'user update'}";

? }

? //當(dāng)前請(qǐng)求方法為GET,表示REST風(fēng)格中的查詢操作

? //@PathVariable注解用于設(shè)置路徑變量(路徑參數(shù)),要求路徑上設(shè)置對(duì)應(yīng)的占位符,并且占位符名稱與方法形參名稱相同

? @RequestMapping(value = "/users/{id}" ,method = RequestMethod.GET)

? @ResponseBody

? public String getById(@PathVariable Integer id){

? System.out.println("user getById..."+id);

? return "{'module':'user getById'}";

? }

? //當(dāng)前請(qǐng)求方法為GET,表示REST風(fēng)格中的查詢操作

? @RequestMapping(value = "/users",method = RequestMethod.GET)

? @ResponseBody

? public String getAll(){

? System.out.println("user getAll...");

? return "{'module':'user getAll'}";

? }

}

簡(jiǎn)化寫法:

@RestController ? ? //使用@RestController注解替換@Controller與@ResponseBody注解,簡(jiǎn)化書寫

@RequestMapping("/books")

public class BookController {

// ? ?@RequestMapping( method = RequestMethod.POST)

? @PostMapping//使用@PostMapping簡(jiǎn)化Post請(qǐng)求方法對(duì)應(yīng)的映射配置

? public String save(@RequestBody Book book){

? System.out.println("book save..." + book);

? return "{'module':'book save'}";

? }

// ? ?@RequestMapping(value = "/{id}" ,method = RequestMethod.DELETE)

? @DeleteMapping("/{id}") ?//使用@DeleteMapping簡(jiǎn)化DELETE請(qǐng)求方法對(duì)應(yīng)的映射配置

? public String delete(@PathVariable Integer id){

? System.out.println("book delete..." + id);

? return "{'module':'book delete'}";

? }

// ? ?@RequestMapping(method = RequestMethod.PUT)

? @PutMapping ? //使用@PutMapping簡(jiǎn)化Put請(qǐng)求方法對(duì)應(yīng)的映射配置

? public String update(@RequestBody Book book){

? System.out.println("book update..."+book);

? return "{'module':'book update'}";

? }

// ? ?@RequestMapping(value = "/{id}" ,method = RequestMethod.GET)

? @GetMapping("/{id}") ? ?//使用@GetMapping簡(jiǎn)化GET請(qǐng)求方法對(duì)應(yīng)的映射配置

? public String getById(@PathVariable Integer id){

? System.out.println("book getById..."+id);

? return "{'module':'book getById'}";

? }

// ? ?@RequestMapping(method = RequestMethod.GET)

? @GetMapping ? ? ?//使用@GetMapping簡(jiǎn)化GET請(qǐng)求方法對(duì)應(yīng)的映射配置

? public String getAll(){

? System.out.println("book getAll...");

? return "{'module':'book getAll'}";

? }

}

靜態(tài)資源放行:

@Configuration

public class SpringMvcSupport extends WebMvcConfigurationSupport {

? //設(shè)置靜態(tài)資源訪問過濾,當(dāng)前類需要設(shè)置為配置類,并被掃描加載

? @Override

? protected void addResourceHandlers(ResourceHandlerRegistry registry) {

? //當(dāng)有請(qǐng)求訪問/pages/**時(shí)候,從/pages目錄下查找內(nèi)容

? registry.addResourceHandler("/pages/**")

? .addResourceLocations("/pages/");

? registry.addResourceHandler("/js/**")

? .addResourceLocations("/js/"); ? ? ? ? ? ? ?

? registry.addResourceHandler("/css/**")

? .addResourceLocations("/css/"); ? ? ?

? registry.addResourceHandler("/plugins/**")

? .addResourceLocations("/plugins/");

? }

}

在主配置上添加掃描:

@Configuration

@ComponentScan({"com.itheima.controller","自定義的SpringMvcSupport 所在的包路徑"})

@EnableWebMvc

public class SpringMvcConfig {

}

你是否還在尋找穩(wěn)定的海外服務(wù)器提供商?創(chuàng)新互聯(lián)www.cdcxhl.cn海外機(jī)房具備T級(jí)流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確流量調(diào)度確保服務(wù)器高可用性,企業(yè)級(jí)服務(wù)器適合批量采購(gòu),新人活動(dòng)首月15元起,快前往官網(wǎng)查看詳情吧

分享題目:spring系列SpringMVC-創(chuàng)新互聯(lián)
本文路徑:http://muchs.cn/article36/hiosg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供標(biāo)簽優(yōu)化、App設(shè)計(jì)、關(guān)鍵詞優(yōu)化、動(dòng)態(tài)網(wǎng)站、網(wǎng)站改版微信公眾號(hào)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都定制網(wǎng)站建設(shè)