Web---3 ways to create a servlet, simple user registration features

Source: Internet
Author: User
Tags getmessage uuid tomcat server
Description:

The way to create a servlet, in the previous blog, has been using Mode 1 (Implementing the Servlet Interface), followed by another 2 ways in this section.
Last blog address: http://blog.csdn.net/qq_26525215/article/details/51942252

Simple user Registration (we have set the permissions are open), you can achieve:
1, user registration.
2, query all users
3, delete the way a user creates a servlet two: Inherit Genericservlet Secondservlet.java:

Package cn.hncu.servlet.day2;

Import java.io.IOException;
Import Javax.servlet.GenericServlet;
Import Javax.servlet.ServletConfig;
Import javax.servlet.ServletException;
Import Javax.servlet.ServletRequest;


Import Javax.servlet.ServletResponse;
    Write the servlet public class Secondservlet extends genericservlet{//A small knowledge point in an inherited Genericservlet way ...
    A knowledge point in the adapter pattern: init (servletconfig config) in the adapter helps us assign the Config object in it and invoke an empty parameter init (). We should then overwrite the null parameter init ().
Because if this parameter is overridden, it cannot be implemented to assign a value to its Config object, resulting in an error in the method using the Config object (this.). In fact this method (invoking an empty parameter init () and doing nothing in the parameter method) is also a way of communicating between programmers that tells us to overwrite the null parameter so that it will call our override method//@Override//public void in It (ServletConfig config) throws servletexception {//System.out.println (config);//There is no problem, parent: init (servletconfig con
FIG) has this sentence: this.config = config;
String charset = Config.getinitparameter ("charset");
System.out.println (CharSet);
System.out.println ("init ..." +this); @Override public void Init () throws SERVLetexception {System.out.println ("init ..." +this); @Override public void Service (ServletRequest request, servletresponse response) throws Servletexcep
        tion, IOException {//string charset = This.getinitparameter ("charset");

        If this example writes the init (servletconfig config) method, overwriting the init (servletconfig config) method of the parent class, this sentence will be an exception//system.out.println (charset);
        String charset = This.getinitparameter ("charset");

        System.out.println (CharSet);
        Request.setcharacterencoding ("Utf-8");
        String name = Request.getparameter ("name");

        String pwd = request.getparameter ("pwd");
    System.out.println ("Name:" +name+ ", pwd:" +pwd);
 }
}
index.jsp:
 
Web.xml: 
<!--below is the--> of today's blog
  <servlet>
    <servlet-name>SecondServlet</servlet-name>
    <servlet-class>cn.hncu.servlet.day2.SecondServlet</servlet-class>
    <init-param>
        < param-name>charset</param-name>
        <param-value>utf-8</param-value>    
    </init-param >
  </servlet>
  <servlet-mapping>
    <servlet-name>secondservlet</servlet-name >
    <url-pattern>/second</url-pattern>
  </servlet-mapping>
Demo Results:

Fill in the name, password and then click Submit:

Look Back backstage:
How to create a servlet three: Inherit HttpServlet index.jsp:

    
Web.xml:
<servlet>
    <servlet-name>ThirdServlet</servlet-name>
    <servlet-class> cn.hncu.servlet.day2.thirdservlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ThirdServlet</servlet-name>
    <url-pattern>/third</url-pattern>   
  </servlet-mapping>
Thirdservlet.java:
Package cn.hncu.servlet.day2;

Import java.io.IOException;

Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;


Note: The 2 methods of writing Servlet,doget and Dopost with inherited HttpServlet are usually overwritten
//Otherwise, if the Doget method is not overwritten, 405 errors occur when there is a GET request, not overwriting the Dopost method in the same way Public
class Thirdservlet extends httpservlet{
    @Override
    protected void doget (HttpServletRequest req, HttpServletResponse resp)
            throws Servletexception, IOException {
        System.out.println ("Get ...");
    }

