JSD-2204-创建Spring项目-Day19

1.创建Spring项目

 File ->new->Project

 

 点击Spring Initializr,进行配置

ServerURL修改为:https://start.aliyun.com

Name修改成项目的名字

Java改为8

Project SDK改为:1.8

选择Web,在SpringWeb那一栏打上对勾 

让后点击Finish

进入项目后需要在右边的Maven那一栏点开左上角有一个刷新按钮点击一下,

如果是第一次创建项目的小伙伴们,下载时间可能稍微长

2.把之前写的项目部署到Spring项目中

2.1项目目录

2.2Java文件

2.2.1UserController(业务逻辑层)

package com.myboot.myfirstspringboot.controller;

import com.myboot.myfirstspringboot.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 *  我创建的Controller类必须要添加注解@Controller
 *  并且处理某个请求的方法上要使用注解@RequestMapping
 */
@Controller
public class UserController {
    private static File userDir;
    static {
        userDir = new File("./users");
        if(!userDir.exists()){
            userDir.mkdirs();
        }
    }

    @RequestMapping("/myweb/showAllUser")
    public void showAllUser(HttpServletRequest request,HttpServletResponse response){
        List<User> userList = new ArrayList<>();
        File[] subs = userDir.listFiles(f -> f.getName().endsWith(".obj"));
        for (File userFile : subs) {
            try (
                    FileInputStream fis = new FileInputStream(userFile);
                    ObjectInputStream ois = new ObjectInputStream(fis);
            ) {
                User user = (User) ois.readObject();
                userList.add(user);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }

        System.out.println(userList);

        //2将数据拼接到html生成页面
        response.setContentType("text/html;charset=utf-8");

        try {
            PrintWriter pw = response.getWriter();
            pw.println("<!DOCTYPE html>");
            pw.println("<html lang=\"en\">");
            pw.println("<head>");
            pw.println("<meta charset=\"UTF-8\">");
            pw.println("<title>用户列表</title>");
            pw.println("</head>");
            pw.println("<body>");
            pw.println("<center>");
            pw.println("<h1>用户列表</h1>");
            pw.println("<table border=\"1\">");
            pw.println("<tr>");
            pw.println("<td>用户名</td>");
            pw.println("<td>密码</td>");
            pw.println("<td>昵称</td>");
            pw.println("<td>年龄</td>");
            pw.println("</tr>");
            for (User user : userList) {
                pw.println("<tr>");
                pw.println("<td>" + user.getUsername() + "</td>");
                pw.println("<td>" + user.getPassword() + "</td>");
                pw.println("<td>" + user.getNickname() + "</td>");
                pw.println("<td>" + user.getAge() + "</td>");
                pw.println("</tr>");
            }
            pw.println("</table>");
            pw.println("</center>");
            pw.println("</body>");
            pw.println("</html>");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/myweb/login")
    public void login(String username,String password, HttpServletResponse response) {
        if (username == null || password == null|| username.isEmpty()||password.isEmpty()) {
            try {
                response.sendRedirect("/myweb/login_info_error.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        //2
        File userFile = new File(userDir, username + ".obj");
        if (userFile.exists()) {//用户名输入正确
            try (
                    FileInputStream fis = new FileInputStream(userFile);
                    ObjectInputStream ois = new ObjectInputStream(fis);
            ) {
                //读取该注册用户信息
                User user = (User) ois.readObject();
                if (user.getPassword().equals(password)) {//密码正确
                    //登录成功
                    response.sendRedirect("/myweb/login_success.html");
                    return;
                }
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }

        //如果程序走到这里,情况1:用户名没有输入正确,文件不存在
        //              情况2:用户名对了,但是密码不对
        try {
            response.sendRedirect("/myweb/login_fail.html");
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    /**
     *  传参方式灵活
     *  传参方式1:可以指定HttpServletRequest和HttpServletResponse作为参数
     *
     *  传参方式2:还可以直接将表单传递过来的参数作为作为方法参数定义出来,需要注意的点:
     *  方法中参数名必须和页面上表单中输入框的名字一致(浏览器传递过来的参数名)
     *
     *  传参方式3:直接将一个对象作为参数,需要注意,该对象中属性名应当和表单提交的数据时
     *           对应输入框的名字要一致!
     *           Sprint MVC框架会使用该类的无参构造器实例化,并利用属性对应的set方法
     *           将表单中对应的数据赋值给该属性。之后就可以将该对象传递进方法了。
     *
     */
    @RequestMapping("/myweb/reg")
    //传参方式3
    public void reg(User user,HttpServletResponse response){
        if(user.getUsername()==null||user.getPassword()==null||
           user.getNickname()==null||user.getUsername().isEmpty()||
           user.getPassword().isEmpty()||user.getNickname().isEmpty()){
            try {
                response.sendRedirect("/myweb/reg_info_error.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        File userFile = new File(userDir,user.getUsername()+".obj");
        if(userFile.exists()){//文件存在则说明是重复用户
            try {
                response.sendRedirect("/myweb/have_user.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        try (
                FileOutputStream fos = new FileOutputStream(userFile);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
        ){
            oos.writeObject(user);
            response.sendRedirect("/myweb/reg_success.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //传参方式2
//    public void reg(String username,String password,String nickname,int age,HttpServletResponse response){
//        System.out.println(username+","+password+","+nickname+","+age);
//
//    }

    //传参方式1
//    public void reg(HttpServletRequest request, HttpServletResponse response){
//        String username = request.getParameter("username");
//        String password = request.getParameter("password");
//        String nickname = request.getParameter("nickname");
//        String ageStr = request.getParameter("age");
//        System.out.println(username+","+password+","+nickname+","+ageStr);
//
//        //后期可以使用spring验证框架来完成
//        if(username==null||password==null||nickname==null||ageStr==null||
//                !ageStr.matches("[0-9]+")){
//            try {
//                response.sendRedirect("/myweb/reg_info_error.html");
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            return;
//        }
//        int age = Integer.parseInt(ageStr);
//        User user = new User(username,password,nickname,age);
//    }

}

2.2.2User(实体层)

package com.myboot.myfirstspringboot.entity;//实体

import java.io.Serializable;

/**
 * User的每一个实例用于表示一个注册用户信息
 */
public class User implements Serializable {
    public static final long serialVersionUID = 1L;
    private String username;
    private String password;
    private String nickname;
    private int age;

    public User(){}

    public User(String username, String password, String nickname, int age) {
        this.username = username;
        this.password = password;
        this.nickname = nickname;
        this.age = age;
    }

    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 String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public int getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", nickname='" + nickname + '\'' +
                ", age=" + age +
                '}';
    }
}







2.2.3MyFirstSpringBootApplication(启动类)

package com.myboot.myfirstspringboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MyFirstSpringBootApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyFirstSpringBootApplication.class, args);
    }

}

2.3HTML代码

2.3.1have_user.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>失败</title>
</head>
<body>
  <center>
    <h1>该用户已存在,请<a href="/myweb/reg.html">重新注册</a></h1>
  </center>
</body>
</html>

2.3.2index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>我的首页</title>
</head>
<body>
<!--
     <h1>-<h6>:标题,分为1-6级标题。标题独占一行
     <center>:居中,该标签在HTML5中已经不再建议使用了。没学习样式前临时使用
     <input>:输入组件。它是一套组件,用来在页面上获取用户输入的。

             属性type决定着该组件的样式。
             常见的值有:
                 text:文本框
                 button:按钮
                 checkbox:多选框
                 radio:单选框
                 submit:提交按钮
                 password:密码框
     <a>:超链接,标签中间的文本是超链接对应的文字,属性href用于指定跳转的路径
     <br>:换行
     <table>标签:表格。属性border用于指定边框。
                 <table>标签中包含<tr>标签用于表示行
                 <tr>标签中包含<td>标签用于表示列
                 <td>标签中常见属性:
                 align:对其方式。left左对齐,right右对齐,center剧中对其
                 colspan:跨列合并列,合并是从左向右合并列
                 rowspan:跨行合并列,合并是从上向下合并列

     <img>:图片标签,src属性用于指定图片的路径

     在页面上我们经常会使用路径去定位页面上要使用的额外资源,比如CSS文件,JS文件
     图片文件等。
     例如图片:
     <img src=""> 这里的src就是用于指定图片的路径的
     路径分两种:相对路径和绝对路径
     相对路径常用的:"./",即:当前目录
     在浏览器中和我们在java源代码中"./"位置不是相同的!!!!!!
     原因是页面是被浏览器理解的。

     在页面上"./"的位置浏览器理解的是:URL地址当中抽象路径里的最后一个"/"的位置
     例如:
     请求inde.html时,我们在地址栏上输入的路径为:
     http://localhost:8088/myweb/index.html
     在这个页面上我们使用了<img src="logo.png"> 注:不写"./"默认就是从"./"开始
     此时浏览器判定该图片的实际位置是哪里,就是根据请求当前页面的URL地址决定:
     当前URL地址中抽象路径部分为:/myweb/index.html
     因此"./"理解的就是这里最后一个"/"的位置为:/myweb/
                                               ^
                                            ./的位置

     所以确定了图片的抽象路径部分为:/myweb/logo.png
     因此浏览器实际请求图片的路径为:
     http://localhost:8088/myweb/logo.png


     绝对路径:"/",即:根
     在页面上"/"的位置浏览器理解的是:URL地址当中抽象路径里的第一个"/"的位置
     同样,如果在当前页面上<img src="/myweb/logo.png">
     此时浏览器理解的"/myweb/logo.png"发先路径从"/"开始,即:从根开始。
     请求当前页面路径:http://localhost:8088/myweb/index.html
                                        ^
                                   就是抽象路径的根

     因此该图片实际请求位置:
     http://localhost:8088/myweb/logo.png


     相对路径存在定位不准确情况,常见于服务端转发404时
     例如:请求一个不存在的页面
     http://localhost:8088/myweb/123.html
     服务端发现该页面不存在后,就响应了root目录下的404.html
     而404页面上我们指定图片如果为:<img src="404.png">
     那么浏览器在得到404页面时,理解的404图片实际位置是哪里?
     由于浏览器是请求 http://localhost:8088/myweb/123.html看到的404页面
     因此浏览器会参考该地址中抽象路径部分:/myweb/123.html来分析404图片位置
     由于"./404.png"中的"./"是当前目录,因此浏览器认为该图片的抽象路径应当为:
     "/myweb/404.png"于是请求了:http://localhost:8088/myweb/404.png

     为了定位准确,我们选取绝对路径中的根"/"
     <img src="/root/404.png">



 -->
    <center>
        <!--<h1>百度</h1>-->
        <img src="/myweb/logo.png"><br>
        <input type="text" size="32">
        <input type="button" value="百度一下" onclick="alert('点你妹啊!')">
        <br>
        <a href="/myweb/reg.html">注册</a>
        <a href="/myweb/login.html">登录</a>
        <a href="/myweb/showAllUser">用户列表</a>
        <br>
        <a href="/myweb/writeArticle.html">发表文章</a>
        <br>
        <a href="/myweb/createQR.html">二维码生成器</a>
        <br>
        <a href="http://www.taobao.com">淘宝</a>
        <br>
        <table border="1">
            <tr>
                <td>第一列</td>
                <td>第二列</td>
                <td colspan="2" align="center">第三列</td>
            </tr>
            <tr>
                <td rowspan="2">第一列</td>
                <td>第二列</td>
                <td>第三列</td>
                <td>第四列</td>
            </tr>
            <tr>
                <td>第二列</td>
                <td>第三列</td>
                <td>第四列</td>
            </tr>
        </table>
    </center>

</body>
</html>

2.3.3reg.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户注册</title>
</head>
<body>
    <center>
        <h1>用户注册</h1>
        <!--
            表单组件<form>
            表单用于将用于在页面上输入的信息提交给服务端使用的组件。
            表单上有两个重要的属性:
            action:用于指定表单提交的路径
            method:用于指定表单提交的方式,该方式有两个可选值
                    GET:地址栏形式提交,表单数据会被拼接到URL的抽象路径中
                    POST:打包提交,表单数据会被包含在请求的消息正文中。
                         当表单数据含有用户隐私信息或附件时则需要使用POST形式提交表单。
                    method属性不指定时,默认为GET形式提交表单。
            注意:所有输入组件只有被包含在form表单中并且必须使用name属性为该组件取名字才会被提交!!
                输入组件取的名字可以任意定义,但是不能有中文(英文数字)。

            http://localhost:8088/myweb/reg?username=fancq&password=123456&nickname=chuanqi&age=22
            表单提交后的URL中抽象路径:
            /myweb/reg?username=fancq&password=123456&nickname=chuanqi&age=22

            URL地址中抽象路径部分可以使用"?"分隔为两块,分别是请求部分和参数部分
            请求部分由表单action决定.参数部分由表单中输入框决定
            格式:
            请求部分?输入框1名字=输入框1信息&输入框2名字=输入框2信息&.....
         -->
        <form action="/myweb/reg" method="get">
            <table border="1">
              <tr>
                <td>用户名</td>
                <td><input name="username" type="text"></td>
              </tr>
              <tr>
                <td>密码</td>
                <td><input name="password" type="password"></td>
              </tr>
              <tr>
                <td>昵称</td>
                <td><input name="nickname" type="text"></td>
              </tr>
              <tr>
                <td>年龄</td>
                <td><input name="age" type="text"></td>
              </tr>
              <tr>
                <td colspan="2" align="center">
                  <input type="submit" value="注册">
                </td>
              </tr>
            </table>
        </form>
    </center>
</body>
</html>

2.3.4reg_info_error.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>失败</title>
</head>
<body>
  <center>
    <h1>注册信息输入有误,请<a href="/myweb/reg.html">重新注册</a></h1>
  </center>
</body>
</html>

2.3.5reg_success.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>成功</title>
</head>
<body>
  <center>
    <h1>恭喜您,注册成功了!</h1>
  </center>
</body>
</html>


版权声明:本文为TheNewSystrm原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。