Build a web App with maven (bottom)

Source: Internet
Author: User
Tags getmessage http post

The implementation details have been encapsulated in the Account-service, so the next step is to provide the Web page on this basis and use the simple servlet,jsp to control the background interactively. The following is the composition of the Account-web module:

    • Pom section
<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" >< Modelversion>4.0.0</modelversion><parent><groupid>com.juvenxu.mvnbook.account</groupid ><artifactid>account-parent</artifactid><version>1.0.0-snapshot</version></ Parent><artifactid>account-web</artifactid><packaging>war</packaging><name> Account web</name><dependencies><dependency><groupid>${project.groupid}</groupid> <artifactid>account-service</artifactid><version>${project.version}</version></ dependency><dependency><groupid>javax.servlet</groupid><artifactid>servlet-api</ artifactid><version>2.5</version><scope>test</scope></dependency>< Dependency><groupid>javax.servlet.jsp</groupid><artifactid>jsp-api</artifactid><version>2.1</version>< Scope>test</scope></dependency><dependency><groupid>org.springframework</groupid ><artifactid>spring-web</artifactid><version>4.1.7.release</version></dependency ></dependencies></project>
In the code above, Account-web's packaging element value is war, which means that this is a Web project that needs to be packaged in a war manner. Account-web relies on packages that are dependent on both SERVLET-API and JSP-API for almost all Web projects, and they support the authoring of Servlets and JSPs. The dependencies here are provided, which means they will not be packaged into the war, because almost all web containers provide these two class libraries, and if repeated occurrences in the war package, they can cause dependency conflicts and so on. Account-web also relies on Account-service and Spring-web, the former providing underlying support for Web applications, which provides spring integration support for Web applications.
In some Web projects, there may be finalname configurations. This element is used to identify the main component name that the project generates, and the default value is set in the Super Pom with a value of ${project.artifactid}-${project.version}. We can modify the main component name to account through the configuration of <finalName>account</finalName>, then the war package name generated by the project becomes Account.war, which makes it easier to deploy.
    • Main code Section
The main code contains 2 JSP pages and 4 Servlets, respectively:
    1. SIGNUP.JSP: Account Registration page
    2. LOGIN.JSP: Account Landing Page
    3. Captchaimageservlet: servlet that generates a CAPTCHA picture
    4. Loginservlet: Processing Account Registration Requests
    5. Activateservlet: Process account activation
    6. Loginservlet
