简单使用 SpringMVC 框架实现传统 Servlet 相似的操作(注解开发)

SpringMVC 可以使用注解进行开发,也可以使用配置文件进行开发,但是使用配置文件还是比较麻烦的,我们这里仅仅做一个 Servlet 控制输出的案例。

IDEA简单使用SpringMVC框架实现简单的Servlet操作(配置文件版本)https://blog.csdn.net/kid_0_kid/article/details/120385068

我们下面就开始使用注解进行完整的开发了。

目录

搭建环境

数据库

创建 Maven 工程

配置项目

添加依赖代码

配置 MyBatis

配置 SpringMVC

编写项目

创建包结构

编写后端代码

dao 包

pojo 包

service 包

controller 包

编写前端代码

登录页面

注册页面

查看个人信息

查看所有学生信息

修改学生信息的页面

配置Tomcat

出现的问题

页面出现404

乱码问题

类中没有getter方法


我们下面就开始使用注解进行完整的开发了。

搭建环境

数据库

我们这里使用的是 MySQL 数据库。新建名为 task 的数据库,在 task 数据库中新建名为 student 的数据表。在表中适当添加数据。创建表和添加数据的 SQL 语句如下所示。

SET FOREIGN_KEY_CHECKS=0;
--创建表
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `sid` varchar(40) NOT NULL DEFAULT '' COMMENT 'UUID,唯一标识',
  `id` int(10) DEFAULT NULL COMMENT '学生编号',
  `name` varchar(20) DEFAULT NULL COMMENT '学生姓名',
  `password` varchar(20) DEFAULT NULL COMMENT '学生密码',
  `age` int(3) unsigned DEFAULT NULL COMMENT '学生年龄',
  `sex` varchar(2) DEFAULT NULL COMMENT '学生性别',
  PRIMARY KEY (`sid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 
--在表中添加数据
INSERT INTO `student` VALUES ('9577f4badff2443e9e67bcc63b640341', '1005', 'KID', '12345', '20', '女');
INSERT INTO `student` VALUES ('9577f4badff2443e9e67bcc63b640342', '1001', '张三', '1235', '12', '女');
INSERT INTO `student` VALUES ('c93bbe3c69ed4cbeb07a2a06ccb97612', '1002', '李四', '1235', '30', '男');
INSERT INTO `student` VALUES ('db7d44de97e1418d95fd73a77b9a9b0c', '1003', '王五', '1235', '12', '女');
INSERT INTO `student` VALUES ('fjakslfk349rhrksar4', '1004', '赵六', '1235', '25', '男');

数据库创建成功的效果图。

创建 Maven 工程

使用IDEA创建Maven项目,选择自己需要的JDK版本,进入下一步。我们这里推荐使用1.8版本的 JDK。

填写项目的名称和项目的存放地址,点击 Finish 即可完成 Mavne 项目的创建。

 添加框架支持。需要将普通的 Maven 工程升级为 Web 工程。右键点击模块。选择 Add Framework Support 进行添加 web 框架。

选择 Web Application 点击 OK ,即可添加 Web 框架支持。

配置项目

添加依赖代码

我们需要在 pom.xml 配置文件中添加依赖代码。我们需要引入 Juint、Spring MVC、Servlet、Jsp、MyBatis、JDBC、JSTL 等框架的依赖。

    <dependencies>

        <!--引入 Juint 单元测试的框架依赖-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <!--引入 SpringMVC(Spring Web MVC) 的框架依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>

        <!--引入 Servlet 框架依赖-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>

        <!--引入 JSP 框架依赖-->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>

        <!--引入 JSTL 标签库的框架依赖-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!--引入 MySQL 数据库的 JDBC 依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.26</version>
        </dependency>

        <!--引入 Mybatis 框架依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>

    </dependencies>


    <!--在build中配置 resources ,来防止资源导出失败的问题-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

配置 MyBatis

接下来我们通过 MyBatis 框架来连接 MySQL 数据库。我们先添加文件名为 mybatis-config.xml 的 MyBatis 的配置文件。我们需要在 resources 包下创建一个名为 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>

    <!--引入外部配置文件-->
    <properties resource="config.properties"/>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/kid/service/StudentServiceImpl.xml"/>
    </mappers>
</configuration>

接下来我们需要在 resources 包下创建一个 config.properties 资源文件,用来存放连接数据库的信息。

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/task?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username=root
password=

配置 SpringMVC

 我们需要在 web.xml 配置文件中,注册 SpringMVC 的 DispatcherServlet,即视图解析器。DispatcherServlet 本质上还是一个 Servlet。添加代码后可能会出现爆红,是因为我们没有创建 springmvc-servlet.xml 配置文件,这里先不需要处理爆红错误,我们后续会进行创建的对应的配置文件的。

    <!--1.注册servlet-->
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--通过初始化参数指定SpringMVC配置文件的位置,进行关联-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <!-- 启动顺序,数字越小,启动越早 -->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!--所有请求都会被springmvc拦截 -->
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

我们在 resources 包下创建 springmvc-servlet.xml 配置文件。自动扫描包即,自动扫描指定路径下的所有注解。视图解析器即,只需要提供文件名称,通过类似于字符串拼接的方式,拼接出来完整的路径信息。添加代码后可能会出现爆红,这是因为找不到 com.kid.controller 路径,我们还是后续会处理的。

<?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:context="http://www.springframework.org/schema/context"
       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
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 自动扫描包,让指定包下的注解生效,由IOC容器统一管理 -->
    <context:component-scan base-package="com.kid.controller"/>
    <!-- 让Spring MVC不处理静态资源 -->
    <mvc:default-servlet-handler/>
    <!--
    支持mvc注解驱动
        在spring中一般采用@RequestMapping注解来完成映射关系
        要想使@RequestMapping注解生效
        必须向上下文中注册DefaultAnnotationHandlerMapping
        和一个AnnotationMethodHandlerAdapter实例
        这两个实例分别在类级别和方法级别处理。
        而annotation-driven配置帮助我们自动完成上述两个实例的注入。
     -->
    <mvc:annotation-driven/>

    <!-- 视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          id="internalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!-- 后缀 -->
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

编写项目

创建包结构

我们按照 MVC 规范进行创建包结构。在 Java 包下创建 com 包,在 com 包中创建 kid 包,在 kid 包中创建 controller、dao、pojo、service 四个后端的包存放 Java 代码。其中,dao包中存放的是数据库的工具类;service 包中存放的是实际可能需要的业务,比如说学生登录、删除学生等;controller 包中存放的是控制类,用来接受 jsp 页面传过来的值,调用 service 包中的业务;pojo 包中存放的是可能用到的对象实体类。还需要在 WEB-INF 包下创建一个 jsp 包用来存放前端页面。

编写后端代码

dao 包

dao 包中存放的是数据库访问对象,用于连接数据库、对数据库进行操作。我们在 dao 包中创建一个 MyBatisUtil 类。

package com.kid.dao;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtil {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession() {
        //修改数据库中的数据(增删改)必须提交事务,否则数据不会保存到数据库
        //openSession(true)中的参数,true自动提交事务
        return sqlSessionFactory.openSession(true);
    }

}

pojo 包

pojo 包中存放的是用到的实体类。这里我们需要创建两个实体类,Student 类和 StudentLogin 类。其中,Student 类是完整的学生类;StudentLogin 类是学生登录时使用的类,只是保存了学生的部分信息。

Student 类中的代码。

package com.kid.pojo;

public class Student {
    private String sid;//UUID,唯一标识
    private int id;//学生编号
    private String name;//学生姓名
    private String password;//登录密码
    private int age;//年龄
    private String sex;//性别

    public Student(String sid, int id, String name, String password, int age, String sex) {
        this.sid = sid;
        this.id = id;
        this.name = name;
        this.password = password;
        this.age = age;
        this.sex = sex;
    }

    public String getSid() {
        return sid;
    }

    public void setSid(String sid) {
        this.sid = sid;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

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

    public int getAge() {
        return age;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "Student{" +
                "sid='" + sid + '\'' +
                ", id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                '}';
    }
}

StudentLogin 类中的代码。

package com.kid.pojo;

public class StudentLogin {
    private String sid;//UUID,唯一标识
    private int id;//学生编号
    private String password;//登录密码

    public StudentLogin() {
    }

    public StudentLogin(String sid, String password) {
        this.sid = sid;
        this.password = password;
    }

    public StudentLogin(int id, String password) {
        this.id = id;
        this.password = password;
    }

    public StudentLogin(String sid, int id, String password) {
        new StudentLogin(sid, password);
        this.id = id;
    }

    public String getSid() {
        return sid;
    }

    public void setSid(String sid) {
        this.sid = sid;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getPassword() {
        return password;
    }

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

    @Override
    public String toString() {
        return "StudentLogin{" +
                "sid='" + sid + '\'' +
                ", id=" + id +
                ", password='" + password + '\'' +
                '}';
    }
}

service 包

service 包中存放的是实际所有的业务。我们这里使用 MyBatis 框架,需要先创建一个 StudentService 接口类,里面定义了业务相关的所有方法;需要在创建一个 StudentServiceImpl 配置文件,用来对 StudentService 接口进行映射。

StudentService 接口类中的代码。

package com.kid.service;

import com.kid.pojo.Student;
import com.kid.pojo.StudentLogin;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface StudentService {

    //增加学生
    int insertStudent(@Param("student") Student student);

    //删除学生
    int deleteStudentBySid(@Param("sid") String sid);

    int deleteStudentById(@Param("id") int id);

    int deleteStudentByName(@Param("name") String name);

    int deleteStudentByAge(@Param("age") int age);

    int deleteStudentBySex(@Param("sex") String sex);

    //修改学生信息
    int updateStudent(@Param("student") Student student);

    //查找学生
    List<Student> getStudentAll();

    List<Student> getStudentBySid(@Param("sid") String sid);

    List<Student> getStudentById(@Param("id") int id);

    List<Student> getStudentByName(@Param("name") String name);

    List<Student> getStudentByAge(@Param("age") int age);

    List<Student> getStudentBySex(@Param("sex") String sex);

    //学生登录
    Student studentLogin(@Param("studentLogin") StudentLogin studentLogin);

}

StudentServiceImpl 配置文件中的代码。

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kid.service.StudentService">

    <!--添加学生信息-->
    <insert id="insertStudent" parameterType="com.kid.pojo.Student">
        insert into task.student (sid, id, name, password, age, sex)
        values (#{student.sid}, #{student.id}, #{student.name}, #{student.password}, #{student.age}, #{student.sex})
    </insert>

    <!--删除学生信息-->
    <!--根据Sid删除学生-->
    <delete id="deleteStudentBySid" parameterType="String">
        delete
        from task.student
        where sid = #{sid}
    </delete>
    <!--根据id删除学生-->
    <delete id="deleteStudentById" parameterType="int">
        delete
        from task.student
        where id = #{id}
    </delete>
    <!--根据name删除学生-->
    <delete id="deleteStudentByName" parameterType="String">
        delete
        from task.student
        where name = #{name}
    </delete>
    <!--根据age删除学生-->
    <delete id="deleteStudentByAge" parameterType="int">
        delete
        from task.student
        where age = #{age}
    </delete>
    <!--根据sex删除学生-->
    <delete id="deleteStudentBySex" parameterType="String">
        delete
        from task.student
        where sex = #{sex}
    </delete>

    <!--修改学生信息-->
    <update id="updateStudent" parameterType="com.kid.pojo.Student">
        update task.student
        set sid      = #{student.sid},
            id       = #{student.id},
            name     = #{student.name},
            password = #{student.password},
            age      = #{student.age},
            sex      = #{student.sex}
        where sid = #{student.sid};
    </update>

    <!--查找学生信息-->
    <!--查找所有学生-->
    <select id="getStudentAll" resultType="com.kid.pojo.Student">
        select *
        from task.student
    </select>
    <!--根据sid查找学生-->
    <select id="getStudentBySid" parameterType="String" resultType="com.kid.pojo.Student">
        select *
        from task.student
        where sid = #{sid}
    </select>
    <!--根据id查找学生-->
    <select id="getStudentById" parameterType="int" resultType="com.kid.pojo.Student">
        select *
        from task.student
        where id = #{id}
    </select>
    <!--根据name查找学生-->
    <select id="getStudentByName" parameterType="String" resultType="com.kid.pojo.Student">
        select *
        from task.student
        where name = #{name}
    </select>
    <!--根据age查找学生-->
    <select id="getStudentByAge" parameterType="int" resultType="com.kid.pojo.Student">
        select *
        from task.student
        where age = #{age}
    </select>
    <!--根据sex查找学生-->
    <select id="getStudentBySex" parameterType="String" resultType="com.kid.pojo.Student">
        select *
        from task.student
        where sex = #{sex}
    </select>

    <select id="studentLogin" parameterType="com.kid.pojo.StudentLogin" resultType="com.kid.pojo.Student">
        select *
        from task.student
        where (id = #{studentLogin.id} and password = #{studentLogin.password})
           or (sid = #{studentLogin.sid} and password = #{studentLogin.password})
    </select>

</mapper>

controller 包

controller 包中存放的就是控制类,接收前端页面传送过来的值,通过调用 service 包中的方法,对值进行处理,然后再指定到前端页面。我们需要再 controller 包中创建一个 StudentController 类。这里可能会爆红,是因为我们没有创建前端页面,我们下面就会创建对应的前端页面了。

package com.kid.controller;

import com.kid.dao.MyBatisUtil;
import com.kid.pojo.Student;
import com.kid.pojo.StudentLogin;
import com.kid.service.StudentService;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.UUID;

// 该类被Spring接管,类中所有方法的返回值都为 String 类型
// 类中的每个方法都会被视图解析器进行解析
@Controller
public class StudentController {

    //学生登录
    //路径为:/login
    @RequestMapping("/login")
    public String login(Model model) {
        //获取request对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //接收值
        String sidORId = request.getParameter("SidORId");
        String password = request.getParameter("password");

        SqlSession session = MyBatisUtil.getSqlSession();
        StudentService studentService = session.getMapper(StudentService.class);

        //根据Sid查找学生
        Student student = studentService.studentLogin(new StudentLogin(sidORId, password));

        //Sid查找失败
        if (student == null) {
            try {
                //尝试将字符串转换为整形数字,再次进行查找
                int id = Integer.parseInt(sidORId);
                student = studentService.studentLogin(new StudentLogin(id, password));
            } catch (Exception e) {
                //字符串转整形失败
                model.addAttribute("msg", "账号或密码错误!请重新尝试登录!");
            }
        }
        session.close();

        //学生登录成功
        if (student != null) {
            model.addAttribute("flag", true);
            model.addAttribute("msg", "登录成功!");
            model.addAttribute("student", student);
        } else {
            model.addAttribute("flag", false);
            model.addAttribute("msg", "登录失败!");
        }

        return "hello";
    }

    //查看所有学生信息
    //路径为:lookupAll
    @RequestMapping("/lookupAll")
    public String lookupAll(Model model) {
        SqlSession session = MyBatisUtil.getSqlSession();
        StudentService studentService = session.getMapper(StudentService.class);
        List<Student> list = studentService.getStudentAll();
        session.close();

        model.addAttribute("list", list);

        return "lookupAll";
    }

    //根据 Sid 删除学生信息
    //路径为:deleteStudent
    @RequestMapping("/deleteStudent")
    public String deleteStudent(Model model) {
        int flag = 0;//标记是否删除成功
        //获取request对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //接收值
        String sid = request.getParameter("sid");
        
        SqlSession session = MyBatisUtil.getSqlSession();
        StudentService studentService = session.getMapper(StudentService.class);

        flag = studentService.deleteStudentBySid(sid);

        if (flag > 0) {
            model.addAttribute("delete", "删除成功!");
        } else {
            model.addAttribute("delete", "删除失败!");
        }

        //删除成功后,再查找一遍所有学生
        List<Student> list = studentService.getStudentAll();

        session.close();

        model.addAttribute("list", list);

        return "lookupAll";
    }

    //更新学生信息
    //路径为:updateStudent
    @RequestMapping("/updateStudent")
    public String updateStudent(Model model) throws UnsupportedEncodingException {
        int flag = 0;//是否修改成功
        //获取request对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        request.setCharacterEncoding("utf-8");//解决乱码问题

        //接收值
        String sid = request.getParameter("sid");
        int id = Integer.parseInt(request.getParameter("id"));
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        int age = Integer.parseInt(request.getParameter("age"));
        String sex = request.getParameter("sex");
        Student student = new Student(sid, id, name, password, age, sex);

        SqlSession session = MyBatisUtil.getSqlSession();
        StudentService studentService = session.getMapper(StudentService.class);
        flag = studentService.updateStudent(student);

        if (flag > 0) {
            model.addAttribute("delete", "修改成功!");
        } else {
            model.addAttribute("delete", "修改失败!");
        }

        List<Student> list = studentService.getStudentAll();

        session.close();

        model.addAttribute("list", list);

        return "lookupAll";
    }

    //根据Sid查找学生信息
    //路径为:/lookupOne
    @RequestMapping("/lookupOne")
    public String lookupOne(Model model) {
        //获取request对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //接收值
        String sid = request.getParameter("sid");

        Student student = null;
        SqlSession session = MyBatisUtil.getSqlSession();
        StudentService studentService = session.getMapper(StudentService.class);
        student = studentService.getStudentBySid(sid).get(0);

        model.addAttribute("student", student);

        return "updateStudent";
    }

    //注册学生信息
    //路径:/logon
    @RequestMapping("logon")
    public String logonStudent(Model model) throws UnsupportedEncodingException {
        int flag = 0;//是否修改成功
        //获取request对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        request.setCharacterEncoding("utf-8");//解决乱码问题
        //接收值
        String sid = UUID.randomUUID().toString().replace("-", "");//SID使用UUID创建,然后使用""替换掉UUID中的"-"
        int id = Integer.parseInt(request.getParameter("id"));
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        int age = Integer.parseInt(request.getParameter("age"));
        String sex = request.getParameter("sex");
        Student student = new Student(sid, id, name, password, age, sex);

        SqlSession session = MyBatisUtil.getSqlSession();
        StudentService studentService = session.getMapper(StudentService.class);
        flag = studentService.insertStudent(student);
        session.close();
        if (flag > 0) {
            model.addAttribute("msg", "注册成功!");
            model.addAttribute("flag", true);
            model.addAttribute("student", student);
        } else {
            model.addAttribute("msg", "注册失败!");
            model.addAttribute("flag", false);
        }

        return "hello";
    }


}

编写前端代码

登录页面

首先,我们需要在 index.jsp 页面中添加登录页面的内容。

<%--
  Created by IntelliJ IDEA.
  User: 24484
  Date: 2021/9/20
  Time: 20:19
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>登录</title>
</head>
<body>
<table border="1">
  <form action="/login" method="post">
    <tr align="center">
      <td>账号:</td>
      <td>
        <input type="text" name="SidORId" placeholder="输入学生编号或唯一标识">
      </td>
    </tr>
    <tr align="center">
      <td>密码:</td>
      <td>
        <input type="password" name="password" placeholder="请输入密码">
      </td>
    </tr>
    <tr align="center">
      <td colspan="2">
        <table border="1">
          <tr align="center">
            <td width="30%">
              <input type="reset" value="清除">
            </td>
            <td width="30%">
              <input type="submit" value="登录">
            </td>
          </tr>
        </table>
      </td>
  </form>
</table>
<form action="logon.jsp" method="post">
  <input type="submit" value="注册"/>
</form>

</body>
</html>

注册页面

我们还需要在 web 包下创建 logon.jsp 注册页面。下面代码为 logon.jsp 页面的代码。

<%--
  Created by IntelliJ IDEA.
  User: 24484
  Date: 2021/9/21
  Time: 19:39
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>注册</title>
</head>
<body>
<form action="/logon" method="post">
    <table>
        <tr>
            <th>ID</th>
            <td>
                <input type="text" name="id">
            </td>
        </tr>
        <tr>
            <th>Name</th>
            <td>
                <input type="text" name="name">
            </td>
        </tr>
        <tr>
            <th>Password</th>
            <td>
                <input type="text" name="password">
            </td>
        </tr>
        <tr>
            <th>Age</th>
            <td>
                <input type="text" name="age">
            </td>
        </tr>
        <tr>
            <th>Sex</th>
            <td>
                <input type="text" name="sex">
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <table>
                    <tr>
                        <td>
                            <input type="reset" value="清除">
                        </td>
                        <td>
                            <input type="submit" value="注册">
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</form>
</body>
</html>

查看个人信息

我们需要在 jsp 包中创建 hello.jsp 页面,用来显示用户登录后的个人信息。

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: 24484
  Date: 2021/9/20
  Time: 20:50
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>${msg}</title>
</head>
<body>
${msg}
<br/>
<c:choose>
    <c:when test="${flag==true}">
        <table border="1">
            <caption>${student.name}的个人信息</caption>
            <tr align="center">
                <td>SID</td>
                <td>${student.sid}</td>
            </tr>
            <tr align="center">
                <td>ID</td>
                <td>${student.id}</td>
            </tr>
            <tr align="center">
                <td>Name</td>
                <td>${student.name}</td>
            </tr>
            <tr align="center">
                <td>Password</td>
                <td>${student.password}</td>
            </tr>
            <tr align="center">
                <td>Age</td>
                <td>${student.age}</td>
            </tr>
            <tr align="center">
                <td>Sex</td>
                <td>${student.sex}</td>
            </tr>
        </table>
        <a href="/lookupAll">查看所有人的信息</a>
    </c:when>

    <%--登录失败--%>
    <c:otherwise>
        <a href="index.jsp">点击重新登录</a>
    </c:otherwise>
</c:choose>
</body>
</html>

查看所有学生信息

需要在 jsp 包下创建 lookupAll.jsp 页面,用来显示全部学生的信息。

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: 24484
  Date: 2021/9/21
  Time: 18:02
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>所有信息</title>
</head>
<body>
${delete}
<br/>

<table border="1">

    <caption>所有学生的信息</caption>

    <tr>
        <th>SID</th>
        <th>ID</th>
        <th>Name</th>
        <th>Age</th>
        <th>Sex</th>
        <th colspan="2">Action</th>
    </tr>

    <c:forEach items="${list}" var="student">
        <tr align="center">
            <td>${student.sid}</td>
            <td>${student.id}</td>
            <td>${student.name}</td>
            <td>${student.age}</td>
            <td>${student.sex}</td>
            <td>
                <form action="/lookupOne" method="post">
                    <input type="hidden" value="${student.sid}" name="sid"/>
                    <input type="submit" value="修改"/>
                </form>
            </td>
            <td>
                <form action="/deleteStudent" method="post">
                    <input type="hidden" value="${student.sid}" name="sid">
                    <input type="submit" value="删除">
                </form>
            </td>
        </tr>
    </c:forEach>

    <br/>
    <form action="logon.jsp" method="post">
        <input type="submit" value="注册"/>
    </form>
</table>
</body>
</html>

修改学生信息的页面

需要在 jsp 包下创建 updateStudent.jsp 页面,用来显示修改学生信息的页面。

<%--
  Created by IntelliJ IDEA.
  User: 24484
  Date: 2021/9/21
  Time: 18:45
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>更新个人信息</title>
</head>
<body>
这里是更新页面,需要输入更新的数据
<form action="/updateStudent" method="post">
    <table>
        <caption>更新学生信息</caption>
        <tr align="center">
            <td>ID</td>
            <td>
                <input type="hidden" name="sid" value="${student.sid}"/>
                <input type="text" name="id" placeholder="${student.id}" value="${student.id}"/>
            </td>
        </tr>
        <tr align="center">
            <td>Name</td>
            <td>
                <input type="text" name="name" placeholder="${student.name}" value="${student.name}"/>
            </td>
        </tr>
        <tr align="center">
            <td>password</td>
            <td>
                <input type="text" name="password" placeholder="${student.password}" value="${student.password}"/>
            </td>
        </tr>
        <tr align="center">
            <td>Age</td>
            <td>
                <input type="text" name="age" placeholder="${student.age}" value="${student.age}"/>
            </td>
        </tr>
        <tr align="center">
            <td>Sex</td>
            <td>
                <input type="text" name="sex" placeholder="${student.sex}" value="${student.sex}"/>
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <table>
                    <tr>
                        <td>
                            <input type="reset" value="清除">
                        </td>
                        <td>
                            <input type="submit" value="修改">
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</form>
</body>
</html>

配置Tomcat

点击右上角的 Add Configuration,添加 Tomcat 的配置。

先点击左上角的+号,选择 Tomcat Server 中的 Local 版本。

如果项目配置没有问题,点击右下角的 Fix 即可完成配置。

需要删除 Application context 中的内容,点击 OK 即可完成 Tomcat 的配置。

Tomcat 配置好了,就可以运行项目了。

出现的问题

页面出现404

可能是资源导入错误,需要手动导入资源。

 选择左边的 Artifacts,在中间选择自己的项目,在右边WEB-INF包下创建 lib 包。

选择在创建好的lib包,点击 + 号,准备添加资源。

我们这里选择添加 Library Files 资源。

选中所有的资源,点击 OK,即可。

乱码问题

乱码问题比较复杂,可以通过 request 对象设置字符集的方法,解决乱码问题。如果还是出现乱码,可以一步一步分析,查看乱码是在什么地方产生的,然后在对应的地方修改字符集即可解决。

httpServletRequest.setCharacterEncoding("UTF-8");

类中没有getter方法

在页面中可能会提示找不到 getter 方法,但是我们这里写的都是标准的JavaBean,所有的类中都包含了 getter 方法和 setter 方法,所以应该是配置文件读取不到我们的 getter 方法 。我们可以给所有的接口添加 @Param("参数名") 注解,即可解决该问题。

注意,我们在创建该项目的时候,已经给所有的接口添加了 @Param("参数名") 注解。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值