第二阶段2

一,在Vue项目中创建多个组件

–1,项目结构

–2,创建自定义组件Person.vue

 <template>
    <div>
        {
   
   {msg}}
    </div>
  </template>
  <script>
  //表明 这个组件可以导出
  export default{
      name:'Person',//组件名
      data(){
        return{
          msg :'hello vue project~'
        }
      }
  }
  </script>
  ​
  <style>
  </style

–3,创建自定义组件Student.vue

  
  <template>
    <h1>姓名:{
  
  {name}}</h1>
  </template>
  ​
  <script>
    export default{
      name:'Student',
      data(){
        return{
          name:"hello vue~"
        }
      }
    }
  </script>
  ​
  <style>
  </style>

–4,修改App.vue

  
  <template>
    <div id="app">
      <!-- 3,使用自定义的组件-->
      <Person></Person>
      <Student></Student>
    </div>
  </template>
  <script>
  //1.导入指定的自定义组件 ,路径要求必须有./
  import Person from './components/Person.vue'
  import Student from './components/Student.vue'
  ​
  export default {
    name: 'App',
    components:{ //2.添加组件
      Person,//使用第一步导入成功的组件名
      Student
    }
  }
  </script>
  ​
  <style>
  #app {
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    margin-top: 60px;
  }
  </style>
  ​

–5,测试

启动服务器,打开浏览器访问 http://localhost:8080 看效果

二,在Vue项目中创建路由

–0,项目结构

–1,自定义组件t1

  
  <template>
    <h1>我是t1</h1>
  </template>
  ​
  <script>
  </script>
  ​
  <style>
  </style>

–2,自定义组件t2

  
  <template>
    <h1>我是t2</h1>
  </template>
  ​
  <script>
  </script>
  ​
  <style>
  </style>

–3,自定义路由router.js

  
  import Vue from 'vue'
  import Router from 'vue-router'
  import HelloWorld from '@/components/HelloWorld'
  ​
  //1.引入自定义的组件位置
  import t1 from '@/components/t1'
  import t2 from '@/components/t2'
  ​
  Vue.use(Router)
  ​
  export default new Router({
    routes: [
      /* 2.定义路由的细则,什么请求路由到哪个组件 */
      { path: '/', component: HelloWorld },
      { path: '/t1', component: t1 },
      { path: '/t2', component: t2 }
    ]
  })

–4,修改App.vue使用路由

  
  <template>
    <div id="app">
      <!-- 3,使用自定义的组件-->
      <Person></Person>
      <Student></Student>
  ​
      <!-- 使用路由规则-->
      <router-link to="/t1">t1</router-link>
      <router-link to="/t2">t2</router-link>
      <router-view></router-view>
  ​
    </div>
  </template>
  <script>
  //1.导入指定的自定义组件 ,路径要求必须有./
  import Person from './components/Person.vue'
  import Student from './components/Student.vue'
  ​
  export default {
    name: 'App',
    components:{ //2.添加组件
      Person,//使用第一步导入成功的组件名
      Student
    }
  }
  </script>
  ​
  <style>
  #app {
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    margin-top: 60px;
  }
  </style>

–5,测试

启动服务器,打开浏览器测试http://localhost:8080

–6,总结

三,Tomcat服务器–1,概述服务器: 就是一台电脑web服务器:就是一台电脑上装了一个软件,用户可以通过浏览器访问这台上的资源Tomcat服务器:就是一个软件,是一个轻量级的web应用服务器.如果你的程序想要被用户访问,那么,这个程序必须放入Tomcat中

–2,使用步骤1,直接解压Tomcat压缩包就可以了,但是解压位置的路径中不能包含中文等特殊符号1参考: D:\Java\apache-tomcat-8.5.72

2, 开启服务器:去 D:\Java\apache-tomcat-8.5.72\bin文件夹里,找一个startup.bat双击就可以启动服务器啦,前提是:必须配置JAVA_HOME的环境变量

3, 开启成功:

4,关闭服务器去 D:\Java\apache-tomcat-8.5.72\bin文件夹里,找一个shutdown.bat双击就可以关闭服务器啦

5,访问服务器启动服务器后,打开浏览器访问 http://localhost:8080/其中的8080是Tomcat软件使用的默认端口号

–3,访问自己的项目1,把你的项目放在D:\Java\apache-tomcat-8.5.72\webapps里面注意: webapps里只能存放文件夹,文件夹里再存你的资源…文件夹名称就是项目名称

2,重启服务器,打开浏览器访问

访问规则: http://localhost:8080/项目名称/资源名称例如: http://localhost:8080/shopping/student.html

–4,一个完整的目录结构

四,IDEA整合Tomcat

–1,配置

–2,启动 & 关闭

五,Servlet–1,概述代表了一个服务器端,主要作用是用来和浏览器动态的交换.1,接受浏览器发来的请求2,服务器给浏览器做出响应

–2,准备动作在IDEA里创建一个web工程1,File- New- Project- 选择Java Enterprise并在右侧勾选Web Application(web.xml)- 输入工程名称-Finish2,需要下载IDEA的童鞋,可以访问网址:达内开发文档服务器去找到[常用下载] ,下载[IntelliJ IDEA Ultimate 终极版 Windows 官网下载 百度云盘 密码:125m]

整理web工程目录结构在WEB-INF里,创建两个文件夹classes 和 lib

修改资源输出位置

修改jar包存放位置

配置Tomcat服务器

–3,Servlet的入门案例

