解决方案 »

  1.   

    我想不调用默认的 doGet、doPost 而调用自己写的方法
      

  2.   

    写一个方法,在doGet或doPost里调用
      

  3.   

    doget  dopost 里面再调用。
      

  4.   

    在doGet 或 doPost 中 根据 request.getRequestURI 判断自己的请求uri,然后分发到不同的方法中去处理。
      

  5.   

    在表单中加一个属性,来确定需要调用哪一个方法执行,然后在doPost或doGet方法里面首先获取这个属性,判断需要调用哪个方法,再去调用对应的方法。
      

  6.   

    楼主貌似是不想重载doGet、doPost方法,你可以去重载service,不管什么get、post、head请求通通在一个方法里解决,但tomcat源码里明确提到不推荐重载service方法。或者在doGet中直接调用doPost方法,把get请求交给post统一处理。当然,一个表单对应一个有名有姓的方法,可以在表单中携带一个参数指明是对应哪个方法,比如action="?type=functionA",再service或doPost中获取参数type,根据type来调用对应的方法。更简单的type值如果就是方法名用反射来弄,判断都免了
      

  7.   


    能不能来个有源代码的例子。
    其实我想的就是 doGet、doPost 这两个方法不重载,而是直接写自己的方法,用的时候直接用自己的方法
      

  8.   

    还要例子写个例子,我是在以前老页面上写的,方便测试,把新写的方法摘出来,一堆import分不出哪个是哪个@WebServlet(urlPatterns=“/test”)
    public class Test extends HttpServlet{
        @SuppressWarnings("unused")
    private void functionA(HttpServletRequest request, HttpServletResponse response) throws IOException {
         response.getWriter().print("A");
        }
        @SuppressWarnings("unused")
        private void functionB(HttpServletRequest request, HttpServletResponse response) throws IOException {
         response.getWriter().print("B");
        }
        protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
         //反射处理任何表单请求,只要方法存在
         String type=request.getParameter("type");
        
         Method[] methods=this.getClass().getDeclaredMethods();
         for(Method method:methods){
         if(method.getName().equals(type)){
         method.setAccessible(true);
         try{
         method.invoke(this, request, response);
         }catch(Exception e){
         //NOOP
         }
         return;
         }
         }
        
         //木有处理方法,显示测试页面
         response.getWriter().append("<form action='?type=functionA' method='post'><input type='submit' value='functionA'></form>");
         response.getWriter().append("<form action='?type=functionB' method='post'><input type='submit' value='functionB'></form>");
        }
    }
      

  9.   


    import java.io.IOException;import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;public class ServletTest extends HttpServlet{ /**
     * 属性说明:serial number
     * @author Sean
     * @date 2014-5-30 下午5:25:10 
     */
    private static final long serialVersionUID = 1L; /**
     * 方法说明:重写doGet
     * @author Sean
     * @date 2014-5-30 下午5:25:44
     * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) 
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
    this.process(req, resp);
    }


    /**
     * 方法说明:重写doPost
     * @author Sean
     * @date 2014-5-30 下午5:26:00
     * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) 
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
    this.process(req, resp);
    }


    /**
     * 方法说明:统一处理请求的方法
     * @author Sean
     * @date 2014-5-30 下午5:26:59 
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void process(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    //提供一个请求转发的参数
    String action = request.getParameter("action"); //处理不同的请求
    if(action.equals("form1")){
    this.processForm1(request, response);
    }else if(action.equals("form2")){
    this.processForm2(request, response);
    }

    }

    /**
     * 方法说明:处理表单一
     * @author Sean
     * @date 2014-5-30 下午5:30:17 
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void processForm1(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    // TODO  
    }

    /**
     * 方法说明:处理表单二
     * @author Sean
     * @date 2014-5-30 下午5:30:26 
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void processForm2(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    // TODO
    }
    }
      

  10.   

    一般都是写 doGet,doPost, 向上楼们说的,要么你在 这两个方法中调用你自定义的方法.
      

  11.   

    粗略的可以用if 写,到一定程度就成了反射。package com.tomstudio.adms.app.faces;import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.util.Map;import org.springframework.beans.BeansException;
    import org.springframework.beans.factory.BeanFactory;import com.tomstudio.adms.common.ejb.ApplicationException;
    import com.tomstudio.adms.common.ejb.ServiceRequest;
    import com.tomstudio.adms.common.ejb.ServiceResponse;
    import com.tomstudio.adms.common.utils.Maps;public class BaseAppFace implements IFace {
    protected BeanFactory context;

    private final static String TXN_MAP_VALUE = "TxnFaceBean";

    /**
     * Support入口
     */
        public ServiceResponse perform(ServiceRequest request) 
            throws ApplicationException {
         try{
         String methodName = request.getMethodName();
         Maps txnMap = (Maps)context.getBean("txnFacesMapping");
         Map<String, String> map = txnMap.getMap();
         System.out.println("TxnFaceBean:="+map);
        
         String beanName = request.getRequestID() + "." + methodName;
         String value = map.get(beanName);
         if(TXN_MAP_VALUE.equals(value)) {
         ServiceResponse response = requiredTxn(request);
         return response;
         } else {
         Method method = getClass().getMethod(methodName, ServiceRequest.class);
         ServiceResponse response = (ServiceResponse)method.invoke(this, request);
         return response;
         }
         } catch (SecurityException e) {
    throw new ApplicationException(e);
    } catch (NoSuchMethodException e) {
    throw new ApplicationException(e);
    } catch (IllegalArgumentException e) {
    throw new ApplicationException(e);
    } catch (IllegalAccessException e) {
    throw new ApplicationException(e);
    } catch (InvocationTargetException e) {
    throw new ApplicationException(e.getCause());
    }
        }
        
        /**
         * Required入口
         */
        public ServiceResponse requiredTxn(ServiceRequest request) 
        throws ApplicationException {
    try{
         String methodName = request.getMethodName();
         Method method = this.getClass().getMethod(methodName, ServiceRequest.class);
         ServiceResponse response = (ServiceResponse)method.invoke(this, request);
         return response;
    } catch (SecurityException e) {
    throw new ApplicationException(e);
    } catch (NoSuchMethodException e) {
    throw new ApplicationException(e);
    } catch (IllegalArgumentException e) {
    throw new ApplicationException(e);
    } catch (IllegalAccessException e) {
    throw new ApplicationException(e);
    } catch (InvocationTargetException e) {
    throw new ApplicationException(e.getCause());
    }
    } @Override
    public void setBeanFactory(BeanFactory context) throws BeansException {
            this.context = context;
    }

    public static void main(String[] ar) {
    String value = "channelFace.addChannel";
    System.out.println( value.indexOf("."));
    String beanName = value.substring(0, value.indexOf("."));
         String sMethodName = value.substring(value.indexOf(".") + 1);
         System.out.println("beanName:-"+beanName);
         System.out.println("sMethodName:-"+sMethodName);
    }
    }
      

  12.   

    我一般就把方法写在doget()里面,然后在dopost()中调用doget()方法,我看视频也是这样的
      

  13.   


    嗯,还是这样方便。
    另外问一下,怎么判断一个对象中有没有内容,比如我想这样用:User user = new User()
    if(user == null){}
    if(!user){}就是想知道对象指针是不是指示的空,该怎么做
      

  14.   


    反射方便,问一下,怎么判断对象是不是指空怎么判断?
    我从数据库中取出数据存在一个对象中,如果没有数据库中没有要取的数据,那对象中不就是没有数据了,就是想判断对象中有没有数据,比如想用这样的User user = new User()
    if(user == null){}
    if(!user){}
      

  15.   


    嗯,还是这样方便。
    另外问一下,怎么判断一个对象中有没有内容,比如我想这样用:User user = new User()
    if(user == null){}
    if(!user){}就是想知道对象指针是不是指示的空,该怎么做

    我把数据库中取的数据存在对象中,想判断对象中存的有没有数据,也就是数据库中有没有要的数据
      

  16.   

    不是很明白你讲的是什么东东
    User user = new User()有了这句,user不可能为null
      

  17.   

    /ServletName?cmd="invokeMethodName",然后你后台通过获取cmd参数得到你想要调用的方法就可以了
      

  18.   

    不是很明白你讲的是什么东东
    User user = new User()有了这句,user不可能为null
    我举个例子吧操作数据库的方法部分代码
    public User findByLoginnameAndLoginpassDao(String username, String password) {
    /**
     * 1、按用户名密码查询匹配的数据
     * 2、把查询出来的结果封装到 map 中 (key 全部转换成小写,和 user 中的属性名相对应)
     * 3、把查询出的用户数据 (map 中)封装在 user 中
     * 4、返回查到的用户数据 user
     */

    User user = new User();
    Map<String, Object> map = new LinkedHashMap<String, Object>();

    System.out.println("进入了 UserDao.findByLoginnameAndLoginpassDao 方法中");
    String sql = "select * from t_user where username=? and password=?";
    try {
    psmt = this.getConn().prepareStatement(sql);
    psmt.setString(1, username);
    psmt.setString(2, password);
    rs = psmt.executeQuery(); int n = rs.getMetaData().getColumnCount();
    while (rs.next()) {
    for (int i = 1; i <= n; i++) {
    String s = rs.getMetaData().getColumnName(i).toLowerCase();
    Object o = rs.getObject(i);
    map.put(s, o);
    }
    } BeanUtils.populate(user, map);

    System.out.println("user : " + user);

    return user;
    }测试方法
    @Test
    public void testClass() {
    UserDao userdao = new UserDao();

    //数据库中的数据是("wangwu", "123")
    if(userdao.findByLoginnameAndLoginpassDao("wangwu", "124") == null){
    System.out.println("yyyyyyyyyyyyy");
    } else {
    System.out.println("nnnnnnnnnnnnn");
    }
    }测试打印出的结果是:
    进入了 UserDao.findByLoginnameAndLoginpassDao 方法中
    user : com.student.user.domain.User@6efdebd
    nnnnnnnnnnnnn其实我是在 Servlet 中用 if(userService.userLoginService(user) == null){} 来判断有没有验证通过
      

  19.   


    findByLoginnameAndLoginpassDao try块后面返回了什么东西,没贴出来啊,如果BeanUtils.populate不会抛出异常,后面的代码也无所谓,因为在这种情况下,findByLoginnameAndLoginpassDao方法除非是查询数据库出错,否则一定会返回一个user对象,通过user==null是无法判断数据库到底有没有返回数据读取结果集部分可以稍微改一下,while块换成if elseif(!rs.next()){
    return null;
    }else{
    //结果集应该不会有多条?
                    for (int i = 1; i <= n; i++) {
                        String s = rs.getMetaData().getColumnName(i).toLowerCase();
                        Object o = rs.getObject(i);
                        map.put(s, o);
                    }
    }
      

  20.   

    提交的时候后面接个字段type,设置值为1或者2,判断值在dopost里面跳转
      

  21.   


    findByLoginnameAndLoginpassDao try块后面返回了什么东西,没贴出来啊,如果BeanUtils.populate不会抛出异常,后面的代码也无所谓,因为在这种情况下,findByLoginnameAndLoginpassDao方法除非是查询数据库出错,否则一定会返回一个user对象,通过user==null是无法判断数据库到底有没有返回数据读取结果集部分可以稍微改一下,while块换成if elseif(!rs.next()){
    return null;
    }else{
    //结果集应该不会有多条?
                    for (int i = 1; i <= n; i++) {
                        String s = rs.getMetaData().getColumnName(i).toLowerCase();
                        Object o = rs.getObject(i);
                        map.put(s, o);
                    }
    }

    findByLoginnameAndLoginpassDao后面没错,就只有 user==null 这个了,我见别人这样写的行,就这样写,但是就是不行,下面这个是别人的代码
    public String login(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
    /*
     * 1. 封装表单数据到User
     * 2. 校验表单数据
     * 3. 使用service查询,得到User
     * 4. 查看用户是否存在,如果不存在:
     *   * 保存错误信息:用户名或密码错误
     *   * 保存用户数据:为了回显
     *   * 转发到login.jsp
     * 5. 如果存在,查看状态,如果状态为false:
     *   * 保存错误信息:您没有激活
     *   * 保存表单数据:为了回显
     *   * 转发到login.jsp
     * 6. 登录成功:
     *   * 保存当前查询出的user到session中
     *   * 保存当前用户的名称到cookie中,注意中文需要编码处理。
     */
    /*
     * 1. 封装表单数据到user
     */
    User formUser = CommonUtils.toBean(req.getParameterMap(), User.class);
    /*
     * 2. 校验
     */
    Map<String,String> errors = validateLogin(formUser, req.getSession());
    if(errors.size() > 0) {
    req.setAttribute("form", formUser);
    req.setAttribute("errors", errors);
    return "f:/jsps/user/login.jsp";
    }

    /*
     * 3. 调用userService#login()方法
     */
    User user = userService.login(formUser);
    /*
     * 4. 开始判断
     */
    if(user == null) {                                                                 //只关心这个
    req.setAttribute("msg", "用户名或密码错误!");
    req.setAttribute("user", formUser);
    return "f:/jsps/user/login.jsp";
    } else {
    if(!user.isStatus()) {
    req.setAttribute("msg", "您还没有激活!");
    req.setAttribute("user", formUser);
    return "f:/jsps/user/login.jsp";
    } else {
    // 保存用户到session
    req.getSession().setAttribute("sessionUser", user);
    // 获取用户名保存到cookie中
    String loginname = user.getLoginname();
    loginname = URLEncoder.encode(loginname, "utf-8");
    Cookie cookie = new Cookie("loginname", loginname);
    cookie.setMaxAge(60 * 60 * 24 * 10);//保存10天
    resp.addCookie(cookie);
    return "r:/index.jsp";//重定向到主页
    }
    }
    }
      

  22.   

    也许人家的userService.login方法在没有查询到数据时明确的返回了null,你的findByLoginnameAndLoginpassDao的逻辑和人家的不一样,就不要照抄了
      

  23.   


    反射方便,问一下,怎么判断对象是不是指空怎么判断?
    我从数据库中取出数据存在一个对象中,如果没有数据库中没有要取的数据,那对象中不就是没有数据了,就是想判断对象中有没有数据,比如想用这样的User user = new User()
    if(user == null){}
    if(!user){}

    一般会把取到的记录放到list中,判断是否取到了记录:
    List<User> silverUserList = findSilverUserList();
    if(null == silverUserList ||  silverUserList.size() == 0){
        errorMsg.addMsg("没有找到银牌级别的会员");
    }