SpringMVC第一天

springmvc概述和入門案例

image.png
springmv執行的原理
image.pnghtml

建立工程

image.png

可能在網上下載了一些亂七八糟的東西,解決建立項目過慢的問題

image.png~~~~前端

建立resources下的springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"java

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="cn.itcast"/>

<!-- 視圖解析器對象 -->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/pages/"/>
    <property name="suffix" value=".jsp"/>
</bean>

<!--配置自定義類型轉換器-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="cn.itcast.utils.StringToDateConverter"/>
        </set>
    </property>
</bean>


<!-- 開啓SpringMVC框架註解的支持 -->
<mvc:annotation-driven />~~~~

</beans>web

webapp下建立web.xml

image.png
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >spring

<web-app>
<display-name>Archetype Created Web Application</display-name>spring-mvc

<!--配置前端控制器-->
<servlet>session

<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>

</servlet>
<servlet-mapping>mvc

<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>

</servlet-mapping>app

<!--配置解決中文亂碼的過濾器-->
<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>
</web-app>

RequestMapping註解

package org.springframework.web.bind.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping {

String name() default "";

@AliasFor("path")
String[] value() default {};

@AliasFor("value")//別名
String[] path() default {};

RequestMethod[] method() default {};

String[] params() default {};

String[] headers() default {};

String[] consumes() default {};

String[] produces() default {};

}
path和value是同樣的
@RequestMapping(path="/user")
@RequestMapping(value="/user")
@RequestMapping("/user")
RequestMethod
image.png
public enum RequestMethod {

GET,
HEAD,
POST,
PUT,
PATCH,
DELETE,
OPTIONS,
TRACE;

private RequestMethod() {
}

}
由於是枚舉的類型,能夠取的值
method={RequestMethod.POST,RequestMethod.GET}
params講解
image.png
能夠傳
params={"username","password"}
params={"username=aa","password=bb"}
headers講解
image.png

參數綁定和自定義類型轉換

1 入門

<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2018/4/29
Time: 22:10
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>

<title>Title</title>

</head>
<body>

<%--請求參數綁定--%>
<%--
<a href="param/testParam?username=hehe&password=123">請求參數綁定</a>

把數據封裝Account類中
<form action="param/saveAccount" method="post">
    姓名:<input type="text" name="username" /><br/>
    密碼:<input type="text" name="password" /><br/>
    金額:<input type="text" name="money" /><br/>
    用戶姓名:<input type="text" name="user.uname" /><br/>
    用戶年齡:<input type="text" name="user.age" /><br/>
    <input type="submit" value="提交" />
</form>
--%>

<%--把數據封裝Account類中,類中存在list和map的集合
<form action="param/saveAccount" method="post">
    姓名:<input type="text" name="username" /><br/>
    密碼:<input type="text" name="password" /><br/>
    金額:<input type="text" name="money" /><br/>

    用戶姓名:<input type="text" name="list[0].uname" /><br/>
    用戶年齡:<input type="text" name="list[0].age" /><br/>

    用戶姓名:<input type="text" name="map['one'].uname" /><br/>
    用戶年齡:<input type="text" name="map['one'].age" /><br/>
    <input type="submit" value="提交" />
</form>
--%>

<%--自定義類型轉換器
<form action="param/saveUser" method="post">
    用戶姓名:<input type="text" name="uname" /><br/>
    用戶年齡:<input type="text" name="age" /><br/>
    用戶生日:<input type="text" name="date" /><br/>
    <input type="submit" value="提交" />
</form>
--%>


<a href="param/testServlet">Servlet原生的API</a>

</body>
</html>

image.png
image.png

2 請求參數綁定實體類

3 解決中文亂碼

<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
<display-name>Archetype Created Web Application</display-name>

<!--配置前端控制器-->
<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:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>

</servlet>
<servlet-mapping>

<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>

</servlet-mapping>

<!--配置解決中文亂碼的過濾器-->
<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>

</web-app>

4 請求參數綁定集合類型

<%--請求參數綁定--%>
<%--
<a href="param/testParam?username=hehe&password=123">請求參數綁定</a>

把數據封裝Account類中
<form action="param/saveAccount" method="post">
    姓名:<input type="text" name="username" /><br/>
    密碼:<input type="text" name="password" /><br/>
    金額:<input type="text" name="money" /><br/>
    用戶姓名:<input type="text" name="user.uname" /><br/>
    用戶年齡:<input type="text" name="user.age" /><br/>
    <input type="submit" value="提交" />
</form>
--%>

<%--把數據封裝Account類中,類中存在list和map的集合
<form action="param/saveAccount" method="post">
    姓名:<input type="text" name="username" /><br/>
    密碼:<input type="text" name="password" /><br/>
    金額:<input type="text" name="money" /><br/>

    用戶姓名:<input type="text" name="list[0].uname" /><br/>
    用戶年齡:<input type="text" name="list[0].age" /><br/>

    用戶姓名:<input type="text" name="map['one'].uname" /><br/>
    用戶年齡:<input type="text" name="map['one'].age" /><br/>
    <input type="submit" value="提交" />
</form>
--%>

表單提交後
image.png
package cn.itcast.controller;

import cn.itcast.domain.Account;
import cn.itcast.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**

  • 請求參數綁定