创建Servlet

  
  package cn.tedu.servlet;
  ​
  import javax.servlet.ServletException;
  import javax.servlet.annotation.WebServlet;
  import javax.servlet.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  import java.io.IOException;
  //Servlet核心功能: 接受请求 + 给出响应
  @WebServlet("/ServletDemo1")
  public class ServletDemo1 extends HttpServlet {
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          //打印一句话  --- 在idea里看
          System.out.println("欢迎来到Servlet的世界~");
          //给浏览器做出响应  --- 在浏览器里看
          response.getWriter().write("hello servlet!!");
      }
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          //你要写的代码和doPost()一样,直接调用上面方法就行啦
          doPost(request,response);
      }
  }

访问Servlet

http://localhost:8080/cgb2109javaweb_war_exploded/ServletDemo1

一,注解方式开发Servlet程序

–1,创建新的web工程,创建Servlet

  
  package cn.tedu.servlet;
  ​
  import javax.servlet.ServletException;
  import javax.servlet.annotation.WebServlet;
  import javax.servlet.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  import java.io.IOException;
  ​
  //1,这是新版本的Servlet提供的注解开发方式,更好更简单(否则自己写配置文件)
  //参数是,规定了浏览器的地址栏到底怎么写才能访问到我这个Servlet类
  //2,ServletDemo1是子类,可以使用父类的所有资源(除了私有的,构造方法)
  //3,自定义Servlet的规则:
  //方式1:extends HttpServlet--推荐!!!
  //方式2:extends GenericServlet--了解
  //方式3:implements Servlet--了解
  @WebServlet("/ServletDemo1")
  public class ServletDemo1 extends HttpServlet {
      //4,继承了父类,但是  想改父类原有的功能时 就重写!!
      //5,不论调用doPost()或者doGet(),都是由Servlet来调用的
  //6,当用户用post方式提交请求时(form表单提交),Servlet来调用doPost()
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          System.out.println("您访问了doPost()");
      }
  //7,当用户用get方式提交请求时,Servlet来调用doGet()
      //(在地址栏?拼接数据 + form没改method的值)
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          System.out.println("您访问了doGet()");
      }
  }

–2,测试Servlet启动服务器,访问浏览器http://localhost:8080/cgb2109javaweb03_war_exploded/ServletDemo1本机 Tomcat默认的端口号 项目名称 项目中的资源名称

二,配置方式开发Servlet程序–1,创建Servlet类

  
  package cn.tedu.servlet;
  import javax.servlet.ServletException;
  import javax.servlet.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  import java.io.IOException;
  //使用配置方式开发Servlet程序
  public class ServletDemo2 extends HttpServlet {
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          System.out.println("doPost()成功的被Servlet调用!");
      }
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          System.out.println("doGet()成功的被Servlet调用!");
      }
  }

–2,配置Servlet类

  
  <?xml version="1.0" encoding="UTF-8"?>
  <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
           version="4.0">
      <!--配置Servlet类的访问信息-->
      <servlet>
          <!--给Servlet设置一个名字(一般是和类名相同)
              细则:名字可以自定义,但是必须唯一,
              不能和别的<servlet>的<servlet-name>相同
          -->
          <servlet-name>hello</servlet-name>
          <!--指定Servlet类的全路径(包名.类名)-->
          <servlet-class>cn.tedu.servlet.ServletDemo2</servlet-class>
      </servlet>
      <!--指定浏览器的访问规则-->
      <servlet-mapping>
          <!--即将根据指定的名字,去找到一个要被访问的Servlet类的全路径-->
          <servlet-name>hello</servlet-name>
          <!--指定了浏览器的访问方式,
          细则:值可以自定义,但是浏览器必须是一样的写法才能访问Servlet
          否则404:找不到你要访问的资源
          -->
           <!--url-pattern的值不能和其他的url-pattern的值相同-->
          <url-pattern>/a/b/c</url-pattern>
      </servlet-mapping>
  ​
  </web-app>

–3,测试

http://localhost:8090/cgb2109javaweb03_war_exploded/ServletDemo2

–4,总结

三,前后端整合

–1,创建前端HTML网页

  
  <!DOCTYPE html>
  <html>
      <head>
          <meta charset="utf-8">
          <title>前后端 安排起来</title>
      </head>
      <body>
          <!-- 点击超链接跳转到Servlet -->
          <a href="http://localhost:8090/cgb2109javaweb03_war_exploded/ServletDemo3">点我,访问Servlet</a>
          
      </body>
  </html>

–2,创建后端Servlet程序

  
  package cn.tedu.servlet;
  ​
  import javax.servlet.ServletException;
  import javax.servlet.annotation.WebServlet;
  import javax.servlet.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  import java.io.IOException;
  ​
  public class ServletDemo3 extends HttpServlet {
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          System.out.println("doPost()");
      }
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          System.out.println("doGet()");
      }
  }

