Advanced Java Development class notes (five)

Optimized code

After logging fully functional development, found a lot of duplicate code (refer to Advanced Java Development class notes (d)) At this point, we need to optimize the code.
Before code optimization:
Here Insert Picture Description
Here Insert Picture Description
the code optimization:
Here Insert Picture Description
Here Insert Picture Description
so the code becomes more simple, after modifying the code, it will not appear a modified, while the other one forget the same code modification.

Development verification code function

After completion of the above work, we can begin to develop the login screen is another important function is to verify code function.
First, we create a new CaptchaControllerclass:
Here Insert Picture Description
Again, is inherited HttpServletand configured WebServlet(configuration WebServlet method, refer to Advanced Java Development class notes (d)), we rewrite this is service:
Here Insert Picture Description
because the code is a picture instead of a text, so let's create a buffer BufferedImageto store pictures, using Graphicsthe abstract class used to pass paint()as a method of brush, this time we need to get used commands are:
Here Insert Picture Description
command contains set the background color, font size, format, slash and increase noise code.
Because the code non-fixed text, all we have to define a way to get random characters:
Here Insert Picture Description
recommended to remove confusing letters, of course, is not removed is also possible.
Define a method, we can maincreate a folder under Testthe folder used to test methods are available:
Here Insert Picture Description
test finished, after the method is to be used, in CaptchaControllerwhich, we can call it:

 String code =randomString(4); //调用随机生成验证码的方法
        g.drawString(code,25,32);

(Specific location to view the previous picture, marked with tips)
Finally, we want to display in the browser code:
Here Insert Picture Description
When you are done, basically completed the development of a verification code, we can now look up and running.
Here Insert Picture Description
Finally, do not forget to submit code to a local warehouse, and to push to a remote repository.

Released seven original articles · won praise 0 · Views 196

Guess you like

Origin blog.csdn.net/Vinseny/article/details/105218279