java stepped pit diary

1: Environment: idea 14 version, win10, springboot

2: The first question: shiro must implement login (plus code)

Reference: https://blog.csdn.net/qq_34021712/article/details/80470738 © Wang Sai super       

Check codes:

@RequestMapping (value = "/ Login", Method = RequestMethod.POST) 
public String loginUser (the HttpServletRequest Request, username String, String password, the rememberMe Boolean, String captcha, the Model Model) { 

// check codes 
// session in codes 
String sessionCaptcha = (String) SecurityUtils.getSubject () the getSession () the getAttribute (CaptchaController.KEY_CAPTCHA);.. 
IF (! == null || captcha captcha.equalsIgnoreCase (sessionCaptcha)) { 
model.addAttribute ( "MSG", "error codes!"); 
return "Login"; 
} 
// encrypting the password 
// password = new SimpleHash ( "md5 ", password, ByteSource.Util.bytes (username.toLowerCase () + "shiro"), 2) .toHex (); 
// if I remember clickswrong user name or password! 
"); }
 
IF (E instanceof LockedAccountException) { 
model.addAttribute (" msg "," account is locked, please contact the administrator ");! 
} 
// returns the login page 
return" Login "; 
} 
}

  Here I put this module which deal specifically with logincontroller login operation; The following is a code generation; a new CaptchaUtil put it under utils, standard local yellow note the path to your own definition of

the java.awt.Color Import; 
Import java.awt.Font; 
Import the java.awt.Graphics; 
Import java.awt.image.BufferedImage; 
Import java.io.File; 
Import java.io.FileOutputStream; 
Import java.util.Random ; 

Import javax.imageio.ImageIO; 

/ ** 
 * tools codes 
 * / 
public class CaptchaUtil { 

    // string generated randomly 
    Private Final static string RANDOM_STRS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 

    Private static string FONT_NAME = Final "the Fixedsys"; 
    Private Final FONT_SIZE int = 18 is static; 

    Private the Random Random new new = the Random (); 

    Private int width = 80; // image width 
    private int height = 25; // high image
    private int lineNum = 50; // number of interference lines 
    private int strNum = 4; // number of randomly generated characters 

    / ** 
     * Generate a random image 
     * / 
    public genRandomCodeImage the BufferedImage (the StringBuffer randomCode) { 
        // the BufferedImage class is the Image Buffer class 
        the BufferedImage new new image = the BufferedImage (width, height, 
                BufferedImage.TYPE_INT_BGR); 
        // Get the Graphics object, facilitating the image you draw 
        Graphics image.getGraphics G = (); 
        // set the background color 
        g.setColor (getRandColor ( 200 is, 250)); 
        g.fillRect (0, 0, width, height); 

        // set the color of the interference line 
        g.setColor (getRandColor (110, 120)); 

        // draw line interference
        for (int I = 0; I <= lineNum; I ++) { 
            drowLine (G); 
        } 
        // draw random characters 
        g.setFont (new new the Font (FONT_NAME, Font.ROMAN_BASELINE, FONT_SIZE)); 
        for (int I =. 1; I <= strNum; I ++) { 
            randomCode.append (drowString (G, I)); 
        } 
        g.dispose (); 
        return Image; 
    } 