–3,配置Servlet类

  
  <?xml version="1.0" encoding="UTF-8"?>
  <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
           version="4.0">
      <!--配置Servlet类的访问信息-->
      <servlet>
          <!--给Servlet设置一个名字(一般是和类名相同)
              细则:名字可以自定义,但是必须唯一,
              不能和别的<servlet>的<servlet-name>相同
          -->
          <servlet-name>hello</servlet-name>
          <!--指定Servlet类的全路径(包名.类名)-->
          <servlet-class>cn.tedu.servlet.ServletDemo2</servlet-class>
      </servlet>
      <!--指定浏览器的访问规则-->
      <servlet-mapping>
          <!--即将根据指定的名字,去找到一个要被访问的Servlet类的全路径-->
          <servlet-name>hello</servlet-name>
          <!--指定了浏览器的访问方式,
          细则:值可以自定义,但是浏览器必须是一样的写法才能访问Servlet
          否则404:找不到你要访问的资源
          -->
          <url-pattern>/a/b/c</url-pattern>
      </servlet-mapping>
  ​
      <servlet>
          <servlet-name>hello2</servlet-name>
          <servlet-class>cn.tedu.servlet.ServletDemo3</servlet-class>
      </servlet>
      <servlet-mapping>
          <servlet-name>hello2</servlet-name>
          <!--url-pattern的值不能和其他的url-pattern的值相同-->
          <url-pattern>/ServletDemo3</url-pattern>
      </servlet-mapping>
      
  </web-app>

–4,测试

四,Servlet的继承结构

五,Servlet的生命周期–1,概述分为三大阶段初始化 – 由Servlet主动调用init()提供服务 – 由Servlet主动调用service()/doGet()/doPost()销毁 – 由Servlet主动调用destroy()

–2,测试创建Servlet程序

  
  package cn.tedu.lifecycle;
  import javax.servlet.ServletException;
  import javax.servlet.annotation.WebServlet;
  import javax.servlet.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  import java.io.IOException;
  //1,Servlet程序的注解开发方式,代替了web.xml文件中的8行配置代码
  @WebServlet("/ServletDemo4")//注解的参数是指浏览器的访问方式
  public class ServletDemo4 extends HttpServlet {
      //2,Servlet的生命周期中会被调用的方法有:
      //init() service()/doGet/doPost destroy()
      //3,因为GenericServlet提供的以上方法中都是空实现,
      // 重写这些方法并添加方法体来感受初始化的不同阶段
      //4,重写的要求:有足够的权限 + 方法声明必须和父类一样
      @Override
      //当第一次访问Servlet程序时,Servlet自己调用init(),只会调用一次
      public void init() throws ServletException {
          System.out.println("init()被调用了,Servlet已被初始化!");
      }
      @Override
      //每次访问Servlet程序时,Servlet自己调用service(),会调用多次
      protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
          System.out.println("service()开始为您服务啦!");
      }
      @Override
      //正常的关闭服务器时,Servlet自己调用destroy(),只会调用一次
      public void destroy() {
          System.out.println("destroy()被调用了,Servlet即将被销毁!");
      }
  }

创建前端网页

  
  <!DOCTYPE html>
  <html>
      <head>
          <meta charset="utf-8">
          <title>前后端 安排起来</title>
      </head>
      <body>
          <!-- 点击超链接跳转到Servlet -->
          <a href="http://localhost:8090/cgb2109javaweb03_war_exploded/ServletDemo3">点我,访问ServletDemo3</a>
          <a href="http://localhost:8090/cgb2109javaweb03_war_exploded/ServletDemo4">点我,访问ServletDemo4</a>
          
      </body>
  </html>

测试

六,Request

–1,概述

是指 从前端浏览器 到 后端的Servlet程序 的访问过程,叫请求的过程可以使用Servlet提供的Request对象,来解析请求中的请求参数

–2,常用方法

  
  getParamter()--按照参数名获取参数值,但是只得到一个值
  getParamterValues()--按照参数名获取参数值,但是得到多个值,存入数组
  setCharacterEncoding()--如果请求参数中有中文,设置字符集为utf-8
  setAttribute()--设置属性
  getAttribute()--获取属性

–3,测试

创建HTML网页

  
  <!DOCTYPE html>
  <html>
      <head>
          <meta charset="utf-8">
          <title>前端提交数据,后端解析数据</title>
      </head>
      <body>
          <a href="http://localhost:8090/cgb2109javaweb03_war_exploded/ServletDemo5?name=jerry&pwd=123">点我,提交get数据1</a>
          <a href="http://localhost:8090/cgb2109javaweb03_war_exploded/ServletDemo5?hobby=篮球&hobby=足球">点我,提交get数据2</a>
      </body>
  </html>
  ​
  ​
  ​

创建Servlet程序,解析请求参数

  
  package cn.tedu.request;
  import javax.servlet.ServletException;
  import javax.servlet.annotation.WebServlet;
  import javax.servlet.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  import java.io.IOException;
  import java.util.Arrays;
  ​
  @WebServlet("/ServletDemo5")
  public class ServletDemo5 extends HttpServlet {
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          doGet(request, response);
      }
      //当用户以get方式提交数据时,Servlet会自动调用doGet()
      //get方式提交的数据,可以一个一个的解析getParameter()
      //也可以解析多个值getParameterValues()
      //如果使用的是Tomcat7.0以上的版本,get方式提交中文数据不会乱码
      protected void doGet(HttpServletRequest request,
                           HttpServletResponse response) throws ServletException, IOException {
          //1,request解析请求参数 name=jerry&pwd=123
          //1.1,获取一个值
          String s = request.getParameter("name");
          System.out.println(s);//获取name参数的值
          String pwd = request.getParameter("pwd");
          System.out.println(pwd);//获取pwd参数的值
          //1.2,获取到多个值
          String[] hobbies = request.getParameterValues("hobby");
          System.out.println( Arrays.toString(hobbies) );
          
      }
  }
  ​
  ​
  ​

七,表单提交数据

