最美情侣中文字幕电影,在线麻豆精品传媒,在线网站高清黄,久久黄色视频

歡迎光臨散文網(wǎng) 會員登陸 & 注冊

SpringMVC

2020-08-10 16:36 作者:某個峙祁  | 我要投稿

環(huán)境配置

pom.xml配置

<properties>
? ?<maven.compiler.source>1.8</maven.compiler.source>
? ?<maven.compiler.target>1.8</maven.compiler.target>
? ?<spring.version>5.2.3.RELEASE</spring.version>
?</properties>

?<dependencies>
? ?<dependency>
? ? ?<groupId>org.springframework</groupId>
? ? ?<artifactId>spring-context</artifactId>
? ? ?<version>${spring.version}</version>
? ?</dependency>

? ?<dependency>
? ? ?<groupId>org.springframework</groupId>
? ? ?<artifactId>spring-web</artifactId>
? ? ?<version>${spring.version}</version>
? ?</dependency>

? ?<dependency>
? ? ?<groupId>org.springframework</groupId>
? ? ?<artifactId>spring-webmvc</artifactId>
? ? ?<version>${spring.version}</version>
? ?</dependency>

? ?<dependency>
? ? ?<groupId>javax.servlet</groupId>
? ? ?<artifactId>servlet-api</artifactId>
? ? ?<version>2.5</version>
? ? ?<scope>provided</scope>
? ?</dependency>

? ?<dependency>
? ? ?<groupId>javax.servlet.jsp</groupId>
? ? ?<artifactId>jsp-api</artifactId>
? ? ?<version>2.0</version>
? ? ?<scope>provided</scope>
? ?</dependency>
? ?<dependency>
? ? ?<groupId>junit</groupId>
? ? ?<artifactId>junit</artifactId>
? ? ?<version>4.11</version>
? ? ?<scope>test</scope>
? ?</dependency>
?</dependencies>



web.xml 配置

