Blog management system--blog details page, login page

With the URL resolved; now to the View Full Text button. We click this to view the full text and we will jump to the blog details page.
insert image description here
We hope to be on this page; replace these hard-coded data with those obtained from the backend.
insert image description here
1: Agree on the front-end and back-end interaction interface
request: GET /blog?blogId=1 (this is the same binding path as the blog list page; or the same method; but we will judge that if there is a query string in the URL, we will return to the blog The content of the details page; otherwise, return the content of the blog list page. It doesn’t matter if you bind a new path here; it’s just that the response results of these two are similar; it’s also much more convenient) But I still try to write in different paths; separate Reduce point coupling.

Response:
HTTP/1.1 200OK

{ blogId:1, title: "This is the first blog" content: "This is the first time I have become like this; how can I deny it", postTime: "2023-5-7 21:23", userId: 1




}

2: Implement the back-end code; this will eliminate the need to truncate the content of the article. query string can use this method to get val according to key. We can easily get this blogId. (We do not need to transmit data at the front end of the blog list page; if the front end transmits data in json format; it is still more troublesome to deal with. It is more convenient to receive query string)

insert image description here

Here we have to deal with it: the query string is null; there is no problem returning it; but an error is reported when the null string is converted into an int.
But the process of printing in the background like this is not satisfactory; because the user can't see what's going on; I hope to return an error page to indicate that there is no blog with this blog id. But it is not
easy to redirect the data sent by ajax. It is still troublesome; unlike the form form, the a tag is supported.
Two options:
1: I construct a json data; when blogId=null or no blog can be found, this object will be returned. The content in this object prompts that blogId=null or that the blog cannot be found; the normal jump will not cause the failure to be found; but sometimes there are too many blogs; you need to manually search in the address bar. Avoid this situation
insert image description here
2: Or change the logic of the front-end code; when nothing is found, return null to the front-end. The front end resolves to null; use location.assign('error page.html') to jump to the error page. The error page has to be implemented by ourselves; that's why the error pages of various websites are different.

3: Realize the front-end code.
Refer to this format we wrote before for construction.
insert image description here

url:'blogdetail'+location.search, where location.search is a global object of js; get the query string in the address bar of the browser. Direct splicing?blogId=3; we don’t need to write the question marks ourselves
insert image description here

insert image description here

insert image description here

login page

insert image description here
Here is the way of using the form form: the login page is to be redirected; because ajax cannot directly return 302 to jump so convenient; there are other ways of writing. The form itself will trigger the page jump.
Three steps:
1: Front-end and back-end interaction interface
request POST /login

username=zhangsan&password=123

Response
HTTP/1.1 302
Location:blog_list.html

2: Modify the front-end code.
insert image description here
The id here is a selector; it is included in the css file introduced earlier; select the style of these boxes; the name attribute is to obtain the content of this box; assign it to the name name; username=zhangsan, password=123 .

3: Back-end code
First read the passed username and password; then see if you can query it in the database
String username=req.getParameter(“username”);
String password=req.getParameter(“password”);

It is relatively convenient to read the form; unlike json, which needs to be turned around; but it is okay to read English here; if it is Chinese, it will be garbled. So you need to set the read.
One request is set; one is the response set; understand the request and construct the response (tell the browser how to understand this encoding). The response type is also set on a page; it is convenient for us to return a server construction page to prompt login failure when there is a login error
req.setCharacterEncoding(“utf8”);
resp.setContentType(“text/html;charset=utf8”);

Pay attention to these two pieces of logic: Do not write clearly whether it is a user error or a wrong password; for example, someone randomly enters a user name and password; the result prompts that the password is wrong; then it will make a program; loop through the input password; then it will not be able to find you password?
insert image description here

Backend code completion:

package api;

import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class Blog_loginServlet extends HttpServlet {
    
    

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        req.setCharacterEncoding("utf8");
        resp.setContentType("text/html;charset=utf8");
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        //空或者空字符串
        if(username == null || "".equals(username) || password == null || "".equals(password)){
    
    
       // 登录失败;这时候就可以返回一个登录失败的页面
            String html = "<h3>登录失败! 缺少 username 或者 password 字段</h3>";
            resp.getWriter().write(html);
            return;

        }
        //看看用户名和密码是否匹配;如果不匹配;还是登录失败
        UserDao userDao=new UserDao();
        User user=userDao.selectByUsername(username);
        //数据库查不到这个用户
        if(user==null){
    
    
            String html = "<h3>登录失败! 缺少 username 或者 password 字段</h3>";
            resp.getWriter().write(html);
            return;


        }
          if (!password.equals(user.getPassword())) {
    
    
            // 密码不对
            String html = "<h3>登录失败! 用户名或密码错误</h3>";
            resp.getWriter().write(html);
            return;
        }
          //  登录成功;创建会话;然后使用该会话保存用户信息
        HttpSession session=req.getSession(true);
        session.setAttribute("user",user);

        // 重定向到博客列表页
        resp.sendRedirect("blog_list.html1.html");
    }
}

Create a few users in the database to log in and test:
insert image description here
force refresh: ctrl+F5; sometimes we modify the code and re-enter the URL to find that the content is still the same. Caused by browser buffering. Because this operation is time-consuming; after one operation, the browser will cache it for you; and then you will directly fetch the cached result when you operate again. Similar to multi-threaded memory visibility issues. The result of frequent reading is the same; it is saved; no longer read repeatedly; but directly use this value. Force refresh ignores local cache.

Implement mandatory login

When the user visits the blog list page/details page/edit page, they are required to be logged in; it can only be used after logging in; you can modify your own. You can't change others.
Or implement it on the login page:
GET /login

HTTP/1.1 200 OK (The response returns the current login user information; if not logged in, a userId=0 is returned)
{ userId :1 username:'zhangsan'

}
insert image description here

Front-end code:
that is to say, access to each page code will execute such a function; then send the get request constructed by ajax; then check whether you are logged in; log in and do nothing; if you are not logged in, you will be forced to jump login page. This logic is added to the blog list, details page, and edit page
insert image description here

Normally, if you restart the server, you have to log in again; if the server is restarted and logged in, the browser is still logged in; this is a plug-in. Some tomcat plug-in versions are convenient for debugging when the server is shut down; the session is persisted; and it is automatically restored when it is restarted. This problem will not occur in the form of war package; you can also modify the configuration to achieve this effect. We can also use database persistence to save this session.

Guess you like

Origin blog.csdn.net/m0_64254651/article/details/130547589