Restful风格--前后端分离

1 概念

RESTFUL是一种网络应用程序的设计风格和开发方式,基于HTTP,可以使用XML格式定义或JSON格式定义
         一种编码规范/一种网络应用程序的设计风格和开发方式:
         给前后台分列的项目的url定义规范:
应用场景:随着互联网的发展和不同数据终端的出现  要求同一个互联网应用要被不同的数据终端使用
        不管前端是:pc/ios/php  后台业务逻辑因该一样:要求我们的后台程序要适用于多个前端
        通过restful定义请求参数+返回值+url的规范 实现前后台开发的完全分离:
  • 规范1:虚拟目录
对于Student表 url的虚拟目录为/student
  • 规范2:请求方式
1:获取 get
2:添加 post
3:修改 put
4:删除 delete
  • 规范3:响应格式
json

2 具体url:Student类的请求

2.1 按主键获取一个

请求方式:get
请求url:/student/{sid}.action
请求参数:null
响应数据:json

2.2 获取所有

请求方式:get
请求url:/student.action
请求参数:null
响应数据:json

2.3 按主键删除一个

请求方式:delete
请求url:/student/{sid}.action
请求参数:null
响应数据:json

2.4 修改一个

请求方式:put
请求url:/student.action
请求参数:json
响应数据:json

2.5 添加一个

请求方式:post
请求url:/student.action
请求参数:json
响应数据:json

2.6 按条件查询

请求方式:get
请求url:/student/{sname}/{sage}/{sex}.action
请求参数:json
响应数据:json

3 搭建框架

3.1 创建表

CREATE TABLE `student` (
  `sid` int(11) NOT NULL AUTO_INCREMENT,
  `sname` varchar(11) DEFAULT NULL,
  `sex` char(1) DEFAULT NULL,
  `score` float(4,1) DEFAULT NULL,
  `sdy` tinyint(1) DEFAULT NULL,
  `sbirthday` date DEFAULT NULL,
  `sphoto` varchar(100) DEFAULT '20.jpg',
  PRIMARY KEY (`sid`)
) ENGINE=InnoDB AUTO_INCREMENT=241 DEFAULT CHARSET=utf8

3.2 创建maven的web项目

  • 完善项目结构
  • 在web-inf下复制核心标签库的tld文件

3.3 在pom.xml中引入依赖

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.zhiyou100</groupId>
  <artifactId>java37_06_restful</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <!-- 指定spring的版本 -->
    <spring.version>5.1.4.RELEASE</spring.version>
    <lombokVersion>1.16.10</lombokVersion>
  </properties>

  <dependencies>
    <!-- Spring相关包 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</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>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!-- AOP相关包 -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjrt</artifactId>
      <version>1.8.0</version>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.0</version>
    </dependency>

    <!-- MyBatis相关包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.3.0</version>
    </dependency>
    <!-- MySQL相关包 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.26</version>
    </dependency>
    <!-- 数据库连接池 -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.0.20</version>
    </dependency>

    <!-- Spring集成MyBatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.3</version>
    </dependency>

    <!-- JSP标准标签库 -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>
    <!-- 引入servlet-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>
    <!-- 日志相关包 -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.21</version>
    </dependency>

    <!-- 单元测试相关包 -->
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>5.1.3.RELEASE</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/junit/junit -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <!-- 引入json依赖 -->
    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.11.2</version>
    </dependency>
    <!-- 添加图片需要的依赖 -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.3</version>
    </dependency>
    <!--解决datetimeformat注解不能使用的问题-->
    <dependency>
      <groupId>joda-time</groupId>
      <artifactId>joda-time</artifactId>
      <version>2.3</version>
    </dependency>
    <!-- lombok插件导包-->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>${lombokVersion}</version>
      <scope>provided</scope>
    </dependency>
       <!--mybatis分页-->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>4.2.0</version>
    </dependency>
  </dependencies>
</project>

3.4 创建log4j配置文件:log4j.properties

log4j.rootLogger = INFO,stdout,D,E

log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n

log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = E://logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =E://logs/error.log 
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR 
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

log4j.logger.org.springframework.web.servlet.FrameworkServlet=INFO