<web-app>
?<servlet>
? ? ?<servlet-name>dispatcherServlet</servlet-name>
? ? ?<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
? ? ?<init-param>
? ? ? ?<param-name>contextConfigLocation</param-name>
? ? ? ?<param-value>classpath:spring.xml</param-value>
? ? ?</init-param>
? ?</servlet>
? ?<servlet-mapping>
? ? ?<servlet-name>dispatcherServlet</servlet-name>
? ? ? ?
<!-- ? 在sprMVC中, / ? /* ? ? ? 這是攔截所有url
/:只匹配所有請求,不會去匹配jsp頁面
/*:匹配所有請求,包括jsp
-->
? ? ?<url-pattern>/</url-pattern>
? ?</servlet-mapping>

</web-app>


配置處理器適配器

?<!--配置控制器適配器
? 所有的處理適配器都實現(xiàn)HandlerAdapter接口
? -->
? ?<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>


編寫Handler

需要實現(xiàn)Controller接口 才能由SimpleControllerHandlerAdapter這個適配器執(zhí)行

public class StudentController implements Controller {
? ?@Override
? ?public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {

? ? ? ?ModelAndView mv=new ModelAndView();
? ? ? ?Student student=new Student();
? ? ? ?student.setName("哇哈哈");
? ? ? ?mv.addObject("student",student);
? ? ? ?mv.setViewName("index");
? ? ? ?return mv;

? ?}
}


配置處理器映射器

<!--配置控制映射器-->
? ?<!--配置handler-->
? ?<bean name="/123.action" id="hemoeController1" class="controller.StudentController"></bean>
<!--處理器映射器講bean的name作為url進行查找
? ?需要配置handler時指定bean的name,即指定訪問的url-->
? ?<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>


視圖解析器

<!--配置視圖解析器
? ?解析jsp。默認使用jstl,需要jstl包-->
? ?<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
? ? ? ?<property name="prefix" value="/WEB-INF/view/"></property>
? ? ? ?<property name="suffix" value=".jsp"></property>
? ?</bean>


使用注解

注解的處理器映射器和適配器

在 SpringMVC 的各個組件中,處理器映射器、處理器適配器、視圖解析器稱為 SpringMVC 的三大組件。 使 用 mvc:annotation-driven 自動加RequestMappingHandlerMapping (處理映射器) 和RequestMappingHandlerAdapter ( 處 理 適 配 器 ) , 可 用 在 SpringMVC.xml 配 置 文 件 中 使 用mvc:annotation-driven替代注解處理器和適配器的配置。

它就相當于在 xml 中配置了:

<!-- Begin -->
<!-- HandlerMapping -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>
<bean
class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>
<!-- HandlerAdapter -->
<bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean>
<bean
class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter"></bean>
<bean
class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>
<!-- HadnlerExceptionResolvers -->
<bean
class="org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver"></bean>
<bean
class="org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver"></bean>
<bean
class="org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver"
></bean>
<!-- End -->

配置案例:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
? ? ? xmlns:mvc="http://www.springframework.org/schema/mvc"
? ? ? xmlns:context="http://www.springframework.org/schema/context"
? ? ? 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/mvc
? ? ? ?http://www.springframework.org/schema/mvc/spring-mvc.xsd
? ? ? ?http://www.springframework.org/schema/context
? ? ? ?http://www.springframework.org/schema/context/spring-context.xsd">

? ?<context:component-scan base-package="controller"></context:component-scan>
? ?
? ?<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
? ? ? ?<property name="prefix" value="/WEB-INF/view/"></property>
? ? ? ?<property name="suffix" value=".jsp"></property>
? ?</bean>

? ?<mvc:annotation-driven></mvc:annotation-driven>

</beans>


@Controller
public class StudentController {

? ?@RequestMapping("/abc.action")
? ?public String getHome(){
? ? ? ?return "index";
? ?}
}


RequestMapping ? 建立請求 URL 和處理請求方法之間的對應(yīng)關(guān)系

作用: 用于建立請求 URL 和處理請求方法之間的對應(yīng)關(guān)系。

@RequestMapping(value = "/abc.action",method = RequestMethod.GET)
public String getHome(){
? ? ? ?return "index";
?}


RequestParam注解 ?為參數(shù)取別名

為參數(shù)取別名,前端傳遞的時候就以 username為準

@GetMapping("/u1")
? ?public String test1(@RequestParam("username") String name, Model model){
? ? ? ?//加上@RequestParam則前端傳入的參數(shù)為注解value
? ? ? ?//接收前端參數(shù)
? ? ? ?System.out.println("接收到的前端參數(shù)為:"+name);
? ? ? ?//將返回的結(jié)果傳遞給前端,model
? ? ? ?model.addAttribute("msg",name);
? ? ? ?//視圖跳轉(zhuǎn)
? ? ? ?return "test1";
? ?}


RequestBody ?獲取請求體內(nèi)容

作用: 用于獲取請求體內(nèi)容。直接使用得到是 key=value&key=value...結(jié)構(gòu)的數(shù)據(jù)。 get 請求方式不適用。 屬性: required:是否必須有請求體。默認值是:true。當取值為 true 時,get 請求方式會報錯。如果取值 為 false,get 請求得到是 null。

使用示例:

<form action="anno/testRequestBody" method="post">
? ? ? ?用戶姓名:<input type="text" name="username" /><br/>
? ? ? ?用戶年齡:<input type="text" name="age" /><br/>
? ? ? ?<input type="submit" value="提交" />
? ?</form>


/**
? ? * 獲取到請求體的內(nèi)容
? ? * @return
? ? */
? ?@RequestMapping("/testRequestBody")
? ?public String testRequestBody(@RequestBody String body){
? ? ? ?System.out.println("執(zhí)行了...");
? ? ? ?System.out.println(body);
? ? ? ?return "success";
? ?}

執(zhí)行結(jié)果:

//輸出結(jié)果:
username=admin&age=11


PathVaribale ?用于綁定 url 中的占位符

作用: 用于綁定 url 中的占位符。例如:請求 url 中 /delete/{id},這個{id}就是 url 占位符。 url 支持占位符是 spring3.0 之后加入的。是 springmvc 支持 rest 風(fēng)格 URL 的一個重要標志。 屬性: value:用于指定 url 中占位符名稱。 required:是否必須提供占位符

使用示例

<a href="anno/testPathVariable/10">testPathVariable</a>
/**
? ? * PathVariable注解
? ? * @return
? ? */
? ?@RequestMapping(value="/testPathVariable/{sid}")
? ?public String testPathVariable(@PathVariable(name="sid") String id){
? ? ? ?System.out.println("執(zhí)行了...");
? ? ? ?System.out.println(id);
? ? ? ?return "success";
? ?}


RequestHeader ?獲取請求消息頭

作用: 用于獲取請求消息頭。 屬性: value:提供消息頭名稱 required:是否必須有此消息頭 注: 在實際開發(fā)中一般不怎么用。

