SpringMVC post 요청 처리

11684 단어 Springpost
1.SpringMVC 는 POST 가 제출 한 데 이 터 를 분석 합 니 다.
C1,수요:form 폼 이 제출 한 대량의 데 이 터 를 분석 합 니 다.
在这里插入图片描述
在这里插入图片描述
C2,html 페이지 준비

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>  post    </title>
		<!--  HTML   css   -->
		<style>
			/*          */
			input[type='text']{
				width: 280px;
				height: 30px;
			}
			/*      */
			form{
				margin-left:50px ;
			}
		</style>
	</head>
	<body>
		<!-- method             ,action              ,
				name                name=jack
				value             
		 -->
		<form method="post" action="http://localhost:8080/stu/add">
			<table>
				<tr>
					<td>
						<h2>        MIS</h2>
					</td>
				</tr>
				<tr>
					<td>  :	</td>
				</tr>
				<tr>
					<td>
						<input type="text" placeholder="     ..." name="name"/>
					</td>
				</tr>
				<tr>
					<td>  :	</td>
				</tr>
				<tr>
					<td>
						<input type="text" placeholder="     ..." name="age"/>
					</td>
				</tr>
				<tr>
					<td>
						  :(   )
						<input type="radio" name="sex" value="1" checked="checked"/> 
						<input type="radio" name="sex" value="0"/> 
					</td>
				</tr>
				<tr>
					<td>
						  :(  )
						<input type="checkbox" name="hobby" value="ppq" checked="checked"/>   
						<input type="checkbox" name="hobby" value="ps"/>  
						<input type="checkbox" name="hobby" value="cg"/>  
					</td>
				</tr>
				<tr>
					<td>
						  :(   )
						<select name="edu">
							<option value="1">  </option>
							<option value="2">  </option>
							<option value="3">   </option>
						</select>
					</td>
				</tr>
				<tr>
					<td>
						    :
						<input type="date" name="intime"/>
					</td>
				</tr>
				<tr>
					<td>
						<input type="submit" value="  " style="color: white;background-color: #0000FF;border-color: #0000FF;"/>
						<input type="reset" value="  " style="color: white;background-color: palevioletred;border-color: palevioletred;"/>
					</td>
				</tr>
			</table>
		</form>
	</body>
</html>
C3,준비 학생 클래스

package cn.tedu.pojo;
import java.util.Arrays;
import java.util.Date;
//   MVC M ,      (             name       ,      )
public class Student {
    private String name;
    private Integer age;
    private Integer sex;
    private String[] hobby;//  
    private Integer edu;
     //  :HTML         String   ,    Date  ,HTML   400  ,           
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date intime;
    //get()  set()  toString()
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public Integer getSex() {
        return sex;
    }
    public void setSex(Integer sex) {
        this.sex = sex;
    }
    public String[] getHobby() {
        return hobby;
    }
    public void setHobby(String[] hobby) {
        this.hobby = hobby;
    }
    public Integer getEdu() {
        return edu;
    }
    public void setEdu(Integer edu) {
        this.edu = edu;
    }
    public Date getIntime() {
        return intime;
    }
    public void setIntime(Date intime) {
        this.intime = intime;
    }
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", sex=" + sex +
                ", hobby=" + Arrays.toString(hobby) +
                ", edu=" + edu +
                ", intime=" + intime +
                '}';
    }
}
C4,RunApp 클래스 준비

package cn.tedu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//      :               
@SpringBootApplication
public class RunApp {
    public static void main(String[] args) {
        SpringApplication.run(RunApp.class);
    }
}
C5,StuController 류 준비

package cn.tedu.controller;
import cn.tedu.pojo.Student;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
//  MVC C ,          
@RestController
@RequestMapping("stu")
public class StuController {
    //  post       
    @RequestMapping("add")
    public void add(Student s){
        System.out.println(s);
    }
}
C6,테스트
在这里插入图片描述
둘째,Ajax 가 post 요청 한 데 이 터 를 제출 하도록 개조 합 니 다.
C1,웹 페이지 저장 버튼 수정

<input type="button" value="  " onclick="fun();" style="color: white;background-color: #0000FF;border-color: #0000FF;"/>
C2,웹 페이지 의 form 태그 수정

<form method="post" action="#" id="f1">
C3,ajax 를 통 해 데이터 제출

<!--1.   jQuery   ajax,  jQuery       -->
<script src="jquery-1.8.3.min.js"></script>
<!--2.    ajax    -->
<script>
	function fun(){
		$.ajax({
			url: "http://localhost:8080/stu/add" , //         
			data: $("#f1").serialize()  , //         
			success: function(data){ //         
				alert(data);
			}
		});
	}
