4, Spring technology stack-verification code generation and send __spring

Source: Internet
Author: User

Integration completes MyBatis, after the log4j2, next will enter the specific function development process, first we explain, enters the concrete research and development process, because the code will be many, therefore in the follow-up function development process, we will have very few code (because the page front end and the backstage code adds up will be many, Paste code is not as good as their own to GitHub download), the source code you can go directly to GitHub, we will be more to explain the specific features of the research and development program and the use of key technologies.

Before doing specific functions, we may have a lot of conditions to consider, such as the choice of which page layout and decoration framework, some basic questions (such as Chinese garbled) how to solve the front frame selection, first let us see what our blog system will be made.

The general needs of our blogging system are made as an effect shown above.

1, Sitemesh use

Under normal circumstances, we developed the application, the layout and appearance of the page are basically consistent, and the page's menu bar and the bottom of the copyright information and so on generally will not change. However, on all pages, if we all copy the menu bar and the bottom copyright information to each page, if one day our system's menu or copyright information changes, we will have to modify all the pages.

Is there a way to unify the common parts, while other different pages simply need to be set up to inherit or share the common parts of the code? The answer is certainly yes, and this is what we need to learn and learn from the adorner.

At present, there are many adorners on the market, our blog system chooses Sitemesh as our system's adorner. Sitemesh is a Web page layout and decoration framework, which can be used to separate the content of the page and the structure of the page to achieve the purpose of sharing the page structure.

Sitemesh is a framework based on web page layouts, decorations, and integration with existing Web applications. It helps us create a consistent page layout and appearance in a large number of page items, such as a consistent navigation bar, consistent banner, consistent copyright, and so on. Not only can it handle dynamic content, such as jsp,php,asp, it can also handle static content, such as HTM content, so that its content also conforms to the requirements of your page structure. It can even embed the HTML file as a panel in the form of a file like include. All of these are the most vivid implementations of the GOF decorator model. Although it is implemented by the Java language, it can be well integrated with other Web applications.

Using Sitemesh, you first need to introduce two dependencies, in the Pom.xml of the BLOG_PC module:

<dependency>
<groupId>opensymphony</groupId>
    <artifactid>sitemesh</ artifactid>
    <version>2.4.2</version>
</dependency>
<dependency>
<groupId>org.sitemesh</groupId>
    <artifactId>sitemesh</artifactId>
    <version >3.0.1</version>
</dependency>

The Sitemesh of the OS (opensymphony) is a framework component used to implement page layouts and decorations (layout and decoration) in the JSP, helping site developers to easily separate the dynamic content and the static decorative appearance of the page.

After the dependency configuration is good, we need to configure the Sitemesh filter in Web.xml:

<!--Add Sitemesh 3 filter start-->
<filter>
    <filter-name>sitemesh</filter-name>
    <filter-class>com.opensymphony.module.sitemesh.filter.PageFilter</filter-class>