<a href="anno/testRequestHeader">RequestHeader</a>
/**
? ? * 獲取請求頭的值
? ? * @param header
? ? * @return
? ? */
? ?@RequestMapping(value="/testRequestHeader")
? ?public String testRequestHeader(@RequestHeader(value="Accept") String header, HttpServletRequest request,HttpServletResponse response) throws IOException {
? ? ? ?System.out.println("執(zhí)行了...");
? ? ? ?System.out.println(header);
? ? ? ?// return "success";
? ? ? ?// response.sendRedirect(request.getContextPath()+"/anno/testCookieValue");
? ? ? ?return "redirect:/param.jsp";
? ?}


CookieValue ?把指定 cookie 名稱的值傳入控制器方法參數(shù)

作用: 用于把指定 cookie 名稱的值傳入控制器方法參數(shù)。 屬性: value:指定 cookie 的名稱。 required:是否必須有此 cookie。

使用示例

<a href="anno/testCookieValue">CookieValue</a>
/**
? ? * 獲取Cookie的值
? ? * @return
? ? */
? ?@RequestMapping(value="/testCookieValue")
? ?public String testCookieValue(@CookieValue(value="JSESSIONID") String cookieValue){
? ? ? ?System.out.println("執(zhí)行了...");
? ? ? ?System.out.println(cookieValue);
? ? ? ?return "success";
? ?}


ModelAttribute ?用于修飾方法和參數(shù)

作用: 該注解是 SpringMVC4.3 版本以后新加入的。它可以用于修飾方法和參數(shù)。 出現(xiàn)在方法上,表示當前方法會在控制器的方法執(zhí)行之前,先執(zhí)行。它可以修飾沒有返回值的方法,也可 以修飾有具體返回值的方法。 出現(xiàn)在參數(shù)上,獲取指定的數(shù)據(jù)給參數(shù)賦值。 屬性: value:用于獲取數(shù)據(jù)的 key。key 可以是 POJO 的屬性名稱,也可以是 map 結(jié)構(gòu)的 key。 應(yīng)用場景: 當表單提交數(shù)據(jù)不是完整的實體類數(shù)據(jù)時,保證沒有提交數(shù)據(jù)的字段使用數(shù)據(jù)庫對象原來的數(shù)據(jù)。 例如: 我們在編輯一個用戶時,用戶有一個創(chuàng)建信息字段,該字段的值是不允許被修改的。在提交表單數(shù) 據(jù)是肯定沒有此字段的內(nèi)容,一旦更新會把該字段內(nèi)容置為 null,此時就可以使用此注解解決問題。

使用示例

<form action="anno/testModelAttribute" method="post">
? ? ? ?用戶姓名:<input type="text" name="uname" /><br/>
? ? ? ?用戶年齡:<input type="text" name="age" /><br/>
? ? ? ?<input type="submit" value="提交" />
? ?</form>
/**
? ? * ModelAttribute注解
? ? * @return
? ? */
? ?@RequestMapping(value="/testModelAttribute")
? ?public String testModelAttribute(@ModelAttribute("abc") User user){
? ? ? ?System.out.println("testModelAttribute執(zhí)行了...");
? ? ? ?System.out.println(user);
? ? ? ?return "success";
? ?}

? ?@ModelAttribute
? ?public void showUser(String uname, Map<String,User> map){
? ? ? ?System.out.println("showUser執(zhí)行了...");
? ? ? ?// 通過用戶查詢數(shù)據(jù)庫(模擬)
? ? ? ?User user = new User();
? ? ? ?user.setUname(uname);
? ? ? ?user.setAge(20);
? ? ? ?user.setDate(new Date());
? ? ? ?map.put("abc",user);
? ?}

? ?/**
? ? * 該方法會先執(zhí)行

? ?@ModelAttribute
? ?public User showUser(String uname){
? ? ? ?System.out.println("showUser執(zhí)行了...");
? ? ? ?// 通過用戶查詢數(shù)據(jù)庫(模擬)
? ? ? ?User user = new User();
? ? ? ?user.setUname(uname);
? ? ? ?user.setAge(20);
? ? ? ?user.setDate(new Date());
? ? ? ?return user;
? ?}
? ? */


SessionAttribute ?多次執(zhí)行控制器方法間的參數(shù)共享

作用: 用于多次執(zhí)行控制器方法間的參數(shù)共享。 屬性: value:用于指定存入的屬性名稱 type:用于指定存入的數(shù)據(jù)類型。