    @Override
    protected void DoPost (HttpServletRequest req, HttpServletResponse resp)
            throws Servletexception, IOException {
        System.out.println ("post");
    }


a description of the 2 methods covering Doget and Dopost:

Note: Writing Servlet,doget and Dopost in a way that inherits HttpServlet is usually overridden by 2 methods
Otherwise, if the Doget method is not overwritten, there will be a 405 error when there is a GET request, not overwriting the Dopost method.
This is caused by:
Let's look at the underlying code:
This is a constant:
public static final int sc_method_not_allowed = 405;
Because HttpServlet inherits the Genericservlet,genericservlet implements Servlet. So, when the client accesses, the first thing to look for is the parent-class servlet
namely: Service (ServletRequest req, servletresponse Res)
This method continues to be invoked: Service (request, response);
Then invoke Doget () or dopost () or other methods by this method.
If we do not cover doget () or Dopost ().
We are using the http1.1 protocol, which will call Resp.senderror (httpservletresponse.sc_method_not_allowed, msg), and there are 405 errors.

Demo Results:

We define the form submission as a post submission. The default is get simple user Registration function:

First, we need an XML to store the user's registration information;
We have created a user.xml file under the SRC folder of the project.

User.xml:
We wrote only the head of the XML, and the need for a root element

<?xml version= "1.0" encoding= "UTF-8"?>
<users>
</users>

Write a public class factory: Dom4jfactory
Everyone shared access to the same document~.
(single case) Dom4jfactory.java

Package cn.hncu.factory;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;

Import java.io.UnsupportedEncodingException;
Import org.dom4j.Document;
Import Org.dom4j.io.SAXReader;

Import Org.dom4j.io.XMLWriter;
    public class Dom4jfactory {private static Document dom = null;
    private static String path; Static block. will only run once.
            The feature is to execute the static{try{saxreader sax = new Saxreader () when the class loads;
            Learn how to load the resource path under the server (because our resources have been released from MyEclipse to the Tomcat server, so it's not the same as the original Pure Java Project)////////class loader with the current class, then get the resource path through the ClassLoader
            Path = Dom4jFactory.class.getClassLoader (). GetResource ("Users.xml"). GetPath (); 
            getClassLoader () Returns a class loader that loads the class or interface represented by this object.
            The public URL getresource (String name) returns: reads the URL object for the resource, or returns NULL if the resource is not found, or if the caller does not have sufficient permissions to obtain the resource.
            This method first searches for the parent class loader of the resource, or if the parent class loader is null, the path of the search is the path of the virtual machine's built-in ClassLoader. 
      The public String GetPath () Gets the path portion of this URL.      SYSTEM.OUT.PRINTLN (path);
        Dom = Sax.read (new FileInputStream (path));
        }catch (Exception e) {throw new RuntimeException (E.getmessage (), E);
    }/** * @return Obtain the user's document/public static document GetDocument () {return DOM; /** * For Users.xml Save, save to local/public static void Save () {try {XMLWriter w = new
            XMLWriter (new FileOutputStream (path));
            W.write (DOM);
        W.close ();
        catch (Unsupportedencodingexception e) {throw new RuntimeException (E.getmessage (), E);
        catch (FileNotFoundException e) {throw new RuntimeException (E.getmessage (), E);
        catch (IOException e) {throw new RuntimeException (E.getmessage (), E); }/** * Test with * @param args/public static void main (string[] args) {System.out.prin
    TLN (GetDocument ());
 }

}
index.jsp:
 
Web.xml: 
<servlet>
    <servlet-name>RegServlet</servlet-name>
    <servlet-class> cn.hncu.servlet.day2.regservlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>RegServlet</servlet-name>
    <url-pattern>/reg</url-pattern>     
  </ Servlet-mapping>
  <servlet> <description>this is the description's my
    Java EE component</ Description>
    <display-name>this is the display name of my Java EE component</display-name>
    < servlet-name>delservlet</servlet-name>
  </servlet>
   <servlet-mapping>
    < servlet-name>delservlet</servlet-name>
    <url-pattern>/del</url-pattern>
  </ Servlet-mapping>
Regservlet.java: User registration:
Package cn.hncu.servlet.day2;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import java.util.List;

Import Java.util.UUID;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;
Import org.dom4j.Document;
Import org.dom4j.Element;

Import Org.dom4j.Node;

Import Cn.hncu.factory.Dom4jFactory; public class Regservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse Respo
        NSE) throws Servletexception, IOException {response.setcontenttype ("text/html;charset=utf-8");
        PrintWriter out = Response.getwriter ();
        Document dom = Dom4jfactory.getdocument ();
        Get all user information list<element> users = dom.selectnodes ("//user");
        Out.print ("

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.