*/
@Controller
@RequestMapping("/param")
public class ParamController {

/**
 * 請求參數綁定入門
 * @return
 */
@RequestMapping("/testParam")
public String testParam(String username,String password){
    System.out.println("執行了...");
    System.out.println("用戶名:"+username);
    System.out.println("密碼:"+password);
    return "success";
}

/**
 * 請求參數綁定把數據封裝到JavaBean的類中
 * @return
 */
@RequestMapping("/saveAccount")
public String saveAccount(Account account){
    System.out.println("執行了...");
    System.out.println(account);
    return "success";
}


/**
 * 自定義類型轉換器
 * @param user
 * @return
 */
@RequestMapping("/saveUser")
public String saveUser(User user){
    System.out.println("執行了...");
    System.out.println(user);
    return "success";
}

/**
 * 原生的API
 * @return
 */
@RequestMapping("/testServlet")
public String testServlet(HttpServletRequest request, HttpServletResponse response){
    System.out.println("執行了...");
    System.out.println(request);

    HttpSession session = request.getSession();
    System.out.println(session);

    ServletContext servletContext = session.getServletContext();
    System.out.println(servletContext);

    System.out.println(response);
    return "success";
}

}
package cn.itcast.domain;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

public class Account implements Serializable{

private String username;
private String password;
private Double money;

// private User user;

private List<User> list;
private Map<String,User> map;

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public Double getMoney() {
    return money;
}

public void setMoney(Double money) {
    this.money = money;
}

public List<User> getList() {
    return list;
}

public void setList(List<User> list) {
    this.list = list;
}

public Map<String, User> getMap() {
    return map;
}

public void setMap(Map<String, User> map) {
    this.map = map;
}

/*

public User getUser() {
    return user;
}

public void setUser(User user) {
    this.user = user;
}

*/

@Override
public String toString() {
    return "Account{" +
            "username='" + username + '\'' +
            ", password='" + password + '\'' +
            ", money=" + money +
            ", list=" + list +
            ", map=" + map +
            '}';
}

}
package cn.itcast.domain;

import java.io.Serializable;
import java.util.Date;

public class User implements Serializable{

private String uname;
private Integer age;

private Date date;

public String getUname() {
    return uname;
}

public void setUname(String uname) {
    this.uname = uname;
}

public Integer getAge() {
    return age;
}

public void setAge(Integer age) {
    this.age = age;
}

public Date getDate() {
    return date;
}

public void setDate(Date date) {
    this.date = date;
}

@Override
public String toString() {
    return "User{" +
            "uname='" + uname + '\'' +
            ", age=" + age +
            ", date=" + date +
            '}';
}

}

5 自定義類型轉換器演示異常

image.png
image.png

6 自定義轉換器代碼的編寫

例如2019-11-11這樣日期格式就不行,必須是2020/12/07這樣的格式,因此須要自定義轉換
必須實現Converter<S,T>這個接口,而裏邊是個泛型ctrl+h尋找到類或者接口的繼承的關係
ctrl鍵一直按找類或者接口的源碼
image.png
image.pngimage.png

springmvc.xml的配置文件

<!--配置自定義類型轉換器-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="cn.itcast.utils.StringToDateConverter"/>
        </set>
    </property>
</bean>


<!-- 開啓SpringMVC框架註解的支持 -->
<mvc:annotation-driven conversion-service="conversionService"/>

編寫自定義轉換的類

package cn.itcast.utils;

import org.springframework.core.convert.converter.Converter;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**

  • 把字符串轉換日期

*/
public class StringToDateConverter implements Converter<String,Date>{

/**
 * String source    傳入進來字符串
 * @param source
 * @return
 */
public Date convert(String source) {
    // 判斷
    if(source == null){
        throw new RuntimeException("請您傳入數據");
    }
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

    try {
        // 把字符串轉換日期
        //返回值java.util.Date的類型
        return df.parse(source);
    } catch (Exception e) {
        throw new RuntimeException("數據類型轉換出現錯誤");
    }
}

}
表單提交
image.png
提交後控制檯打印的數據
Student{username='李四', age=12, birthday=Sun Mar 22 00:00:00 CST 2020}

7 獲取Servlet原生的API~~~~

@RequestMapping("/testServlet")
public String testServlet(HttpServletRequest request, HttpServletResponse response){
    System.out.println("執行了...");
    System.out.println(request);

    HttpSession session = request.getSession();
    System.out.println(session);

    ServletContext servletContext = session.getServletContext();
    System.out.println(servletContext);

    System.out.println(response);
    return "success";
}

image.png

Spring MVC的經常使用註解

1 RequestParam註解

image.png
image.png
image.png
當傳uname的時候也不行
image.png
image.png

2 RequestBody註解

3 PathVariable註解

4 HiddentHttpMethodFilter過濾器

5 RequestHeader註解

6 CookieValue註解

7 ModelAttribute註解

8 SessionAttributes註解

image.png
這樣的話session域裏邊也有msg
request域和session域
image.png
image.png
image.png

/**
 * SessionAttributes的註解
 * @return
 */
@RequestMapping(value="/testSessionAttributes")
public String testSessionAttributes(Model model){
    System.out.println("testSessionAttributes...");
    // 底層會存儲到request域對象中
    model.addAttribute("msg","美美");
    return "success";
}

/**
 * 獲取值獲取的時候必須填寫Model的實現類ModelMap
 * @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";
}
相關文章
相關標籤/搜索