</filter >
<filter-mapping>
    <filter-name>sitemesh</filter-name>
    <url-pattern>/* </url-pattern>
</filter-mapping>
<!--add Sitemesh 3 filter End-->

This configuration above indicates that all requests are filtered using the Com.opensymphony.module.sitemesh.filter.PageFilter filter.

The configuration Sitemesh descriptor file is then used to specify decorative pages and pages that need to be decorated and that do not need to be decorated. You first need to create a new Decorators.xml file in the Web-inf directory, and then write the following configuration:

<?xml version= "1.0" encoding= "Utf-8"?> <decorators defaultdir=
"/web-inf/views/layout/" >
    <! --here to define pages that don't need filtering-->
    <!--<excludes>
        <pattern>/static/*</pattern>
    </ Excludes>-->

    <!--used to define the page to be filtered by the adorner-->
    <decorator name= "Default" page= "blog_decor.jsp" >
        <pattern>/*</pattern>
    </decorator>
</decorators>

So the Sitemesh is configured, next in the/web-inf/views/layout/directory to create a new blog_decor.jsp page, as a decorative page.

The decorative pages of our blog system are designed in the following way:

<%@ page language= "java" contenttype= "text/html; charset=utf-8" pageencoding= "UTF-8"% > <%@ taglib prefix= "C" uri= "Http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix= "Sitemesh" uri= "http:/" /www.opensymphony.com/sitemesh/decorator "%> <c:set var= ctx" value= "${pagecontext.request.contextpath}"/ > <! DOCTYPE html> 

The system head and the bottom are fixed, the middle content takes the content which the body label in each JSP page contains.

The head code is written in the/web-inf/views/include/header.jsp file, the bottom code is written in the/web-inf/views/include/bottom.jsp file, here is not posted, the reader to GitHub download.

2, Chinese garbled solution

In the use of Spring MVC development application, we often encounter the problem of Chinese garbled, so we need to configure a character encoding filter in the Web.xml file, the system is forced to encode as UTF-8, the specific configuration as follows (in the Web.xml file appended), this article does not do a specific explanation.

<!--solve Chinese garbled start-->
<filter>  
        <filter-name>characterEncodingFilter</filter-name>  
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
        < init-param>  
            <param-name>encoding</param-name>  
            <param-value>utf-8</param-value >  
        </init-param>  
        <init-param>  
            <param-name>forceEncoding</param-name>  
            <param-value>true</param-value>  
        </init-param>  
</filter>  
< filter-mapping>  
        <filter-name>characterEncodingFilter</filter-name>  
        <url-pattern >/*</url-pattern>  
</filter-mapping>   
<!--solve Chinese garbled end-->

3. Front Frame Selection

Our blog system front-end framework chooses to use Layerui, for more content on Layerui, please view the official website of Layerui.
http://layer.layui.com/, this article does not make detailed explanation.

4. JSON Data Support

In the course of our system development, in many requests, we all need to use JSON-formatted data, such as data in JSON format to be easier to process, and to support transformations between JSON, objects, and maps, so our system also needs to support these functions. So our blogging system uses Jackson, which is well known to all.

In the pom of the blog system's parent module blog, we add dependent dependencies as follows:

<!--JSON data--> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId> Jackson-core-asl</artifactid> <version>${jackson.version}</version> </dependency> < Dependency> <groupId>org.codehaus.jackson</groupId> <artifactid>jackson-mapper-asl</ artifactid> <version>${jackson.version}</version> </dependency> <dependency> < Groupid>com.fasterxml.jackson.core</groupid> <artifactId>jackson-core</artifactId> < version>${jackson_version}</version> </dependency> <dependency> <groupId> Com.fasterxml.jackson.core</groupid> <artifactId>jackson-databind</artifactId> <version> ${jackson_version}</version> </dependency> <dependency> <groupId> Com.fasterxml.jackson.core</groupid> <artifactId>jackson-annotations</artifactId> <version& Gt;${jackson_version}</version> </dependency> <dependency> <groupId> Com.fasterxml.jackson.module</groupid> <artifactid>jackson-module-jaxb-annotations</artifactid > <version>${jackson_version}</version> </dependency>

After the dependency configuration is complete, you will need to Blog_ In the Spring-mvc.xml file of the PC module, add the message Converter (mappingjackson2httpmessageconverter) and the Annotation method processing adapter (Annotationmethodhandleradapter), if this configuration is not done, we Objects returned using methods such as @responsebody annotations report an exception when they need to be converted to JSON format.

<!--rest JSON related ... start-->
<bean id= "Mappingjacksonhttpmessageconverter" class= "
          Org.springframework.http.converter.json.MappingJackson2HttpMessageConverter ">
        <property name=" Supportedmediatypes ">
            <list>
                <value>application/json;charset=UTF-8</value>
            </list>
        </property>
</bean>
<bean class= " Org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter ">
        <property name=" Messageconverters ">
            <list>
                <ref bean=" Mappingjacksonhttpmessageconverter "/>
            </ list>
        </property>
</bean>
<!--rest JSON related ... end-->

5, the Mail sends uses (the authentication code sends)

Well, now basically our base configuration has been completed (note that about the front-end CSS, JS, html These things, we directly on the GitHub take down the good, the code is too much, not fit one by one posted out, we first do a registration page, the controller under the package to build a user package, Then build a Usercontroller, in the controller to create a new method, so that the request-oriented registration page, our blog system will register the JSP page in the/web-inf/views/user directory, named Register.

The registration page style is probably the following figure:

We mainly need to implement a function, that is, when users fill out the user's mailbox, click the "Get Authentication Code" button, we will mail the form of the user's mailbox to send a registration verification code.

Here is a key technical point, that is, send the mail, we have here to tell you how to use Javax.mail to send mail and verify the code to send the implementation of the function.

To send a message using JavaMail, you first need to add two dependencies, because the message is a public function, we can call it in other modules, so we will send this piece of mail in the common module, so, in Blog_ In the pom.xml of the common module, add the following dependencies:

<dependency>
<groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>${java_mail_version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
    <artifactId>commons-email</artifactId>
    <version>${commons_email_version}</version>
</dependency>

After the dependency configuration, the next thing to do is to get an SMTP service, our blog system using the SMTP service provided by QQ mailbox to achieve.

To configure the SMTP service, you will first need to set up and open the SMTP service to your QQ mailbox, and then you'll get an authorization code, especially to remember that when you send the message, the mailbox password is the authorization code that is given to you when you set up the SMTP service, not your own mailbox password, remember While using the QQ SMTP service, be sure to set the port of SMTP, not using the default port, use the default port will report 530 error, you can set the port to 587.

In the resources directory of the BLOG_PC module, create a new config.properties configuration file and write your SMTP service information.

mail_host=smtp.qq.com
mail_port=587
mail_address= mailbox
mail_passowrd= Authorization Code

In the public module of our blogging system, which is the Blog_common module, we create a new config package, which we use to implement the ability to get a wide variety of configuration information.

First we create a new Sysconfig.java class in the Config package, which is used to read configuration information from the Config.properties file. So we need to set four private static properties in this class (since these properties are typically configured with very low frequency of changes), respectively, Mail_host, Mail_port, Mail_address, MAIL_PASSOWRD, and of course, subsequent if there is configuration information to read, can also be set to this class, and these properties only need to set the fetch (GET) method on the line, do not have to set the set method, because the values of these properties we will be obtained from the configuration file.

In the Sysconfig class, when we get the configuration file, because we just need to get one, we write a static block of code that allows the JVM to set the property value to the configuration class when the class is loaded, with the key code as follows.

public class Sysconfig {private static String mail_host;
    private static String mail_address;
    private static String mail_passowrd;

    private static String Mail_port;

    @IgnoreAssignment private static Logger Logger = Logmanager.getlogger (Sysconfig.class); @IgnoreAssignment public static final InputStream fileInput = SysConfig.class.getResourceAsStream ("/config.properties

    "); 

    @IgnoreAssignment private static Properties prop = new properties ();
    Private Sysconfig () {} static{load (fileInput);
        private static void Load (InputStream is) {try {prop.load (IS);
        catch (IOException e) {logger.error ("", e);
        }//Assign value to config class attribute class<sysconfig> configclass = Sysconfig.class;
        field[] fields = Configclass.getdeclaredfields ();
            for (Field field:fields) {ignoreassignment ia = field.getannotation (ignoreassignment.class); if (IA= = null) {String fieldName = Field.getname ();
                    try {Object valobj = Field.get (Configclass); String Fieldvalue = (valobj!= null)?
                    String.valueof (valobj): "";
                    String Provalue = Prop.getproperty (fieldName);
                    if (Stringutils.isempty (Provalue)) {Provalue = Prop.getproperty (Fieldname.replace ("_", ".")); } if (!fieldvalue.equals (Provalue)) {//If the value is not the same as the assignment field.setaccess
                        Ible (TRUE);
                    Field.set (Configclass, Provalue);
                The catch (Exception e) {logger.error ("field name {} assignment Failed", FieldName, E);
    }}} public static String Getmail_host () {return mail_host;
    public static String getmail_address () {return mail_address; } public static String Getmail_passowRD () {return mail_passowrd;
    public static String Getmail_port () {return mail_port; }
}

After the basic configuration is complete, we need to develop a mail-sent Help class, under the Utils package under the Blog_common module, create a new Mailutils class, write two methods, a simple message, a send HTML message code as follows:

public static string Sendsimpleemail (string FromName, string to, string subject, string content) throws emailexception{
    String res = null;
    Simpleemail simpleemail = new Simpleemail ();
    Simpleemail.setsocketconnectiontimeout (connection_timeout);
    Simpleemail.setsockettimeout (TIMEOUT);
    Simpleemail.sethostname (Sysconfig.getmail_host ());
    Simpleemail.setauthentication (Sysconfig.getmail_address (), SYSCONFIG.GETMAIL_PASSOWRD ());
    Simpleemail.setfrom (Sysconfig.getmail_address (), fromname);
    Simpleemail.setsmtpport (Integer.parseint (Sysconfig.getmail_port ()));

    Simpleemail.addto (to);
    Simpleemail.setsubject (subject);
    Simpleemail.setmsg (content);
    res = Simpleemail.send ();
return res;
    public static string Sendhtmlemail (string FromName, string to, string subject, string content) throws emailexception{
    String res = null;
    Htmlemail htmlemail = new Htmlemail ();
    Htmlemail.setsocketconnectiontimeout (connection_timeout); Htmlemail.setsockEttimeout (TIMEOUT);
    Htmlemail.sethostname (Sysconfig.getmail_host ());
    Htmlemail.setauthentication (Sysconfig.getmail_address (), SYSCONFIG.GETMAIL_PASSOWRD ());
    Htmlemail.setfrom (Sysconfig.getmail_address (), fromname);
    Htmlemail.setsmtpport (Integer.parseint (Sysconfig.getmail_port ()));

    Htmlemail.addto (to);
    Htmlemail.setsubject (subject);  
    Htmlemail.setmsg (content);
    Htmlemail.setcharset ("Utf-8");
    res = Htmlemail.send ();
return res; }

The configuration of the message, front frame of the selection of what the basic has been completed, the next is to generate the verification code, the verification code generation is actually generated a fixed length of the random number, we provide two kinds of random number of methods, one is 0, one is not 0, the specific generation method is as follows.

public class Idgenerator {
    private static final char[] Numarr = {' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 '};
    private static final char[] Numarrnozero = {' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 '};

    private static final Random Random = new Random (); 

    

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.