–1,创建HTML网页文件

  
  <!DOCTYPE html>
  <html>
      <head>
          <meta charset="utf-8">
          <title></title>
      </head>
      <body>
          <form action="http://localhost:8090/cgb2109javaweb03_war_exploded/ServletDemo6">
              <h3>测试 get提交数据</h3>
              姓名:<input type="text" placeholder="请输入姓名..." name="user"/> <br />
              密码:<input type="password" placeholder="请输入密码..." name="pwd"/> <br />
              <input type="submit" value="提交"/>
          </form>
          
          <form method="post" 
          action="http://localhost:8090/cgb2109javaweb03_war_exploded/ServletDemo6">
              <h3>测试 post提交数据</h3>
              姓名:<input type="text" placeholder="请输入姓名..." name="user"/> <br />
              密码:<input type="password" placeholder="请输入密码..." name="pwd"/> <br />
              <input type="submit" value="提交"/>
          </form>
      </body>
  </html>

–2,创建Servlet程序

  
  package cn.tedu.request;
  import javax.servlet.ServletException;
  import javax.servlet.annotation.WebServlet;
  import javax.servlet.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  import java.io.IOException;
  @WebServlet("/ServletDemo6")
  public class ServletDemo6 extends HttpServlet {
      //TODO 处理post方式提交的数据--可能出现中文乱码!!
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  ​
      }
      //ServletDemo6?user=jack&pwd=123
      //处理get方式提交的数据
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          String user = request.getParameter("user");//获取user的值
          String pwd = request.getParameter("pwd");//获取pwd的值
          System.out.println(user+pwd);
      }
  }

一,模拟Servlet解析请求参数

–1,测试

  
  package cn.tedu;
  //模拟Servlet解析请求参数的对象Request
  public class MyRequest {
      public static void main(String[] args) {
          //this是代表的本类对象,static里不能出现this,原因就是加载顺序
  //        this.getParamter();
          MyRequest my = new MyRequest();
          my.getParamter();
      }
      //1,getParamter()获取每个请求参数
      public void getParamter(){
          String url="http://localhost:8090/cgb2109javaweb03_war_exploded/ServletDemo6" +
                  "?user=jack&pwd=123" ;
  //        1,按照?切割字符串,切出来两部分,存入数组
          //[http://localhost:8090/cgb2109javaweb03/ServletDemo6,user=jack&pwd=123]
          String[] strs = url.split("\\?");//转义
  //        2,重点解析数组中的第二个元素,下标为1的元素
          String datas = strs[1];//user=jack&pwd=123
  //        3,把第二步的结果,按照&切割
          //[user=jack,pwd=123]
          String[] data = datas.split("&");
  //        4,遍历数组,获取每个数据
          for(String s : data){//遍历两次,第一次s是user=jack,第二次s是pwd=123
  //        5,按照=切割,得到数组 [user,jack],只要第二个元素
  //            String params = s.split("=")[1];//和下面两行等效,只是简写形式
              String[] ss = s.split("=");
              String params = ss[1];
              System.out.println(params);
          }
      }
  }

二,Servlet 解析post方式提交的数据

–1,测试

  
  package cn.tedu.request;
  import javax.servlet.ServletException;
  import javax.servlet.annotation.WebServlet;
  import javax.servlet.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  import java.io.IOException;
  @WebServlet("/ServletDemo6")
  public class ServletDemo6 extends HttpServlet {
      //总结1:Servlet什么时候会自动调用doPost()?什么时候会自动调用doGet()?
      //  Servlet会调用getMethod()来获取用户的访问方式,如果是POST会调用doPost()
      //  Servlet会调用getMethod()来获取用户的访问方式,如果是GET会调用doGet()
      //总结2:中文乱码问题?
      //    get方式提交数据没有乱码问题,Tomcat已经配置好了(URIEncoding="utf-8"),不必关心
      //    post方式提交的数据如果有中文一定乱码,request.setCharacterEncoding("utf-8");
      //TODO 处理post方式提交的数据--如果请求参数包含中,一定乱码!!
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          //验证,请求方式是post吗?
          String method = request.getMethod();
          //指定请求的方式使用的编码--解决中文乱码
          request.setCharacterEncoding("utf-8");
          String name=request.getParameter("user");
          String pwd = request.getParameter("pwd");
          System.out.println("doPost..."+name+pwd+"..."+method);
      }
      //ServletDemo6?user=jack&pwd=123
      //处理get方式提交的数据:如果出现中文不会乱码,Tomcat7.0以上都处理过了
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          String method = request.getMethod();
  ​
          String user = request.getParameter("user");//获取user的值
          String pwd = request.getParameter("pwd");//获取pwd的值
          System.out.println("doGet..."+user+pwd+"..."+method);
      }
  }

–2,前端HTML页面

  
  <!DOCTYPE html>
  <html>
      <head>
          <meta charset="utf-8">
          <title></title>
      </head>
      <body>
          <form action="http://localhost:8090/cgb2109javaweb03_war_exploded/ServletDemo6">
              <h3>测试 get提交数据</h3>
              姓名:<input type="text" placeholder="请输入姓名..." name="user"/> <br />
              密码:<input type="password" placeholder="请输入密码..." name="pwd"/> <br />
              <input type="submit" value="提交"/>
          </form>
          
          <form method="post" 
          action="http://localhost:8090/cgb2109javaweb03_war_exploded/ServletDemo6">
              <h3>测试 post提交数据</h3>
              姓名:<input type="text" placeholder="请输入姓名..." name="user"/> <br />
              密码:<input type="password" placeholder="请输入密码..." name="pwd"/> <br />
              <input type="submit" value="提交"/>
          </form>
      </body>
  </html>

