servlet 的一些相关问题

上代码:

项目名字/webroot/html/index.html

<form action="../login" method="post">
                    <img src="../images/headpic.png"/><input style="border-radius: 15px; margin-left: 10px;" placeholder="请输入用户名" name="username" id="uname"/><br><br>
                    <img src="../images/passwdpic.png"/><input style="border-radius: 15px;margin-left: 10px;" placeholder="请输入密码" name="password" id="passwd"/><br><br>
                    <button style="width:100px; border: 1px solid #000;border-radius: 12px;background: #0080ff;" name="login" method="post">立即登录</button><br><br>
                    <a class="astyle">忘记密码?</a><a style="margin-left: 35px;" class="astyle">会员注册</a>
                </form>

项目名字/包名/LoginServlet.java

public class LoginServlet extends HttpServlet{

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        Dao dao = Factory.createMysqlDao();
        User user = dao.select(username);
        
        PrintWriter printWriter = resp.getWriter();
        if (username.equals(user.getUsername()) && password.equals(user.getPassword())) {
            System.out.println("登录成功");
            printWriter.print("<div style='color:green'>success</div>");
        }else {
            System.out.println("登录失败");
            printWriter.print("<div style='color:green'>fail</div>");
        }
    }
}

项目名字/webroot/WEB-INF/web.xml             ps:web.xml由自己创建

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>com.fengwuj.Servlet.LoginServlet</servlet-class>
    </servlet>
 
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>
</web-app>

全都是代码,那么......我要说什么?

我说的都是遇到的坑......

1、首先先了解servlet的运行逻辑,index.html通过form的action指定需要拦截的url,然后在<servlet-mapping>---<url-pattern>中寻找到指明的url,再通过<url-pattern>中的Url找到mapping中的 <servlet-name>​​​​​​​,通过mapping中的 <servlet-name>的名字找到 <servlet>中的name,最后找到下方的class---Servlet类进行数据处理;

2、怎么配?首先需要保证web.xml与要代理的html路径的统一,普通的html文件,如果直接建立在WebRoot目录下(webroot--xxx.html),就直接配置就行了,在action中任意取个名字,mapping中的url名字保证一致;如果像我一样多建立了一个文件夹即WebRoot--文件夹--xxx.html,则需要配置../name,  ../表示上层目录。

3、如果你配好了,那么恭喜你,你将遇到405的报错,我网上查了一下资料,原因有两个一个是form表单中的methord方法不应该使用post而是get,但是我这边好像使用post也没有问题,此题不明,还有就是,删掉Servlet类中的super(request,respose)方法,doPost(),doGet(),service()中,用哪个方法就删哪个的super();

4、如果你看完了,那么恭喜你,放飞自我吧!!!

发布了46 篇原创文章 · 获赞 3 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/fengwuJ/article/details/81124196
今日推荐