3.5 创建spring核心配置文件:spring_config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	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/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/mvc 
	http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
	
	<!-- 1:通过context标签自动扫描包 -->
    <context:component-scan base-package="com.zhiyou100.service"/>
	<!--1 扫描除了action包以外的所有包 为添加注解的类创建bean
	<context:component-scan base-package="com.zhiyou100">
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
	</context:component-scan>
     -->

	<!-- 1 配置数据源dataSource 指定连接数据库的四大参数 -->
	<bean id="ds"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="url" value="jdbc:mysql://localhost:3306/db_37" />
		<property name="username" value="root" />
		<property name="password" value="root" />
		<property name="driverClassName"
			value="com.mysql.jdbc.Driver" />
	</bean>

	<!-- 2 创建sqlsessionfactory的bean 关联数据源 并指定mapper映射文件的位置 -->
	<bean class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="ds" />
		<!-- 指定sql的映射文件的包-->
		<property name="mapperLocations" value="classpath:mapper/*.xml"/>
		<!-- 引入mybatis的核心配置文件 -->
		<property name="configLocation" value="classpath:mybatis_config.xml"/>
	</bean>
    <!-- 通过tx标签实现service的事务管理-->
    <tx:annotation-driven/>

	<!-- 3 创建事务管理bean -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="ds" />
	</bean>

	<!-- 4 创建 MapperScannerConfigurer的bean 自动扫描mapper包 为mapper接口创建实现类对象 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.zhiyou100.dao" />
	</bean>
</beans>

3.6 创建springmvc配置文件:springmvc_config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans 	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans.xsd
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context.xsd
	http://www.springframework.org/schema/aop 
	http://www.springframework.org/schema/aop/spring-aop.xsd
	http://www.springframework.org/schema/mvc 
	http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!-- 0:引入context+aop+mvc的shcema -->
    <!-- 1:通过context标签自动扫描包 -->
    <context:component-scan base-package="com.zhiyou100.action"/>
    
    <!-- 2:通过mvc标签自动注册注解的处理器映射器和处理器适配器 -->
    <mvc:annotation-driven/>
    
    
    <!-- 3:配置视图解析器 -->
    <!-- ctrl+shift+t全workspase中查找类  -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
         <property name="prefix" value="/"/>
         <property name="suffix" value=".jsp"/>
    </bean> 
    
    <!-- 4:多部件表单解析器 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
          <property name="maxUploadSize" value="88888888"/>
          <property name="defaultEncoding" value="UTF-8"/>
    </bean>
    
    <!-- 5:配置所有的拦截器
    <mvc:interceptors>
       <mvc:interceptor>
             <mvc:mapping path="/*/*.action"/>
             <mvc:exclude-mapping path="/user/login.action"/>
             <mvc:exclude-mapping path="/ajax/getYzm.action"/>
             <bean  class="com.zhiyou100.interceptor.UserLoginInterceptor"/>
       </mvc:interceptor>
    </mvc:interceptors>
    -->
    
</beans>

3.7 创建mybatis核心配置文件:mybatis_config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <!-- 显示sql语句 -->
  <!-- -->
  <settings>
      <setting name="logImpl" value="STDOUT_LOGGING"/>
      <setting name="mapUnderscoreToCamelCase" value="true"/>
  </settings>
   
  <typeAliases>
     <package name="com.zhiyou100.entity"/>
  </typeAliases>
  <!-- 导入pagehelper的插件
  <plugins>
           <plugin interceptor="com.github.pagehelper.PageInterceptor"/>
  </plugins>
   -->
  <!-- 引入所有的sql映射文件 -->
</configuration>

3.8 修改web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>java37_06_restful</display-name>
  <!--1 配置欢迎页 -->
  <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>

  <!--2 配置项目的初始化参数 指定spring核心配置文件  -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring_config.xml</param-value>
  </context-param>
  <!-- 3 配置spring的上下文监听器 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!--4 配置springmvc的中央控制器 -->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 通过servlet的初始化参数指定springmbvc核心配置文件的位置 -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc_config.xml</param-value>
    </init-param>
    <!-- 指定第一个加载 -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.action</url-pattern>
  </servlet-mapping>


  <!-- 5 配置springmvc的全站编码过滤器 -->
  <filter>
    <filter-name>charsetFilter</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>
    <!-- 初始化参数指定强制使用此编码集 -->
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>charsetFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>ERROR</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
  </filter-mapping>
</web-app>

3.9 创建必要的包

image-20211213104802971

3.10 启动测试

补充1

  • 在maven的核心配置文件中设置jre的版本
  <profiles>
     <!--配置jre的版本-->
	<profile>
	    <id>jdk-1.8</id>
	    <activation>
	        <activeByDefault>true</activeByDefault>
	        <jdk>1.8</jdk>
	    </activation>
	    <properties>
	        <maven.compiler.source>1.8</maven.compiler.source>
	        <maven.compiler.target>1.8</maven.compiler.target>
	        <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
	    </properties>
	</profile>
      ...