三,综合案例–1,需求综合案例:1,准备前端HTML网页,让用户输入部门数据(编号,名称,地址)2,准备DeptServlet,接受请求,并且解析请求参数3,把解析成功的请求参数,进行入库3.1,准备jar包3.2,准备dept表(deptno,dname,loc)3.3,准备jdbc代码,进行insert的SQL语句操作

–2,创建HTML网页

  
  <!DOCTYPE html>
  <html>
      <head>
          <meta charset="utf-8">
          <title>前后端大融合</title>
          <style>
              input[type='text']{
                  width: 200px;/* 宽度*/
                  height: 30px;/* 高度  */
                  background-color: pink;/* 背景色 */
                  border-color: pink;/* 边框色 */
                  border-radius: 10px;/* 圆角边框 */
              }
              input[type="submit"]{
                  width: 80px;/* 宽度*/
                  height: 40px;/* 高度  */
                  background-color: gray;/* 背景色 */
                  border-color: gray;/* 边框色 */
                  color: white;/* 文字的颜色 */
                  font-size: 20px;/* 字号大小 */
              }
          </style>
      </head>
      <body>
          <form method="post" action="http://localhost:8090/cgb2109javaweb03_war_exploded/DeptServlet">
              <h1>添加部门数据</h1>
              <h3>编号:<input type="text" name="deptno"/></h3>
              <h3>名称:<input type="text" name="dname"/></h3>
              <h3>地址:<input type="text" name="loc"/></h3>
              <input type="submit" value="保存" />
          </form>
      </body>
  </html>

–3,创建DeptServlet类

  
  package cn.tedu.dept;
  ​
  import javax.servlet.ServletException;
  import javax.servlet.annotation.WebServlet;
  import javax.servlet.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  import java.io.IOException;
  import java.sql.Connection;
  import java.sql.DriverManager;
  import java.sql.PreparedStatement;
  ​
  @WebServlet("/DeptServlet")
  public class DeptServlet extends HttpServlet {
      //用户以post方式提交的数据,doPost()解析请求参数
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          try{
              //防止中文乱码
              request.setCharacterEncoding("utf-8");
              //用来获取网页中传递来的参数,
              //getParameter()的参数是网页中name属性的值
              String a = request.getParameter("deptno");
              String b = request.getParameter("dname");
              String c = request.getParameter("loc");
              //TODO  jdbc--把解析到的参数入库,,insert
              //获取驱动
              Class.forName("com.mysql.jdbc.Driver");
              //获取连接
              String url="jdbc:mysql:///cgb2109?characterEncoding=utf8";
              Connection con=DriverManager.getConnection(url,"root","root");
              //获取传输器Statement不安全低效,PreparedStatement安全防止了SQL攻击高效
              String sql="insert into dept values(?,?,?)";//sql骨架,?是占位符
              PreparedStatement p = con.prepareStatement(sql);
              //设置SQL的参数,执行SQL
              p.setObject(1,a);
              p.setObject(2,b);
              p.setObject(3,c);
              p.executeUpdate();
              //关闭资源
              p.close();
              con.close();
          }catch (Exception e){
              System.out.println("插入失败,请检查数据~");
          }
      }
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          //post提交的,不能写在这里,
      }
  }

–4,总结

四,请求转发–1,概述作用是想让AServlet调用BServlet的功能.过程: 浏览器访问AServlet ,但是AServlet偷偷调用了BServlet ,此时浏览器的地址栏没变全程只是一次请求实现:request.getRequsetDispather(访问BServlet的方式).forward(request,response)

–2,测试AServlet

  
  package cn.tedu.forwardtest;
  ​
  import javax.servlet.ServletException;
  import javax.servlet.annotation.WebServlet;
  import javax.servlet.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  import java.io.IOException;
  ​
  @WebServlet("/AServlet")
  public class AServlet extends HttpServlet {
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  ​
      }
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          System.out.println("AServlet被执行!");
          //实现请求转发:想让AServlet调用BServlet,本质上这是服务器的动作,浏览器没变化发现不了
          //要求:两个资源可以互相调用,但是要求两个资源必须在同一项目中
          //getRequestDispatcher()的参数是,对方的访问方式
          //请求转发本质上就是一次请求:在AServlet添加请求的数据,试试BServlet也能获取到就可以了
          request.setAttribute("name","rose");
          request.getRequestDispatcher("/BServlet").forward(request,response);
      }
  }

BServlet

  
  package cn.tedu.forwardtest;
  ​
  import javax.servlet.ServletException;
  import javax.servlet.annotation.WebServlet;
  import javax.servlet.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  import java.io.IOException;
  ​
  @WebServlet("/BServlet")
  public class BServlet extends HttpServlet {
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  ​
      }
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          System.out.println("BServlet被执行!");
          //获取在AServlet中存入的数据,其实就是根据key获取value
          Object data = request.getAttribute("name");
          System.out.println(data);
      }
  }

–3,总结

直接访问AServlet,背后的BServlet也会被执行,并且浏览器没变化.

五,响应Response

–1,概述

是指 从java程序组织好的数据 发送给 前端浏览器 的过程,叫响应常用方法

  
  getwriter()---给浏览器响应数据
  setContentType()---用来解决防止响应时的中文乱码
  senRedirect()--重定向

