404错误,请老师帮忙看看

404错误,请老师帮忙看看

http://img1.sycdn.imooc.com//climg/5f50a48309c2952a12830432.jpghttp://img1.sycdn.imooc.com//climg/5f50a5430984e42e13251004.jpg

catalogbiz

package com.andreas.cake.biz;

import com.andreas.cake.entity.Catalog;

import java.util.List;

public interface CatalogBiz {
    void add(List<Catalog> list);

    void remove(int id);

    Catalog getRoot();

}

catalogbizimpl

package com.andreas.cake.biz.impl;

import com.andreas.cake.biz.CatalogBiz;
import com.andreas.cake.dao.CatalogDao;
import com.andreas.cake.entity.Catalog;
import com.andreas.cake.global.DaoFactory;

import java.util.List;

public class CatalogBizImpl implements CatalogBiz {

    //声明成员变量,catalogDao 其由dao工厂取出
    private CatalogDao catalogDao = DaoFactory.getInstance().getDao(CatalogDao.class);

    public void add(List<Catalog> list) {
        catalogDao.BatchInsert(list);
    }

    public void remove(int id) {
        catalogDao.BatchDelete(id);
    }

    public Catalog getRoot() {
        return catalogDao.select(10000);
        //此处插入的10000是业务规则,已经在数据库内给定了最根节点的组件
    }
}

catalogController

package com.andreas.cake.controller;

import com.andreas.cake.biz.CatalogBiz;
import com.andreas.cake.biz.impl.CatalogBizImpl;
import com.andreas.cake.entity.Catalog;
import com.sun.deploy.net.HttpRequest;
import com.sun.deploy.net.HttpResponse;
import org.apache.ibatis.datasource.pooled.PooledDataSource;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class CatalogController {
    //声明业务处理对象
    private CatalogBiz catalogBiz = new CatalogBizImpl();

    //用户打开界面显示所有商品的方法list.do
    public void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//由于分类是一个树状结构,拿到了根节点root就相当于拿到了所有节点
        Catalog root = catalogBiz.getRoot();
        request.setAttribute("root", root);
        request.getRequestDispatcher("/WEB-INF/pages/admin/catalog_list.jsp").forward(request, response);
    }

    //用户打开添加界面的方法toAdd.do
    public void toAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Catalog root = catalogBiz.getRoot();
        request.setAttribute("root", root);
        request.getRequestDispatcher("/WEB-INF/pages/admin/catalog_add.jsp").forward(request, response);
    }

    //用户在提交添加数据后执行的方法Add.do
    public void Add(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String[] titles = request.getParameterValues("title");
        String[] pids = request.getParameterValues("pid");
        String[] infos = request.getParameterValues("info");
        List<Catalog> catalogs = new ArrayList<Catalog>();
        for (int i = 0; i <= titles.length; i++) {
            Catalog catalog = new Catalog();
            catalog.setTitle(titles[i]);
            catalog.setInfo(infos[i]);
            catalog.setPid((Integer.parseInt(pids[i])));
            catalogs.add(catalog);
        }
        catalogBiz.add(catalogs);
        response.sendRedirect("list.do");//同目录下可使用相对路径
    }

    //用户删除商品的方法remove.do
    public void Remove(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        catalogBiz.remove(id);
        response.sendRedirect("list.do");//同目录下可使用相对路径
    }

}

catalogDao

package com.andreas.cake.dao;

import com.andreas.cake.entity.Catalog;
import com.sun.xml.internal.bind.v2.model.core.ID;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface CatalogDao {
    //使用注解开发sql,动态sql可以使用插入脚本方式解决
    @Insert("<script> " +
            "insert into catalog(title,pid,info) values" +
            "<foreach collection='list' item='catalog' separator=','>" +
            "(#{catalog.title},#{catalog.pid},#{catalog.info})" +
            "</foreach>" +
            "</script")
    //配置数据库自增属性
    @Options(useGeneratedKeys = true, keyProperty = "id")
    //批量插入方法
    void BatchInsert(List<Catalog> list);

    @Delete("delete from catalog where id = #{id}")
    //批量删除的方法
    void BatchDelete(int id);

    //批量查询的方法
    @Select("select * from catalog where id=#{id}")
    Catalog select(int id);

    @Results(id = "all",value = {
            @Result(column = "id", property = "id", id = true),
            @Result(column = "title", property = "title"),
            @Result(column = "pid",property = "pid"),
            @Result(column = "info",property = "info"),
            //将此分类下的所有子类查询出来交给此属性
            @Result(column = "id",property = "children",many = @Many(select = "SelectByPid"))
    })
    @Select("select * from catalog where pid=#{pid}")
    @ResultMap("all")//直接他用过id all 调用value
    List<Catalog> SelectByPid(int pid);
}

Daofactory

package com.andreas.cake.global;

import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

