The way of Java playing strange ----- the book city project of JavaWeb

(1) Replace content

In the response directory, ctrl+shift+R

(2) Error message echo

Solution (three modifications are needed here):
1. In the servlet program, when the user name or password is entered incorrectly, the data is saved in the request domain object
(in fact, you can imagine why you want to save the data in the request field. A: the data saved in the request field object fails after sending another request. The first time I submit and save the data requested for the first time, the data requested for the first time is echoed, and the second time I submit and save the data requested for the second time, so the data requested for the second time should be echoed.)
2. Judge the error information in the jsp page. If the error information value is not empty, the error information will be output
3. Judge the information to be echoed in the jsp page. If the input is wrong, save it in the value of the input box

//Servlet
if(userService.login(user)==null){
            System.out.println("Wrong user name or password");
            //If an error occurs, put the echo information into the req field
            req.setAttribute("msg","Wrong user name or password");
            req.setAttribute("username",username);
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);
        }else{
            req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req,resp);
        }
//jsp error message
<span class="errorMsg"><%=request.getAttribute("msg")==null?"Please enter your user name and password":request.getAttribute("msg")%></span>
//jsp input box echo
<input class="itxt" type="text" placeholder="enter one user name" autocomplete="off" tabindex="1" name="username"
value="<%=request.getAttribute("username")==null?"":request.getAttribute("username")%>"/>

(3) Code optimization

In general business, a servlet corresponds to a function, and a user business corresponds to a UserServlet program. So it needs to be simplified

3.1 optimize with hidden

Solution:
1. Write UserServlet
2. Add hidden in the form of jsp page

public class UserServlet extends HttpServlet {
    UserService userService= new UserServiceImpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");

        if("login".equals(action)){
            login(request,response);
        }else if("regist".equals(action)){
            regist(request,response);
        }
    }
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException {
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        User user=new User(null,username,password,null);
        if(userService.login(user)==null){
            System.out.println("Wrong user name or password");
            //If an error occurs, put the echo information into the req field
            req.setAttribute("msg","Wrong user name or password");
            req.setAttribute("username",username);
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);
        }else{
            req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req,resp);
        }

    }
    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException {
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        String email=req.getParameter("email");
        String code=req.getParameter("code");
        //First, check whether the verification code is correct
        if("abcde".equalsIgnoreCase(code)){
            if(userService.existsUsername(username)){
                System.out.println("User name already exists");
                req.setAttribute("msg","User name already exists");
                req.setAttribute("username",username);
                req.setAttribute("email",email);
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
            }else{
                userService.registUser(new User(null,username,password,email));
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req,resp);
            }
        }
        else{
            req.setAttribute("msg","Verification code error");
            req.setAttribute("username",username);
            req.setAttribute("email",email);
            System.out.println("Verification code error");
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);

        }
    }


}

<form action="userServlet" method="post">
									<input type="hidden" name="action" value="login" />
									<label>User name:</label>
									<input class="itxt" type="text" placeholder="enter one user name" autocomplete="off" tabindex="1" name="username"
									value="<%=request.getAttribute("username")==null?"":request.getAttribute("username")%>"
									/>

3.2 optimizing with reflection

Why use reflection? We can see that there are a large number of if judgment statements in the previous step, and the names of action and login are the same.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");
        //Obtain the action business authentication string and the corresponding business method reflection object
        try {
            Method method=this.getClass().getDeclaredMethod(action,HttpServletRequest.class,HttpServletResponse.class);
            //Call the target business method
            method.invoke(this,request,response);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }

Why is the message delivered class without directly passing in parameters?
Reflection is to obtain the specific method according to the parameter type, and pass class. Wait until the invoke method is called before passing the arguments, that is, req and resp, to the method

3.3 optimization using baseServlet

The reason why the parent class method is defined as abstract is that it is convenient to call. When the post request enters the userServlet, it will look for the post method. If it is not found, it will call the post method of the parent class. The post method of the parent class is not rewritten in the subclass userServlet
Just move the contents of the dopost method in the UserServlet to the baseServlet

(4) BeanUtils

All requested parameters can be injected into the JavaBean at once.

(5) Using EL expressions

Keywords: Java

Added by paul.mac on Thu, 03 Feb 2022 02:13:06 +0200