–2,测试

  
  package cn.tedu.response;
  ​
  import javax.servlet.ServletException;
  import javax.servlet.annotation.WebServlet;
  import javax.servlet.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  import java.io.IOException;
  import java.io.PrintWriter;
  ​
  //给浏览器响应数据
  @WebServlet("/ResponseServlet")
  public class ResponseServlet extends HttpServlet {
      protected void doGet(HttpServletRequest request,
                           HttpServletResponse response) throws ServletException, IOException {
          //3,如果想要响应中文,防止中文乱码
          response.setContentType("text/html;charset=utf-8");
          //1,获取写出流
          PrintWriter out = response.getWriter();
          //2,正式写出数据--写到浏览器
          out.write("hello servlet1~~~");
          out.write("hello servlet2~~~");
          out.write("hello servlet3~~~");
          out.write("你好servlet~~~");//中文乱码啦~
      }
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  ​
      }
  }

六,重定向

–1,概述

特点:1, 整个过程有 两个请求 两个响应2, 地址栏会发生改变使用: response.sendRedirect(对方的访问方式)此时,你想访问哪个程序都可以

–2,测试

ServletA

package cn.tedu.redirect;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/ServletA")
public class ServletA extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //面试题:重定向和请求转发的区别???
        //1,请求转发是请求request的功能,全程1次请求1次响应,地址栏不变
            //request.getRequestDispather("目标访问的方式").forward(请求,响应)
        //2,重定向是response的功能,全程2次请求2次响应,地址栏改变
            //response.sendRedirect("目标访问的方式")
        response.sendRedirect("https://www.baidu.com/");
    }
}


ServletB

package cn.tedu.redirect;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/ServletB")
public class ServletB extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}


一,优化MyRequest类

–1,测试

package cn.tedu;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

//模拟Servlet解析请求参数的对象Request
public class MyRequest {
    public static void main(String[] args) {
        //this是代表的本类对象,static里不能出现this,原因就是加载顺序
//        this.getParamter();
        MyRequest my = new MyRequest();
        //查询指定参数名对应的值
        String u = my.getParamter("pwd");
        System.out.println(u);
    }
    //1,getParamter()获取每个请求参数
    public String getParamter(String keyword){
        String url="http://localhost:8090/cgb2109javaweb03_war_exploded/ServletDemo6" +
                "?user=jack&pwd=123" ;
        String[] data = url.split("\\?")[1].split("&");
        //Map存数据有特性,数据必须以键值对的形式存在,可以根据key找value
        Map<String,String> map = new HashMap<>();//{pwd=123, user=jack}
//        4,遍历数组,获取每个数据
        for(String s : data){//遍历两次,第一次s是user=jack,第二次s是pwd=123
//        5,按照=切割,得到数组 [user,jack],只要第二个元素
            String[] ss = s.split("=");
            String value = ss[1];
            String key = ss[0];
            map.put(key,value);//存入map
        }
        return map.get(keyword);//去map里找key对应的value,{pwd=123, user=jack}
    }
}


二,Maven–1,概述目前我们管理jar包的方式: 搜jar包 , 下载 , 存放jar包 , 导入jar包, 编译jar包…太复杂用Maven来管理jar包,帮我们处理以上所有流程.

1.仓库远程仓库/中央仓库: 本质上就是一个 国外的 网址镜像仓库: 本质上就是一个 国内的 网址,网站上存了去中央仓库下载好的jar包,常用的是阿里云本地仓库: 就是你在电脑里创建的一个文件夹,存放从镜像仓库中下载的jar包D:\Java\maven\resp

2,坐标: 能够快速定位jar包groupId: 组id,通常值是公司域名artifactId: 项目id,通常值是项目名称version: 版本

3.依赖项目的运行需要依赖jar包,jar包间也有依赖关系.使用dependency来指定需要的jar包坐标

4.命令:clean: 清除maven缓存install: 安装

–2,使用步骤1, 解压apache-maven-3.6.3.rar2, 打开解压好的文件夹,里面有一个conf,再里面有一个settings.xml3, 在settings.xml中进行配置, 镜像仓库和本地仓库

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

<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->