</script>
C4,Controller 코드 를 수정 하고 반환 값 과 도 메 인 문제 에 대한 주 해 를 추가 합 니 다.

package cn.tedu.controller;
import cn.tedu.pojo.Student;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Arrays;
//  MVC C ,          
@RestController
@RequestMapping("stu")
**@CrossOrigin//       ,      **
public class StuController {
    //  post       
    @RequestMapping("add")
    public Student add(Student s) throws Exception {
        System.out.println(s);
        **return s;**
    }
}
C5,테스트
在这里插入图片描述
3.SpringMVC 정리
C1,원리
C2,자주 사용 하 는 주해
@RestController:사용자 의 요청 을 받 아들 이 고 json 데이터@RequestMapping:요청 경로 와 일치 합 니 다@PathVariable:restful 의 매개 변수 값@CrossOrigin 가 져 오기:크로스 도 메 인 문제 해결(IP 가 다 르 거나 포트 가 다 름)
C3,분석 매개 변수
SpringMVC 는 하나의 인 자 를 처리 할 수도 있 고 여러 개의 인 자 를 처리 할 수도 있다.필요 하 다 면 여러 개의 인 자 를 자바 대상 으로 밀봉 할 수 있 습 니 다.GET 방식 으로 데 이 터 를 제출 할 수 있 습 니 다.Controller 층 에서 직접 방법의 매개 변수 목록 을 일치 해석 하면 됩 니 다.Restful 방식 으로 데 이 터 를 제출 할 수 있 습 니 다.Controller 층 에 서 는@PathVariable 주 해 를 사용 하여 주소 표시 줄 의 값 을 가 져 오고 방법의 매개 변수 목록 을 일치 해석 하면 POST 방식 으로 데 이 터 를 제출 할 수 있 습 니 다.Controller 층 에서 자바 대상 으로 요청 인 자 를 직접 받 아들 이면 됩 니 다.
C4,json 꼬치 되 돌리 기
이전 버 전 은@Response Body 를 사용 하여 데 이 터 를 json 문자열 로 바 꾸 고 브 라 우 저 에 새로운 버 전 으로 되 돌려 줍 니 다.@RestController 를 사용 하여 데 이 터 를 json 문자열 로 바 꾸 고 브 라 우 저 에 게 되 돌려 줍 니 다.

C1,개념
SpringMVC 프레임 워 크 는 요청 을 받 고 응답 하 는 Spring 프레임 워 크 를 사용 하여 Bean 을 관리 합 니 다.핵심 구성 요소 인 Bean Factory 는 Bean 을 저장 하 는 데 사 용 됩 니 다.Application Context 는 Spring 용기 입 니 다.IOC 는 반전 을 제어 하 는 것 으로 뉴 의 과정 을 스프링 에 맡 기 는 것 을 말한다.DI 는 의존 주입 이란 spring 프레임 워 크 가 대상 간 의존 관 계 를 자동 으로 조립 할 수 있 도록 하 는 것 을 말한다.AOP 가 절단면 을 향 해 프로 그래 밍 하 는 것 은 일종 의 사상 이다.
C2,Spring IOC
필요:클래스 를 만 들 고 spring 프레임 워 크 에 ioc(new)를 전달 합 니 다.
在这里插入图片描述
Hello 클래스 만 들 기

package cn.tedu.spring;
public class Hello {
    public void show(){
        System.out.println("hello springioc~");
    }
}
설정 클래스 의 정보 생 성 spring 의 핵심 프로필:resources-오른쪽 단 추 를 누 르 면-new-xml configuration-spring configure-설정 파일 의 이름-리 턴

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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">
    <!--     spring         ,        bean-->
    <!--  bean  ,        
        class           (  .  )
        id      bean     
        IOC: spring    Hello   
        Map==={"hello",new Hello()}
    -->
    <bean class="cn.tedu.spring.Hello" id="hello"></bean>
</beans>
테스트(spring 용기 에서 대상 가 져 오기)

package cn.tedu.spring;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
//   spring      ioc ???
public class TestIOC {
    //    ::       。@Test + void +      + public
    @Test
    public void ioc(){
        //1,  spring       
        ClassPathXmlApplicationContext spring =
                    new ClassPathXmlApplicationContext(
                            "spring-config.xml");
        //2, spring     bean  --ioc
        Object o = spring.getBean("hello");
        Object o2 = spring.getBean("hello");
        System.out.println(o == o2);//true
    }
}
총결산
이 글 은 여기까지 입 니 다.당신 에 게 도움 을 줄 수 있 기 를 바 랍 니 다.또한 당신 이 우리 의 더 많은 내용 에 관심 을 가 져 주 실 수 있 기 를 바 랍 니 다!

좋은 웹페이지 즐겨찾기