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:
the code optimization:
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 CaptchaController
class:
Again, is inherited HttpServlet
and configured WebServlet
(configuration WebServlet method, refer to Advanced Java Development class notes (d)), we rewrite this is service
:
because the code is a picture instead of a text, so let's create a buffer BufferedImage
to store pictures, using Graphics
the abstract class used to pass paint()
as a method of brush, this time we need to get used commands are:
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:
recommended to remove confusing letters, of course, is not removed is also possible.
Define a method, we can main
create a folder under Test
the folder used to test methods are available:
test finished, after the method is to be used, in CaptchaController
which, 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:
When you are done, basically completed the development of a verification code, we can now look up and running.
Finally, do not forget to submit code to a local warehouse, and to push to a remote repository.