<!--
 | This is the configuration file for Maven. It can be specified at two levels:
 |
 |  1. User Level. This settings.xml file provides configuration for a single user,
 |                 and is normally provided in ${user.home}/.m2/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -s /path/to/user/settings.xml
 |
 |  2. Global Level. This settings.xml file provides configuration for all Maven
 |                 users on a machine (assuming they're all using the same Maven
 |                 installation). It's normally provided in
 |                 ${maven.conf}/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -gs /path/to/global/settings.xml
 |
 | The sections in this sample file are intended to give you a running start at
 | getting the most out of your Maven installation. Where appropriate, the default
 | values (values used when the setting is not specified) are provided.
 |
 |-->
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <!-- localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ${user.home}/.m2/repository 
    -->
  <localRepository>D:\Java\maven\resp</localRepository>


  <!-- interactiveMode
   | This will determine whether maven prompts you when it needs input. If set to false,
   | maven will use a sensible default value, perhaps based on some other setting, for
   | the parameter in question.
   |
   | Default: true
  <interactiveMode>true</interactiveMode>
  -->

  <!-- offline
   | Determines whether maven should attempt to connect to the network when executing a build.
   | This will have an effect on artifact downloads, artifact deployment, and others.
   |
   | Default: false
  <offline>false</offline>
  -->

  <!-- pluginGroups
   | This is a list of additional group identifiers that will be searched when resolving plugins by their prefix, i.e.
   | when invoking a command line like "mvn prefix:goal". Maven will automatically add the group identifiers
   | "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not already contained in the list.
   |-->
  <pluginGroups>
    <!-- pluginGroup
     | Specifies a further group identifier to use for plugin lookup.
    <pluginGroup>com.your.plugins</pluginGroup>
    -->
  </pluginGroups>

  <!-- proxies
   | This is a list of proxies which can be used on this machine to connect to the network.
   | Unless otherwise specified (by system property or command-line switch), the first proxy
   | specification in this list marked as active will be used.
   |-->
  <proxies>
    <!-- proxy
     | Specification for one proxy, to be used in connecting to the network.
     |
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>proxyuser</username>
      <password>proxypass</password>
      <host>proxy.host.net</host>
      <port>80</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
    -->
  </proxies>

  <!-- servers
   | This is a list of authentication profiles, keyed by the server-id used within the system.
   | Authentication profiles can be used whenever maven must make a connection to a remote server.
   |-->
  <servers>
    <!-- server
     | Specifies the authentication information to use when connecting to a particular server, identified by
     | a unique name within the system (referred to by the 'id' attribute below).
     |
     | NOTE: You should either specify username/password OR privateKey/passphrase, since these pairings are
     |       used together.
     |
    <server>
      <id>deploymentRepo</id>
      <username>repouser</username>
      <password>repopwd</password>
    </server>
    -->

    <!-- Another sample, using keys to authenticate.
    <server>
      <id>siteServer</id>
      <privateKey>/path/to/private/key</privateKey>
      <passphrase>optional; leave empty if not used.</passphrase>
    </server>
    -->
  </servers>

  <!-- mirrors
   | This is a list of mirrors to be used in downloading artifacts from remote repositories.
   |
   | It works like this: a POM may declare a repository to use in resolving certain artifacts.
   | However, this repository may have problems with heavy traffic at times, so people have mirrored
   | it to several places.
   |
   | That repository definition will have a unique id, so we can create a mirror reference for that
   | repository, to be used as an alternate download site. The mirror site will be the preferred
   | server for that repository.
   |-->
  <mirrors>
    <!-- mirror
     | Specifies a repository mirror site to use instead of a given repository. The repository that
     | this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used
     | for inheritance and direct lookup purposes, and must be unique across the set of mirrors.
     |
    <mirror>
      <id>mirrorId</id>
      <mirrorOf>repositoryId</mirrorOf>
      <name>Human Readable Name for this Mirror.</name>
      <url>http://my.repository.com/repo/path</url>
    </mirror>
     -->
      <!-- 达内私服地址 -->
	<!--<mirror>
		<id>nexus</id>
		<name>Tedu Maven</name>
		<mirrorOf>*</mirrorOf>
		<url>http://maven.tedu.cn/nexus/content/groups/public/</url>
	</mirror>-->

	<!--阿里私服地址-->
	<mirror>
		<id>ali</id>
		<name>ali Maven</name>
		<mirrorOf>*</mirrorOf>
		<url>https://maven.aliyun.com/repository/public/</url>
	</mirror>
	<!--
	<mirror>
        <id>nexus-aliyun</id>
        <mirrorOf>*</mirrorOf>
        <name>Nexus aliyun</name>
        <url>http://maven.aliyun.com/nexus/content/groups/public</url>
 	</mirror> 
 	<mirror>
	  <id>aliyunmaven</id>
	  <mirrorOf>*</mirrorOf>
	  <name>阿里云公共仓库</name>
	  <url>https://maven.aliyun.com/repository/public</url>
	</mirror>
	-->
  </mirrors>

  <!-- profiles
   | This is a list of profiles which can be activated in a variety of ways, and which can modify
   | the build process. Profiles provided in the settings.xml are intended to provide local machine-
   | specific paths and repository locations which allow the build to work in the local environment.
   |
   | For example, if you have an integration testing plugin - like cactus - that needs to know where
   | your Tomcat instance is installed, you can provide a variable here such that the variable is
   | dereferenced during the build process to configure the cactus plugin.
   |
   | As noted above, profiles can be activated in a variety of ways. One way - the activeProfiles
   | section of this document (settings.xml) - will be discussed later. Another way essentially
   | relies on the detection of a system property, either matching a particular value for the property,
   | or merely testing its existence. Profiles can also be activated by JDK version prefix, where a
   | value of '1.4' might activate a profile when the build is executed on a JDK version of '1.4.2_07'.
   | Finally, the list of active profiles can be specified directly from the command line.
   |
   | NOTE: For profiles defined in the settings.xml, you are restricted to specifying only artifact
   |       repositories, plugin repositories, and free-form properties to be used as configuration
   |       variables for plugins in the POM.
   |
   |-->
  <profiles>
    <!-- profile
     | Specifies a set of introductions to the build process, to be activated using one or more of the
     | mechanisms described above. For inheritance purposes, and to activate profiles via <activatedProfiles/>
     | or the command line, profiles have to have an ID that is unique.
     |
     | An encouraged best practice for profile identification is to use a consistent naming convention
     | for profiles, such as 'env-dev', 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc.
     | This will make it more intuitive to understand what the set of introduced profiles is attempting
     | to accomplish, particularly when you only have a list of profile id's for debug.
     |
     | This profile example uses the JDK version to trigger activation, and provides a JDK-specific repo.
    <profile>
      <id>jdk-1.4</id>

      <activation>
        <jdk>1.4</jdk>
      </activation>

      <repositories>
        <repository>
          <id>jdk14</id>
          <name>Repository for JDK 1.4 builds</name>
          <url>http://www.myhost.com/maven/jdk14</url>
          <layout>default</layout>
          <snapshotPolicy>always</snapshotPolicy>
        </repository>
      </repositories>
    </profile>
    -->

    <!--
     | Here is another profile, activated by the system property 'target-env' with a value of 'dev',
     | which provides a specific path to the Tomcat instance. To use this, your plugin configuration
     | might hypothetically look like:
     |
     | ...
     | <plugin>
     |   <groupId>org.myco.myplugins</groupId>
     |   <artifactId>myplugin</artifactId>
     |
     |   <configuration>
     |     <tomcatLocation>${tomcatPath}</tomcatLocation>
     |   </configuration>
     | </plugin>
     | ...
     |
     | NOTE: If you just wanted to inject this configuration whenever someone set 'target-env' to
     |       anything, you could just leave off the <value/> inside the activation-property.
     |
    <profile>
      <id>env-dev</id>

      <activation>
        <property>
          <name>target-env</name>
          <value>dev</value>
        </property>
      </activation>

      <properties>
        <tomcatPath>/path/to/tomcat/instance</tomcatPath>
      </properties>
    </profile>
    -->
    
  </profiles>

  <!-- activeProfiles
   | List of profiles that are active for all builds.
   |
  <activeProfiles>
    <activeProfile>alwaysActiveProfile</activeProfile>
    <activeProfile>anotherAlwaysActiveProfile</activeProfile>
  </activeProfiles>
  -->