    / ** 
     * given color range obtained random 
     * / 
    Private color getRandColor (int FC, BC int) { 
        IF (FC> 255) { 
            FC = 255; 
        } 
        IF (BC> 255) { 
            BC = 255; 
        } 
        int = FC + R & lt random.nextInt (BC - FC);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

    /**
     * 绘制字符串
     */
    private String drowString(Graphics g, int i) {
        g.setColor(new Color(random.nextInt(101), random.nextInt(111), random
                .nextInt(121)));
        String rand = String.valueOf(getRandomString(random.nextInt(RANDOM_STRS
                .length())));
        g.translate(random.nextInt(3), random.nextInt(3));
        g.drawString(rand, 13 * i, 16);
        return rand;
    }

    /**
     * 绘制干扰线
     */
    private void drowLine(Graphics g) {
        int x = random.nextInt(width);
        int y = random.nextInt(height);
        int x0 = random.nextInt(16);
        int y0 = random.nextInt(16);
        g.drawLine(x, y, x + x0, y + y0);
    }

    /**
     * 获取随机的字符
     */
    private String getRandomString(int num) {
        return String.valueOf(RANDOM_STRS.charAt(num));
    }

    public static void main(String[] args) {
        CaptchaUtil tool = new CaptchaUtil();
        StringBuffer code = new StringBuffer();
        BufferedImage image = tool.genRandomCodeImage(code);
        System.out.println ( "Random code =" + code); 
        the try { 
            memory // output image to the client by flowing form 
            ImageIO.write (Image, "the JPEG", a FileOutputStream new new (new new File ( "/ the Users /wangsaichao/Desktop/random-code.jpg "))); 
        } the catch (Exception E) { 
            e.printStackTrace (); 
        } 
    } 
}
                    

  Login interface code, if this is the case you will find that the page will not appear verification code, standard yellow part is the verification code refresh the code, you must call this method to generate verification codes, marked red part of your logincontroller inside methods path.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8" />
    <title>Insert title here</title>
</head>
<body>
<h1>欢迎登录</h1>
<h1 th:if="${msg != null }" th:text="${msg}" style="color: red"></h1>
<form action="/login" method="post">
    用户名:<input type="text" name="username"/><br/>@ {/ Captcha.jpg}
    codes" th: src = "codes: <input type = "text"
    Password: <input type = "password"" title="点击更换" id="captcha_img"/>
    (看不清<a href="javascript:void(0)" onclick="javascript:refreshCaptcha()">换一张</a>)<br/>
    <input type="checkbox" name="rememberMe" />记住我<br/>
    <input type="submit" value="提交"/> <button><a href="/unlockAccount">解锁admin用户</a></button>
</form>
</body>

<script type="text/javascript">
    window.οnlοad=kickout();
    

加上:
$(function(){
refreshCaptcha();
})
    function refreshCaptcha(){
        $("#captcha_img").attr("src","/Captcha.jpg?id=" + new Date() + Math.floor(Math.random()*24));
    }
</script>
</html>

  Then talk about the problems I encountered: Enter the correct account password but can not log in, because that will be your default shiro md5 password encryption, time will shiro match either of md5 encryption removed, or is the md5 encrypted password then match. shiro does not require you to find the database, he acquiesced carried out this operation.

3. The second problem, common Jump

  There are a variety of ways, just say here that the controller is inside the jump:

@RequestMapping("/")
    public String index() {
        return "login";
    }

@RequestMapping("/")
    public String index() {
        return "redirect:/login";
    }

  Both of the above jump is more, the first direct return, then it is to find your .jsp file. The second, redirect: / login interpreted as redirection, he will find inside the controller corresponding to RequestMapping ( "/ login") to the beginning of the method. Then jump.

Another problem involves the mutual transfer of the value of the page (jump) to analyze a case

logincontroller里面
@RequestMapping("/edit") public String userEdit(Model model, HttpServletRequest request) { String id = request.getParameter("id"); int userid = Integer.parseInt(id); 方法 model.addAttribute("user", uservo);传值方式 return "页面"; } @RequestMapping("/editUser") @ResponseBody public ResultVo edit(UserEntity userEntity) { ResultVo result = new ResultVo(); 方法 if (CommonUtil.isNotNull(userVo)) { result.setSuccess(false); } else { result.setSuccess(true); } Result return; } Page main ajax pass value code $ .ajax ({ type: "the POST", the async: "to false", DataType1: "JSON", Data: T, URL: "the root} {$ / User / edituser" , // incoming values Success: function (Data) { IF (data.success) { window.location.href = '$ {} the root / Edit'; // Go interface } } });

  Process: the main page has finished loading: Click the Edit button, judge in editUser inside, the result returned is true and false, returns true if it will jump to edit, edit jump to the corresponding page.

Guess you like

Origin www.cnblogs.com/FlowerNotGiveYou/p/11511154.html