?<a href="anno/testSessionAttributes">testSessionAttributes</a>
?<a href="anno/getSessionAttributes">getSessionAttributes</a>
?<a href="anno/delSessionAttributes">delSessionAttributes</a>
@Controller
@RequestMapping("/anno")
@SessionAttributes(value={"msg"}) ? // 把msg存入到session域?qū)χ?br/>public class AnnoController {
}
/**
? ? * SessionAttributes的注解
? ? * @return
? ? */
? ?@RequestMapping(value="/testSessionAttributes")
? ?public String testSessionAttributes(Model model){
? ? ? ?System.out.println("testSessionAttributes...");
? ? ? ?// 底層會存儲到request域?qū)ο笾?br/> ? ? ? ?model.addAttribute("msg","美美");
? ? ? ?return "success";
? ?}

? ?/**
? ? * 獲取值
? ? * @param modelMap
? ? * @return
? ? */
? ?@RequestMapping(value="/getSessionAttributes")
? ?public String getSessionAttributes(ModelMap modelMap){
? ? ? ?System.out.println("getSessionAttributes...");
? ? ? ?String msg = (String) modelMap.get("msg");
? ? ? ?System.out.println(msg);
? ? ? ?return "success";
? ?}

? ?/**
? ? * 清除
? ? * @param status
? ? * @return
? ? */
? ?@RequestMapping(value="/delSessionAttributes")
? ?public String delSessionAttributes(SessionStatus status){
? ? ? ?System.out.println("getSessionAttributes...");
? ? ? ?status.setComplete();
? ? ? ?return "success";
? ?}


RestController ?不走視圖解析器直接返回字符串

在類上使用



RestFul 風(fēng)格

這時瀏覽器輸入的url 就是 ?http://localhost:8080/t1/aaaa/bbbb

aaaa和bbbb 就是輸入的參數(shù)

@RequestMapping("/t1/{aa}/{bb}")
? ?public String t1(@PathVariable String aa,@PathVariable String bb, HttpServletRequest req){
? ? ? ?String s = aa + bb;
? ? ? ?req.setAttribute("hhh","合并字符串為"+s);

? ? ? ?return "wahh";
? ?}


轉(zhuǎn)發(fā)和重定向

轉(zhuǎn)發(fā)

@RequestMapping("/t4")
? ?public String t4(Map<String,String> mp){
? ? ? ?mp.put("whh","轉(zhuǎn)發(fā)的頁面");
? ? ? ?return "wahh";
? ?}


重定向

@RequestMapping("/t5/{name}")
? ?public String t5(@PathVariable String name,HttpServletRequest req, HttpServletResponse rsp){
? ? ? ?//重定向的頁面
? ? ? ?req.getSession().setAttribute("name", name);
? ? ? ?//重定向調(diào)用的是其他方法的 URL
? ? ? ?return "redirect:/t4";
? ?}



向后臺參數(shù)的傳遞

傳遞的參數(shù)一般要名字一致


通過map傳遞

@RequestMapping("/wahh") ?//url
? ?public String getHome(Map<String,String> mp){
? ? ? ?mp.put("whh","/wahh");

? ? ? ?return "wahh";
? ?}


通過對象傳遞

@GetMapping("/u2")public String test2(User user){
? ?System.out.println(user); ?
? ?return "test1";
}


通過request傳遞

@RequestMapping("/hhh")
? ?public String gethhh(HttpServletRequest req){
? ? ? ? req.setAttribute("hhh","阿彌陀佛");

? ? ? ?return "wahh";
? ?}


通過基本類型傳遞

有String ?boolean ? Integer int 等

@RequestMapping("/hhh")
? ?public String gethhh(String sss){
? ? ? ? System.out.println(sss); ?

? ? ? ?return "wahh";
? ?}


向前端的返回數(shù)據(jù)


第一種 ?ModelAndView


public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {

? ? ? ?ModelAndView mv=new ModelAndView();
? ? ? ?Student student=new Student();
? ? ? ?student.setName("哇哈哈");
? ? ? ?mv.addObject("student",student);
? ? ? ?mv.setViewName("wahh");
? ? ? ?return mv;

? ?}


第二種 ?Model

@GetMapping("/u1")
? ?public String test1( Model model){
? ? ? ?//將返回的結(jié)果傳遞給前端,model
? ? ? ?model.addAttribute("msg","name");
? ? ? ?//視圖跳轉(zhuǎn)
? ? ? ?return "test1";
? ?}


第三種 ?ModelMap

LinkedHashMap-->>ModelMap-->>model ? ? ?上下關(guān)系
ModelMap ?繼承了LinkedHashMap,擁有它的全部功能
Model ? ? 精簡版(大部分情況下,我們都直接使用Model) ? ?@GetMapping("/u3")
? ?public String test3(ModelMap map){

? ? ? ?map.addAttribute("name","nameeeee");

? ? ? ?return "test1";

? ?}