</settings>


–3,把Maven整合到IDEA中

三,在IDEA中创建Maven工程

–1,步骤

File -New -Project -选中Maven -next -设置项目名称并设置公司域名 - Finish

–2,项目结构

–3,配置maven

四,使用Maven工程

–1,修改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>cn.tedu</groupId>
    <artifactId>cgb2109maven02</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!--添加jar包的依赖-->
    <dependencies>
        <!--添加jdbc的-->
        <dependency>
            <!--组id,通常是公司的域名-->
            <groupId>mysql</groupId>
            <!--项目id,通常是项目名称-->
            <artifactId>mysql-connector-java</artifactId>
            <!--指定jar包的版本号 5.1.48或者8.0.21,参考数据库的版本-->
            <version>5.1.48</version>
        </dependency>
    </dependencies>
</project>


–2,创建测试类

package cn.tedu.test;
//测试 jdbc:导入jar包
//以前:找到jar包,复制到工程中,编译jar包
//现在:直接在pom.xml文件中,添加了jar包的依赖,maven自动下载自动保存自动编译
public class Test1 {
    public static void main(String[] args) throws ClassNotFoundException {
        //1,注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        System.out.println(100);
    }
}


扩展1:Filter过滤器–1,概述用来过滤请求或者响应当A请求B时,可以在中间添加一个过滤器当A给B做出响应时,可以在中间添加一个过滤器

–2,使用步骤1, 创建类implements Filter接口2, 重写抽象方法doFilter3, 能否触发过滤器

–3,创建过滤器

package cn.tedu.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
//创建过滤器:implements Filter+重写抽象方法
@WebFilter("/*")//拦截所有请求
public class Filter1 implements Filter {
    //销毁,执行1次
    public void destroy() {
    }
    //类似于Servlet的service(),会被执行多次
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        System.out.println("过滤器开始执行任务~~");
        chain.doFilter(req, resp);//放行,解除阻塞状态
    }
    //初始化,执行1次
    public void init(FilterConfig config) throws ServletException {
    }
}


–4,测试

直接浏览器访问Servlet就可以触发过滤器的规则

–5,Filter生命周期

package cn.tedu.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
//创建过滤器:implements Filter+重写抽象方法
@WebFilter("/*")//拦截所有请求
public class Filter1 implements Filter {
    //第三阶段,销毁阶段,Filter会自动调用destroy(),只会执行1次
    public void destroy() {
        System.out.println("filter被销毁~~~");
    }
    //第二阶段,类似于Servlet的service()服务阶段,会被Filter执行多次
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        System.out.println("过滤器开始执行任务~~");
        chain.doFilter(req, resp);//放行,继续访问目标资源,否则目标资源无法执行
    }
    //第一阶段,初始化阶段,Filter会自动调用init(),只会执行1次
    public void init(FilterConfig config) throws ServletException {
        System.out.println("filter被初始化完成~~~");
    }
}


–6,测试

–7,过滤器的匹配规则

扩展2:ElementUI

–1,下载

E:\workspace\vue\jt>npm i element-ui -S   #参考官网的安装命令


–2,修改main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'

//引入了ElementUI相关的资源
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})


–3,使用ElementUI,修改Person.vue文件

<template>
  <div>
      {
  
  {msg}}
      <!-- 1,el-button组件用来实现按钮的功能,
      type用来指定按钮的颜色,round是圆角,circle是圆形,icon是给按钮加图标-->
      <el-button type="primary">主要按钮</el-button>
      <el-button type="success" round>成功按钮</el-button>
      <el-button type="danger" icon="el-icon-delete" circle></el-button>

      <!-- 2.图标,class用来指定图标的名字-->
      <i class="el-icon-share"></i>
      <i class="el-icon-star-off"></i>

      <!-- 3.el-input是输入框,placeholder是输入框的提示信息,
        v-model是双向绑定,可以获取指定变量的值也可以修改值
      -->
      <el-input placeholder="请在这里输入..." v-model="msg"></el-input>
  </div>
</template>
<script>
//表明 这个组件可以导出
export default{
    name:'Person',//组件名
    data(){
      return{
        msg :'hello vue project~'
      }
    }
}
</script>

<style>
</style>


–4,测试

重启Vue项目,然后直接访问http://localhost:8080/#/ 看看元素成功展示就可以了.

猜你喜欢

转载自blog.csdn.net/weixin_43762083/article/details/121522672