</profiles>

4 功能分析

  • 获取所有
get   /student.action
  • 获取一个
get  /student/{sid}.action
  • 删除一个
delete  /student/{sid}.action
  • 添加一个:没有文件上传
post  /student.action   参数是json
  • 修改一个:没有文件上传
put  /student.action   参数是json
  • 文件上传:
post /student.action   多部件表单

5 功能实现

5.1 创建实体类

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student   implements Serializable {
    private  Integer sid;
    private String sname;
    private String sex;
    private Float score;
    private boolean sdy;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date sbirthday;
    private String sphoto;
}

5.2 创建dao接口和service 略

5.3 创建sql映射文件

  • 位置resources下的mapper包
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhiyou100.dao.StudentMapper">
      <select id="getAll" resultType="Student">
          select * from student
      </select>
       <select id="getOneBySid" resultType="Student">
          select * from student where sid=#{sid}
      </select>
      <delete id="deleteOne" parameterType="int">
           delete from student where sid=#{sid}
      </delete>
      <insert id="addOne" parameterType="Student">
           insert into student(sname,sex,score,sdy,sbirthday,sphoto)
           values(#{sname},#{sex},#{score},#{sdy},#{sbirthday},#{sphoto})
      </insert>
    <update id="updateOne" parameterType="Student">
        update  student
        <set>
            <if test="sname != null">
                   sname=#{sname},
            </if>
            <if test="sex != null">
                sex=#{sex},
            </if>
            <if test="score != null">
                score=#{score},
            </if>
            <if test="sdy != null">
                sdy=#{sdy},
            </if>
            <if test="sbirthday != null">
                sbirthday=#{sbirthday},
            </if>
            <if test="sphoto != null">
                sphoto=#{sphoto},
            </if>
        </set>
        where sid=#{sid}
    </update>
</mapper>

5.4 测试类

package com.zhiyou100;

import com.zhiyou100.service.StudentService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring_config.xml","classpath:springmvc_config.xml"})
public class TestStudentService {
    @Autowired
    private StudentService studentService;

    @Test
    public void test02(){
        System.out.println(studentService.getAll());
    }
}

6 action

  • 有待更改
package com.zhiyou100.action;

import com.zhiyou100.entity.ResponseVO;
import com.zhiyou100.entity.Student;
import com.zhiyou100.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class StudentAction {
      @Autowired
      private StudentService studentService;

      //获取一个
      @RequestMapping(value="/student/{sid}.action",method = RequestMethod.GET)
      @ResponseBody
      public ResponseVO<Student>  getOneBySidMethod(@PathVariable("sid") int sid){
              try {
                  Student student=studentService.getOneBySid(sid);
                  if(student!=null){
                      return new ResponseVO <Student>(200,null,student);
                  }
                  return new ResponseVO <Student>(4001,"学生不存在!",null);
              }catch(Exception e){
                  return new ResponseVO <Student>(5001,"获取"+sid+"失败!",null);
              }
      }

      //获取所有
    @RequestMapping(value="/student.action",method = RequestMethod.GET)
    @ResponseBody
    public ResponseVO<List<Student>>  getAllMethod(){
            return new ResponseVO <List<Student>>(200,null,studentService.getAll());
    }
    //删除一个
    @RequestMapping(value="/student/{sid}.action",method = RequestMethod.DELETE)
    @ResponseBody
    public ResponseVO<String>  deleteOneBySidMethod(@PathVariable("sid") int sid){
          studentService.deleteOne(sid);
          return new ResponseVO <String>(200,null,"删除成功");
    }

    //修改一个:无文件上传
    @RequestMapping(value="/student.action",method = RequestMethod.PUT)
    @ResponseBody
    public ResponseVO<String>  updateOneMethod(@RequestBody Student student){
        studentService.updateOne(student);
        return new ResponseVO <String>(200,null,"修改成功!");
    }

    //添加一个:无文件上传
    @RequestMapping(value="/student.action",method = RequestMethod.POST)
    @ResponseBody
    public ResponseVO<String>  addOneMethod(@RequestBody Student student){
        studentService.addOne(student);
        return new ResponseVO <String>(200,null,"添加成功");
    }
}

7 页面

  • 深刻理解:为什么必须用ajax请求
  • 引入:jquery.serializejson.min.js
  • 注意:每次添加文件夹如:js/imgs 必须clean项目 然后再发布

7.0 准备

<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
<div id="div_data">
    <table id="tab_data">
        <tr>
            <th>顺序</th><th>学号</th><th>名字</th><th>性别</th>
            <th>分数</th><th>党员</th><th>生日</th><th>照片</th>
        </tr>
    </table>
</div>
<script type="text/javascript">
    //文档加载成功 获取所有学生
    $(function(){
        $.get(path+"student.action",null,function(responseVO){
            for(var i=0;i<responseVO.data.length;i++){
                $("select[name='sel_getOne']").append("<option value='"+responseVO.data[i].sid+"'>"+responseVO.data[i].sid+"</option>");
                $("select[name='sel_deleteOne']").append("<option value='"+responseVO.data[i].sid+"'>"+responseVO.data[i].sid+"</option>");
                $("#select_updateOne").append("<option value='"+responseVO.data[i].sid+"'>"+responseVO.data[i].sid+"</option>");
            }
        },"json");
    });
</script>

7.1 获取所有

<!--获取所有-->
<script type="text/javascript">
    var path="<c:url value='/'/>";
    function getAll(){
        //发送ajax请求
        $.ajax({
            method:"GET",
            data:null,
            url:path+"student.action",
            dataType:"json",
            success:function(responseVO){
                //清空table
                $("#tab_data tr:gt(0)").remove();
                //拼凑tr
                for(var i=0;i<responseVO.data.length;i++){
                    var $tr=$("<tr></tr>");
                    $tr.append("<td>"+(i+1)+"</td>");
                    $tr.append("<td>"+responseVO.data[i].sid+"</td>");
                    $tr.append("<td>"+responseVO.data[i].sname+"</td>");
                    $tr.append("<td>"+responseVO.data[i].sex+"</td>");
                    $tr.append("<td>"+responseVO.data[i].score+"</td>");
                    $tr.append("<td>"+responseVO.data[i].sdy+"</td>");
                    var sbirthday=new Date(responseVO.data[i].sbirthday);
                    $tr.append("<td>"+date2Str(sbirthday)+"</td>");
                    var imgPath="<c:url value='/imgs/'/>"+responseVO.data[i].sphoto;
                    $tr.append("<td><img src='"+imgPath+"'/></td>");
                    $("#tab_data").append($tr);
                }
            }
        });
    }
</script>
<a  href="javascript:getAll();">获取所有</a><br/>

<script type="text/javascript">
    function date2Str(date){
        return date.getFullYear()+"年"+(date.getMonth()+1)+"月"+date.getDate()+"号";
    }
</script>

7.2 获取一个

<!--获取一个-->
<script type="text/javascript">
    function getOne(){
        //发送ajax请求
        var sid=$("select[name='sel_getOne']").val();
        $.ajax({
            method:"GET",
            data:null,
            url:path+"student/"+sid+".action",
            dataType:"json",
            success:function(responseVO){
                //清空table
                $("#tab_data tr:gt(0)").remove();
                //拼凑tr
                var $tr=$("<tr></tr>");
                $tr.append("<td>"+1+"</td>");
                $tr.append("<td>"+responseVO.data.sid+"</td>");
                $tr.append("<td>"+responseVO.data.sname+"</td>");
                $tr.append("<td>"+responseVO.data.sex+"</td>");
                $tr.append("<td>"+responseVO.data.score+"</td>");
                $tr.append("<td>"+responseVO.data.sdy+"</td>");
                var sbirthday=new Date(responseVO.data.sbirthday);
                $tr.append("<td>"+date2Str(sbirthday)+"</td>");
                var imgPath="<c:url value='/imgs/'/>"+responseVO.data.sphoto;
                $tr.append("<td><img src='"+imgPath+"'/></td>");
                $("#tab_data").append($tr);
            }
        });
    }
</script>
<select name="sel_getOne"></select>
<a  href="javascript:getOne();">获取一个</a><br/>

7.3 删除一个

<!--删除一个-->
<script type="text/javascript">
    function deleteOne(){
        //发送ajax请求
        var sid=$("select[name='sel_deleteOne']").val();
        $.ajax({
            method:"DELETE",
            data:null,
            url:path+"student/"+sid+".action",
            dataType:"json",
            success:function(responseVO){
                alert(responseVO.data);
                if(responseVO.status=200){
                    //清空table
                    $("#tab_data tr:gt(0)").remove();
                }
            }
        });
    }
</script>
<select name="sel_deleteOne"> </select>
<a  href="javascript:deleteOne();">删除一个</a><br/>

7.4 修改一个

<!--修改一个-->
<script src="<c:url value='/js/jquery.serializejson.min.js'/>"></script>
<script type="text/javascript">
    //给select_update添加oncnage事件
    $(function(){
        $("#select_updateOne").bind("change",function(){
            var sid=$("#select_updateOne").val();
            $.ajax({
                method:"GET",
                data:null,
                url:path+"student/"+sid+".action",
                dataType:"json",
                success:function(responseVO){
                    //设置两个input的值
                    $("#tab_update input[name='sname']").val(responseVO.data.sname);
                    $("#tab_update input[name='score']").val(responseVO.data.score);
                }
            });
        });
    });
    //响应json 请求json  put请求
    //方式1:自己拼凑json串
    function updateOne1(){
        alert(11);
        var sid=$("#select_updateOne").val();
        var sname=$("#form_update input[name='sname']").val();
        var score=$("#form_update input[name='score']").val();
        var jsonObj={"sid":sid,"sname":sname,"score":score};
        var jsonObjStr=JSON.stringify(jsonObj);//由json对象获取json串
        $.ajax({
            method:"PUT",
            data:jsonObjStr,   //传递的是json串 不是json(415)
            url:path+"student.action",
            dataType:"json",
            contentType:"application/json;charset=utf-8",/*请求参数是json:必须加请求头contentType 指定请求参数的类型*/
            success:function(responseVO){
                alert(responseVO.data);
            }
        });
    }
    //方式2:通过jquery.serializejson.js中的serializeJSON 获取表单数据拼凑的json对象
    function updateOne2(){
        var jsonObj=$("#form_update").serializeJSON();
        console.log(jsonObj);
        var jsonObjStr=JSON.stringify(jsonObj);//由json对象获取json串
        $.ajax({
            method:"PUT",
            data:jsonObjStr,   //传递的是json串 不是json(415)
            url:path+"student.action",
            dataType:"json",
            contentType:"application/json;charset=utf-8",/*请求参数是json:必须加请求头contentType 指定请求参数的类型*/
            success:function(responseVO){
                alert(responseVO.data);
            }
        });
    }
</script>


<form action="#" id="form_update">
    <table id="tab_update">
        <tr>
            <th>学生学号:</th>
            <td><select name="sid" id="select_updateOne"><option>请选择学号</option></select></td>
        </tr>
        <tr>
            <th>学生名字:</th>
            <td><input type="text" name="sname"/></td>
        </tr>
        <tr>
            <th>学生分数:</th>
            <td><input type="text" name="score"/></td>
        </tr>
        <tr>
            <th  colspan="2">
                <input type="button" value="修改一个1"  onclick="updateOne1()"/>
                <input type="button" value="修改一个2"  onclick="updateOne2()"/>
            </th>
        </tr>
    </table>
</form>

7.5 文件上传:添加

<!--文件上传:添加 -->
<script type="text/javascript">
    //响应json 请求:多部件表单 必须请求方式:post
    //通过js的FormData类 实现表单数据的序列化
    //var formdata=new FormData(form);可以通过append()方法来追加数据formdata.append("name","laotie");
    function addOne() {
        var dataForm = new FormData($("#form_add")[0]);//获取#form_add的FormData对象
        console.log(dataForm);
        $.ajax({
            method: "POST",
            data: dataForm,
            contentType: false,//如果请求参数是FormData 必须设置 contentType请求头为false
            processData: false,//如果请求参数是FormData 必须设置 processData请求头为false
            cache: false,
            url: path + "student/file.action",
            dataType: "json",
            success: function (responseVO) {
                alert(responseVO.data);
            }
        });
    }
</script>

<form action="#" id="form_add">
    <table id="tab_add">
        <tr>
            <th>学生名字:</th>
            <td><input type="text" name="sname"/></td>
        </tr>
        <tr>
            <th>学生分数:</th>
            <td><input type="text" name="score"/></td>
        </tr>
        <tr>
            <th>学生性别:</th>
            <td>男:<input type="radio" name="sex" value="男"/> |
                女:<input type="radio" name="sex" value="女"/></td>
        </tr>
        <tr>
            <th>是否党员:</th>
            <td>是:<input type="radio" name="sdy" value="true"/> |
                否:<input type="radio" name="sdy" value="false"/></td>
        </tr>
        <tr>
            <th>学生生日:</th>
            <td><input type="date" name="sbirthday"/></td>
        </tr>
        <tr>
            <th>学生照片:</th>
            <td><input type="file" name="photo"/></td>
        </tr>
        <tr>
            <th colspan="2">
                <input type="button" value="有文件上传的添加" onclick="addOne()"/>
            </th>
        </tr>
    </table>
</form>

posted @ 2021-12-14 22:23  RenVei  阅读(575)  评论(0编辑  收藏  举报