First, however, you configure the servlet in Web. XML, which is located in the src/main/webapp/web-inf/directory. The configuration is as follows://web.xml
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE Web-app Public "-//sun Microsystems, INC.//DTD Web Application 2.3//en" "Http://java.sun.com/dtd/web-app_2_3. DTD "><web-app><display-name>account service</display-name><context-param>< param-name>contextconfiglocation</param-name><param-value>classpath:/ Account-persist.xmlclasspath:/account-captcha.xmlclasspath:/account-email.xmlclasspath:/account-service.xml </param-value></context-param><listener><listener-class> Org.springframework.web.context.contextloaderlistener</listener-class></listener><servlet> <servlet-name>CaptchaImageServlet</servlet-name><servlet-class> com.juvenxu.mvnbook.account.web.captchaimageservlet</servlet-class></servlet><servlet>< Servlet-name>activateservlet</servlet-name><servlet-class> com.juvenxu.mvnbook.account.web.activateservlet</servlet-class></servlet><Servlet><servlet-name>loginservlet</servlet-name><servlet-class> com.juvenxu.mvnbook.account.web.loginservlet</servlet-class></servlet><servlet>< Servlet-name>signupservlet</servlet-name><servlet-class> com.juvenxu.mvnbook.account.web.signupservlet</servlet-class></servlet><servlet-mapping>< Servlet-name>captchaimageservlet</servlet-name><url-pattern>/captcha_image</url-pattern> </servlet-mapping><servlet-mapping><servlet-name>SignUpServlet</servlet-name>< Url-pattern>/signup</url-pattern></servlet-mapping><servlet-mapping><servlet-name> Activateservlet</servlet-name><url-pattern>/activate</url-pattern></servlet-mapping> <servlet-mapping><servlet-name>loginservlet</servlet-name><url-pattern>/login</ Url-pattern></servlet-mapping></web-app>
The Web. XML first configures the display name of the website project, followed by a servletlistener named Contextloaderlistener. The listener comes from Spring-web, which is used to launch the spring IOC container for the Web project, thus implementing the bean injection. A caontext-param named Contextconfiglocation is used for the location of the specified spring configuration file. The value here is the spring configuration XML file for four modules, such as Classpath:/account-persist.xml for a file named Account-persist.xml from the root path of classpath. We know that the Account-persist.xml file is under the root path of the Account-persist module after it is packaged, and this jar file is introduced to Account-web Classpath in a way that relies on it. The remainder of Web. XML is a servlet, including the name of each servlet, the class name, and the corresponding URL pattern.
The following builds the view file signup.jsp file to display the Account registration page, which is stored in the src/main/webapp/directory.
<%@ page language= "java" pageencoding= "UTF-8" contenttype= "text/html"; Charset=utf-8 "%><%@ pageimport=" Org.springframework.web.context.support.WebApplicationContextUtils "%> <%@ page import= "org.springframework.web.context.WebApplicationContext"%><%@ page import= " Org.springframework.context.ApplicationContext "%><%@ page import=" com.juvenxu.mvnbook.account.service.* "% ><%string path = Request.getcontextpath (); String basepath = request.getscheme () + "://" + request.getservername () + ":" + request.getserverport () + path + "/";%&GT;&L t;! DOCTYPE html>The above JSP uses the/captcha_image resource to obtain a CAPTCHA image. According to Web. XML, this resource corresponds to Captchaimageservlet, and all servlets are placed under the src/main/java/directory with the following code://captchaimageservlet.java
Package Com.juvenxu.mvnbook.account.web;import Java.io.ioexception;import Java.io.outputstream;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.springframework.context.applicationcontext;import Org.springframework.web.context.support.webapplicationcontextutils;import Com.juvenxu.mvnbook.account.service.accountservice;import com.juvenxu.mvnbook.account.service.AccountServiceException; @SuppressWarnings ("Serial") public class Captchaimageservlet extends HttpServlet {private ApplicationContext context;//Spring applicationcontext@override/** * First initialize applicationcontext */public void init () throws Servletexception {Super.init (); context = Webapplicationcontextutils.getwebapplicationcontext (Getservletcontext ());} public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {// Gets the key parameter string key = Request.getparameter ("Key ");//Check if key is empty if (key = = NULL | | key.length () = = 0) {//return HTTP400 error, request illegal response.senderror (" No Captcha key Found ");} else {//Get spring bean and force type conversion Accountservice service = (accountservice) context.getbean ("Accountservice"); try {// Set the response format to Image/jpegresponse.setcontenttype ("Image/jpeg");//writes the resulting byte stream to the output stream of the servlet outputstream out = Response.getoutputstream (); Out.write (Service.generatecaptchaimage (key)); Out.close ();} catch (Accountserviceexception e) {response.senderror (+, E.getmessage ());}}} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { This.doget (request, Response);}}
And the action of form form in signup.jsp is signup, according to Web. XML corresponds to Signupservlet, the code is as follows://signupservlet.java
Package Com.juvenxu.mvnbook.account.web;import Java.io.ioexception;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.springframework.context.applicationcontext;import Org.springframework.web.context.support.webapplicationcontextutils;import Com.juvenxu.mvnbook.account.service.accountservice;import Com.juvenxu.mvnbook.account.service.accountserviceexception;import Com.juvenxu.mvnbook.account.service.SignUpRequest, @SuppressWarnings ("Serial") public class Signupservlet extends HttpServlet {private ApplicationContext context;//used to get spring bean@override/** * First initialize applicationcontext */public void I NIT () throws Servletexception {Super.init (); context = Webapplicationcontextutils.getwebapplicationcontext ( Getservletcontext ());} @Overrideprotected void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException { Get an HTTP POST request, read the ID in the form, mailbox, username, password, confirm password, verify primary key, verify value parameter string id = req.getparameter ("id"); String email = req.getparameter ("email"); String name = Req.getparameter ("name"); String Password = req.getparameter ("password"); String ConfirmPassword = Req.getparameter ("Confirm_password"); String Captchakey = Req.getparameter ("Captcha_key");  String Captchavalue = Req.getparameter ("Captcha_value");//Determine whether the parameters are empty, the return error if the existence of NULL value if (id = = NULL | | id.length () = = 0 | | email = = Null| | Email.length () = = 0 | | Name = = NULL | | Name.length () = = 0| | Password = = NULL | | Password.length () = = 0| | ConfirmPassword = = NULL | | Confirmpassword.length () = = 0| | Captchakey = = NULL | | Captchakey.length () = = 0| | Captchavalue = = NULL | | Captchavalue.length () = = 0) {resp.senderror, "Parameter incomplete."); return;} Get Beanaccountservice service = (accountservice) context.getbean ("Accountservice") named Accountservice;// Initializes a signuprequest instance and sets its properties signuprequest request = new Signuprequest (); Request.setid (ID); request.setemail (email); Request.setname (name); Request.sEtpassword (password); Request.setconfirmpassword (ConfirmPassword); Request.setcaptchakey (Captchakey); Request.setcaptchavalue (Captchavalue); Request.setactivateserviceurl (Getservletcontext (). GetRealPath ("/") + " Activate "); Send account activation email address, here is the address of activateservlet//Use Accountservice registered user try {service.signup (request); Resp.getwriter (). Print (" Account was created, please check your mail box for activation link. "); catch (Accountserviceexception e) {resp.senderror (+, E.getmessage ()); return;}}}
Here again to use the Activateservlet, the code is as follows://activateservlet
Package Com.juvenxu.mvnbook.account.web;import Java.io.ioexception;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.springframework.context.applicationcontext;import Org.springframework.web.context.support.webapplicationcontextutils;import Com.juvenxu.mvnbook.account.service.accountservice;import com.juvenxu.mvnbook.account.service.AccountServiceException; @SuppressWarnings ("Serial") public class Activateservlet extends HttpServlet {private applicationcontext context; @Overridepublic void Init () throws servletexception {super.init (); context = Webapplicationcontextutils.getwebapplicationcontext (GetServletContext ()) ;} @Overrideprotected void Doget (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {  String key = Req.getparameter ("key");//Determine if the activation code is empty if (key = = NULL | | key.length () = = 0) {resp.senderror, "No activation Key provideD. "); return;} Accountservice service = (accountservice) context.getbean ("Accountservice");//Activate account try {service.activate (key); Resp.getwriter (). Write ("account was activated, now can login."); catch (Accountserviceexception e) {resp.senderror ("Unable to activate account"); return;}}
The above is the registration page and the implementation of related logic processing. Another page is login.jsp, which is responsible for handling logins.
<%@ page contenttype= "text/html; Charset=utf-8 "language=" java "%>
The action of the form is Login,loginservlet code as follows://loginservlet.java
Package Com.juvenxu.mvnbook.account.web;import Java.io.ioexception;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.springframework.context.applicationcontext;import Org.springframework.web.context.support.webapplicationcontextutils;import Com.juvenxu.mvnbook.account.service.accountservice;import Com.juvenxu.mvnbook.account.service.AccountServiceException, @SuppressWarnings ("Serial") public class Loginservlet Extends HttpServlet {private applicationcontext context; @Overridepublic void Init () throws Servletexception {Super.init (); context = Webapplicationcontextutils.getwebapplicationcontext (Getservletcontext ());} @Overrideprotected void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException { String id = req.getparameter ("id"); String Password = req.getparameter ("password"); if (id = = NULL | | id.length () = = 0 | | password = NULL|| Password.length () = = 0) {resp.senderror ("incomplete parameter"); return;} Accountservice service = (accountservice) context.getbean ("Accountservice"); try {service.login (ID, password); Resp.getwriter (). Print ("Login successful!"); catch (Accountserviceexception e) {resp.senderror (+, E.getmessage ());}}}
Because the code format and content are very similar to the above, the annotations are omitted here, and most of the code can refer to Signupservlet.
Finally in the src/main/resources/directory to establish a configuration file, Account-service.properties, specific configuration see the configuration of the previous mailbox, such as the following//account.service.properties
Email.protocol=smtpemail.host=localhostemail.port=25[email Protected]email.password=123456email.auth=true[email Protected]persist.file=c\:/persist-data.xml



Such a MAVEN Web project was built. Executing mvn clean Install on the Account-web directory, the project's war package is packaged on the local repository.
Reference book: The 12th chapter of Maven Combat-Xu Xiaobin

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Build a web App with maven (bottom)

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.