MVC架构中的servlet层重定向404小坑

servlet层中的UserLoginServlet.java

java 复制代码
package com.mhys.servlet; /**
 * ClassName: ${NAME}
 * Description:
 *
 * @Author 数开_11
 * @Create 2024-05-29 20:32
 * @Version 1.0
 */

import com.mhys.pojo.User;
import com.mhys.service.UserService;
import com.mhys.service.impl.UserServiceImpl;

import javax.naming.Name;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.annotation.Repeatable;
import com.mhys.servlet.UserLoginServlet;
@WebServlet(name = "UserLoginServlet",value = "/UserLoginServlet")
public class UserLoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doPost(request,response);
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        String name = request.getParameter("name");
        String pwd = request.getParameter("pwd");
        // 创建userServlet
        UserService service = new UserServiceImpl();
        User user = service.findByNameAndPassword(name, pwd);
        if (user != null) {
            request.getRequestDispatcher("/index.jsp").forward(request, response);
//            response.sendRedirect("/login.jsp");
        } else {
            request.setAttribute("msg", "user/pwd错误哦");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
//            response.sendRedirect("login.jsp");
        }

    }
}

创建servlet映射对应到页面表单的跳转

login.jsp

html 复制代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <style>
        .centered-element{
            margin: 300px auto ;
            width: 200px;
            display: block;
        }
    </style>
    <meta charset="UTF-8" >
    <title>HadoopWebLogin</title>
</head>
<body>
    <form action="/UserLoginServlet" class="centered-element">
<%--        使用外部css来居中这个table--%>
        <table class="centered-element">
<%--            caption标签定义了表格的标题--%>
            <caption>用户登录</caption>
<%--            tr标签表示的时表格的row--%>
            <tr>
<%--                td标签表示的是单元格cell--%>
                <td>账户:</td>
<%--    input标签是一个输入的控件--%>
                <td><input type="text" name="name"></td>
            </tr>
            <tr>
                <td> 密码: </td>
                <td><input type="text" name="pwd"></td>
            </tr>
            <tr>
                <td><input type="submit" value="登录"></td>
                <td><input type="reset" value="重置"></td>
            </tr>
<%--    从request域中拿info--%>
            <tr>
                <td colspan="2"><span style="color: red;">${msg}</span></td>
            </tr>
        </table>
    </form>

</body>
</html>

submit之后去找servlet层中的UserLoginServlet.java 进行逻辑判断---> 重定向操作

注!: 这里必须要在web.xml中配置上**!!!!!(我是在这里犯错了,U小写了,找了半天没看出了,笑晕)**

XML 复制代码
   <servlet>    
        <servlet-name>UserLoginServlet</servlet-name>
        <servlet-class>com.mhys.servlet.UserLoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>UserLoginServlet</servlet-name>
        <url-pattern>/UserLoginServlet</url-pattern>
    </servlet-mapping>
复制代码

这里的webservlet中的路径是严格区分大小写的,写错小个小点都会在登录时重定向报404找不到资源!!!!

另一个注意点:就是创建对象获取数据库中的user/pwd时new 数据类型是UserService 父类

不要是接口的实现类

utils 层中的JDBCUtils.java

java 复制代码
package com.mhys.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

/**
 * ClassName: JdbcUtils
 * Description:
 *
 * @Author 数开_11
 * @Create 2024-05-29 17:46
 * @Version 1.0
 */
public class JdbcUtils {
    public static Connection getConnection() throws Exception{
        Connection connection=null;
        try{
            //1-读取db.properties文件
            Properties properties=new Properties();
            InputStream in=JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
            properties.load(in);

            //2-读取属性
            String driver=properties.getProperty("driver");
            String url=properties.getProperty("url");
            String username=properties.getProperty("username");
            String password=properties.getProperty("password");

            //3-注册驱动
            Class.forName(driver);

            //4-获取连接
            connection= DriverManager.getConnection(url,username,password);

            //5-日志打印连接信息
            System.out.println("连接信息: " + url + " " + username + " " + password);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("数据库连接失败,请检查连接参数是否正确!");
        }
        return connection;
    }
}

和项目的资源目录下配置db.properties文件

复制代码
内容:
java 复制代码
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:33306/javaweb?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
username=root
password=root
相关推荐
EFCY1MJ903 分钟前
ASP.NET MVC 1.0 (五) ViewEngine 深入解析与应用实例
后端·asp.net·mvc
深念Y5 分钟前
从张量到微分方程:AI计算架构的底层思考笔记
深度学习·架构·张量·npu·计算机架构·ai芯片·计算范式
小江的记录本9 分钟前
【RabbitMQ】RabbitMQ核心知识体系全解(5大核心模块:Exchange类型、消息确认机制、死信队列、延迟队列、镜像队列)
java·前端·分布式·后端·spring·rabbitmq·mvc
小江的记录本28 分钟前
【RocketMQ】RocketMQ核心知识体系全解(5大核心模块:架构模型、事务消息两阶段提交、回查机制、延迟消息、顺序消息)
linux·运维·服务器·前端·后端·架构·rocketmq
心.c29 分钟前
嵌入式 AI 助手的三层意图识别架构:如何在“快、准、稳“之间取得平衡
人工智能·ai·架构
AI自动化工坊31 分钟前
HiClaw多Agent协同实战:基于Matrix协议的透明化AI团队架构
人工智能·ai·架构·agent·matrix·hiclaw
William_cl33 分钟前
[特殊字符]C# ASP.NET 架构封神之路:分层 + 仓储 + EFCore,写出企业级可维护代码!
架构·c#·asp.net
三更两点35 分钟前
[特殊字符] 智能代理AI架构(生产就绪系统)
人工智能·架构
chenglin01636 分钟前
多模型协同与智能体(Agent)架构
架构
无忧智库37 分钟前
从“数据孤岛”到“数智飞轮”:解码浙江移动“5141”企业级数据治理体系的顶层架构与实战逻辑(PPT)
架构