actionservlet.java

来自「关于servlet监听器和过滤器的例子,大家如果有这方面的需求的话可以」· Java 代码 · 共 69 行

JAVA
69
字号
package com.allanlxf.sms.web;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class ActionServlet extends HttpServlet
{
    public void doGet(HttpServletRequest request, HttpServletResponse response)
                        throws IOException, ServletException
    {
        String path = request.getServletPath();
        //String path=request.getContextPath()
        path = path.substring(0, path.indexOf("."));

        if(path.equals("/login"))
        {
            String userName = request.getParameter("userName");
            String password = request.getParameter("password");
            if(getContextParameter("userName").equals(userName)
                && getContextParameter("password").equals(password))
            {
                HttpSession session = request.getSession();
                session.setAttribute("userName", userName);
                request.setAttribute("data", "request");
                response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/protected/user/center"));
                
                return;
            }else
            {
                response.sendRedirect(request.getContextPath() + "/login");
                return;
            }          
        }else if(path.equals("/logout"))
        {
            HttpSession session = request.getSession(false);
            session.invalidate();
            response.sendRedirect(request.getContextPath() + "/login");
            return;
        }else if(path.equals("/viewinfo"))
        {
            forward("/protected/user/info", request, response);
        }else if(path.equals("/modifyinfo"))
        {
            request.setAttribute("data", "request");
            forward("/protected/user/modify", request, response);
        }else
        {
            throw new ServletException("unknown path:" + path);
        }
    }
    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
                        throws IOException, ServletException
    {
        doGet(request, response);
    }
    
    private String getContextParameter(String name)
    {
        return getServletContext().getInitParameter(name);
    }
    
    private void forward(String path, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    {
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(path);
        dispatcher.forward(request, response);
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?