小結(jié)

Model ?只有寥寥幾個方法只適合儲存數(shù)據(jù),簡化了新手對于Model對象的操作和理解

ModelMap ?繼承了LinkedHashMap,除了實現(xiàn)了自身的一些方法同樣繼承了LinkedMap的方法和特性

ModelAndView ?可以在儲存數(shù)據(jù)的同事,可以進行設(shè)置發(fā)揮的了邏輯視圖,進行控制展示層的跳轉(zhuǎn)


亂碼處理

在web.xml中加入

?<!-- ?解決參數(shù)亂碼問題-->
?<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>


JSON

json鍵值對是用來保存 JavaScript 對象的一種方式,和 ?JavaScript 對象的寫法也大同小異,鍵/值對組合中的鍵名寫在前面并用雙引號 "" 包裹,使用冒號:分隔,然后緊接著值:

{"name":"adsfasdfasdfasd"}

{"age":"6"}

{"sex":"難"}

JSON 和 JavaScript 對象可以互轉(zhuǎn)

要實現(xiàn)從JSON字符串轉(zhuǎn)換為JavaScript 對象,使用 JSON.parse() 方法:

var obj = JSON.parse('{"a": "Hello", "b": "World"}');
//結(jié)果是 {a: 'Hello', b: 'World'}

要實現(xiàn)從JavaScript 對象轉(zhuǎn)換為JSON字符串,使用 JSON.stringify() 方法:

var json = JSON.stringify({a: 'Hello', b: 'World'});
//結(jié)果是 '{"a": "Hello", "b": "World"}'


json亂碼處理 ? 在spring配置文件下添加配置

<!-- ? ?json亂碼解決-->
? ?<mvc:annotation-driven>
? ? ? ?<mvc:message-converters>
? ? ? ? ? ?<bean class="org.springframework.http.converter.StringHttpMessageConverter">
? ? ? ? ? ? ? ?<constructor-arg value="UTF-8"/>
? ? ? ? ? ?</bean>
? ? ? ? ? ?<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
? ? ? ? ? ? ? ?<property name="objectMapper">
? ? ? ? ? ? ? ? ? ?<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
? ? ? ? ? ? ? ? ? ? ? ?<property name="failOnEmptyBeans" value="false"/>
? ? ? ? ? ? ? ? ? ? </bean>
? ? ? ? ? ? ? ?</property>
? ? ? ? ? ?</bean>
? ? ? ?</mvc:message-converters>
? ?</mvc:annotation-driven>


返回 json 對象

?<!--pom.xml導(dǎo)入依賴-->
?<dependency>
? ? ? ? ? ?<groupId>com.fasterxml.jackson.core</groupId>
? ? ? ? ? ?<artifactId>jackson-databind</artifactId>
? ? ? ? ? ?<version>2.11.0</version>
? ? ? ?</dependency>


? ?@RequestMapping("/js1")
? ?@ResponseBody ?//不走視圖解析器直接返回
? ?public String json1() throws JsonProcessingException {
? ? ? ?ObjectMapper mapper = new ObjectMapper();
? ? ? ?User user = new User();
? ? ? ?String s = mapper.writeValueAsString(user);
? ? ? ?return s;
? ?}


Fastjson

導(dǎo)入依賴

?<dependency>
? ? ? ? ? ?<groupId>com.alibaba</groupId>
? ? ? ? ? ?<artifactId>fastjson</artifactId>
? ? ? ? ? ?<version>1.2.73</version>
? ? ? ?</dependency>


jsonobject 代表 json 對象


jsonarray 代表 json 對象數(shù)組


json 代表 jsongobject 和 jsonarray 的轉(zhuǎn)化



SpringMVC的評論 (共 條)

分享到微博請遵守國家法律
东乡族自治县| 托里县| 梅河口市| 久治县| 赣榆县| 聂荣县| 巴里| 子长县| 汶川县| 五大连池市| 浦城县| 三亚市| 凌源市| 夏河县| 阿拉善盟| 义马市| 芜湖县| 霍州市| 客服| 罗甸县| 海门市| 肇州县| 彝良县| 西青区| 许昌市| 湾仔区| 中西区| 霍州市| 扎赉特旗| 微博| 准格尔旗| 赤壁市| 东宁县| 健康| 教育| 蒙自县| 开封县| 滦南县| 郴州市| 咸宁市| 义乌市|