public class DaoFactory {
    //工具类使用单例模式封装
    private static DaoFactory daoFactory;
    SqlSessionFactory sqlSessionFactory;
    //构造方法私有
    private DaoFactory(){
        try {
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            sqlSessionFactory = sqlSessionFactoryBuilder.build(Resources.getResourceAsReader("/mybatis.xml"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //提供公有的静态反回对象的方法
    public static DaoFactory getInstance() {
        if (daoFactory == null) {
            daoFactory = new DaoFactory();
        }
        return daoFactory;
    }

    public <T> T getDao(Class<T> tClass) {
//        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(Resources.getResourceAsReader("/mybatis.xml"));
       //由于只需要执行一次,所以可以放在上面的单例构造方法中,只执行一次,提高代码效率
        return sqlSessionFactory.openSession(true).getMapper(tClass);//自动提交事物
    }
}

encodingfilter

package com.andreas.cake.global;

import com.sun.deploy.net.HttpRequest;
import com.sun.deploy.net.HttpResponse;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

public class EncodingFileter implements Filter {
    private String encoding = "UTF-8";
    public void init(FilterConfig filterConfig) throws ServletException {
        //可以通过filterConfig获取初始化参数来指定编码
        if (filterConfig.getInitParameter("encoding") != null) {
            encoding = filterConfig.getInitParameter("encoding");
        }
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        request.setCharacterEncoding(encoding);
        response.setCharacterEncoding(encoding);
        filterChain.doFilter(request,response);
    }

    public void destroy() {

    }
}

golbalController

package com.andreas.cake.global;


import javafx.scene.shape.Path;
import org.apache.ibatis.javassist.bytecode.stackmap.BasicBlock;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class GlobalController extends GenericServlet {
    //请求处理方法,可以根据用户请求的url可以分辨出由哪个类的哪个方法来处理,然后再调用其方法
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //单用户发送请求时候获取请求路径
        String path = request.getServletPath();
        //判断前后台请求
        if (path.indexOf("admin") != -1) {
            path = path.substring(7);
        } else {
            path = path.substring(1);
        }
        int index = path.indexOf("/");
        //通过请求路径获取到一个类名一个方法名
        String className = null;
        String methodName = null;
        if (index != -1) {
            className = "com.andreas.cake.controller" + path.substring(0, index) + "Controller";
            methodName = path.substring(index + 1, path.indexOf(".do"));
        } else {
            className = "com.andreas.cake.controller.DefaultController";
            methodName = path.substring(0, path.indexOf(".do"));
        }
        try {
            //通过反射执行相应的方法
            Class cla =Class.forName(className);
            Object obj = cla.newInstance();//获取对象
            Method method = cla.getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
            //执行方法,(调用次方的的对象,调用方法的参数)
            method.invoke(obj, request, response);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

mybatis.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.4//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--    mybatis的环境标签,mybayis可以支持多个数据源-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/music?useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
<!--        当前项目使用注解开发,自动扫描包中的接口设置成映射器接口-->
        <package name="com.andreas.cake.dao"/>
    </mappers>
</configuration>

cataloglist.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"  %>
<%--
  Created by IntelliJ IDEA.
  User: Andreas Byrsting
  Date: 2020/9/3
  Time: 14:42
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<jsp:include page="top.jsp"></jsp:include>
    <section id="content_wrapper">
        <section id="content" class="table-layout animated fadeIn">
            <div class="tray tray-center">
                <div class="content-header">
                    <h2> 分类管理</h2>
                    <p class="lead"></p>
                </div>
                <div class="admin-form theme-primary mw1000 center-block" style="padding-bottom: 175px;">
                    <div class="panel  heading-border">
                        <div class="panel-menu">
                            <div class="row">
                                <div class="hidden-xs hidden-sm col-md-3">
                                    <div class="btn-group">
                                        <button type="button" class="btn btn-default light">
                                            <i class="fa fa-trash"></i>
                                        </button>
                                        <button type="button" class="btn btn-default light">
                                            <i class="fa fa-plus" onclick="javascript:window.location.href='/admin/Catalog/toAdd.do';"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="panel-body pn">
                            <table id="message-table" class="table admin-form theme-warning tc-checkbox-1">
                                <thead>
                                <tr class="">
                                    <th class="text-center hidden-xs">Select</th>
                                    <th class="hidden-xs">名称</th>
                                    <th class="hidden-xs">描述</th>
                                    <th>操作</th>
                                </tr>
                                </thead>
                                <tbody>
                                <c:forEach items="${root.children}" var="cat1">
                                <tr class="message-unread">
                                    <td class="hidden-xs">
                                        <label class="option block mn">
                                            <input type="checkbox" name="mobileos" value="FR">
                                            <span class="checkbox mn"></span>
                                        </label>
                                    </td>
                                    <td>${cat1.title}</td>
                                    <td>${cat1.info}</td>
                                    <td>
                                        <a href="/admin/Catalog/remove.do?=${cat1.id}">删除</a>
                                    </td>
                                </tr>
                                    <c:forEach items="${cat1.children}" var="cat2">
                                        <tr class="message-unread">
                                            <td  class="hidden-xs">
                                                <label class="option block mn">
                                                    <input type="checkbox" name="mobileos" value="FR">
                                                    <span class="checkbox mn"></span>
                                                </label>
                                            </td>
                                            <td style="padding-left: 50px;">${cat2.title}</td>
                                            <td>${cat2.info}</td>
                                            <td>
                                                <a href="/admin/Catalog/remove.do?=${cat2.id}">删除</a>
                                            </td>
                                        </tr>
                                        <c:forEach items="${cat2.children}" var="cat3">
                                            <tr class="message-unread">
                                                <td class="hidden-xs">
                                                    <label class="option block mn">
                                                        <input type="checkbox" name="mobileos" value="FR">
                                                        <span class="checkbox mn"></span>
                                                    </label>
                                                </td>
                                                <td style="padding-left: 50px;">${cat3.title}</td>
                                                <td>${cat3.info}</td>
                                                <td>
                                                    <a href="/admin/Catalog/remove.do?=${cat3.id}">删除</a>
                                                </td>
                                            </tr>
                                        </c:forEach>
                                    </c:forEach>
                                </c:forEach>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </section>
<jsp:include page="bottom.jsp"></jsp:include>

web.xml

<?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_3_1.xsd"
         version="3.1">
    <filter>
        <filter-name>encoding</filter-name>
        <filter-class>com.andreas.cake.global.EncodingFileter</filter-class>
<!--        为过滤器指定初始化参数-->
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>GlobalServlet</servlet-name>
        <servlet-class>com.andreas.cake.global.GlobalController</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>GlobalServlet</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>


正在回答

登陆购买课程后可参与讨论,去登陆

3回答

同学你好,

1、CatalogDao接口中script尾标签少了>,如下:

http://img1.sycdn.imooc.com//climg/5f54b94209500fcd05880240.jpg

2、select()方法写错位置了,参考代码如下:

http://img1.sycdn.imooc.com//climg/5f54bada09219c3708700505.jpg

祝学习愉快~

好帮手慕阿慧 2020-09-04 10:39:59

同学你好,输出的类名和方法名没有问题。Application context是上下文访问路径,访问项目资源的时候需要带上。

     例如Application context为/web01,访问webapp->js目录下jquery.min.js文件,访问路径是http://localhost:8080/web01/js/jquery.min.js

如果我的回答解决了你的疑惑,请采纳!祝学习愉快!

  • 提问者 孬帮手慕小菜 #1
    这个错误我看了很多解决方法好像都不行啊,什么编码错误,xml头有空格这类的都缉拿查了还是这样麻烦老师帮忙看看, ### Error building SqlSession. ### The error may exist in com/andreas/cake/dao/CatalogDao.java (best guess) ### Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.builder.BuilderException: Error creating document instance. Cause: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 175; XML 鏂囨。缁撴瀯蹇呴』浠庡ご鑷冲熬鍖呭惈鍦ㄥ悓涓�涓疄浣撳唴銆� at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30) at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:52) at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:36) at com.andreas.cake.global.DaoFactory.<init>(DaoFactory.java:18) at com.andreas.cake.global.DaoFactory.getInstance(DaoFactory.java:26) at com.andreas.cake.biz.impl.CatalogBizImpl.<init>(CatalogBizImpl.java:13) at com.andreas.cake.controller.CatalogController.<init>(CatalogController.java:20) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) 这只能放这个么多字。
    2020-09-04 13:59:27
  • 同学你好,根据错误信息,CatalogDao.java中有错误,同学检查一下sql语句是否写错。如果问题没有解决,同学可以贴一下CatalogDao代码,老师检查一下。 祝学习愉快~
    2020-09-04 16:15:54
  • 我上面有贴啊
    2020-09-06 17:48:22
好帮手慕阿慧 2020-09-03 17:15:30

同学你好,GlobalController类中拼接类名的时候少些了一个点,导致找不到CatalogController类。同学添加输出语句,看一下类名和方法名是否正确。

参考代码如下:

http://img1.sycdn.imooc.com//climg/5f50b41609ea157108660300.jpg

如果我的回答解决了你的疑惑,请采纳!祝学习愉快!

  • 提问者 孬帮手慕小菜 #1
    我把 Deployment里面的Application context 由 /cakeProject_war_exploded 改成/ 终于不是404了 然后 System.out.println("className:"+className+"|||methodName:"+methodName); 类名和方法名出来了:className:com.andreas.cake.controller.CatalogController|||methodName:list 老师你帮我看一下有没有问题, 还有,这个Application context是干什么的能不能解释一下。
    2020-09-03 19:50:15
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师