Springmvc and servlet comparison

Source: Internet
Author: User

first, the servlet implements the login.

Let's take a look at the servlet to register for login.

  • <servlet>
  • <servlet-name>loginservlet</servlet-name > 3
  •       < Servlet-class>demo.servlet.loginservlet</ Servlet-class>              4
  • </servlet>
  • <servlet-mapping>
  •      <servlet-name>LoginServlet< span class= "tag" ></servlet-name>                                    2
  •       < Url-pattern>login</url-pattern >                                                          1
  • </servlet-mapping>

The access order is 1->2->3->4, where the values of 2 and 3 must be the same.

The value in the Url-pattern tag is the URL to be entered in the browser's address bar, which can be named by itself, which accesses a servlet named Servlet-name, and the value of the two Servlet-name tags must be the same because the values in the servlet tag The Servlet-name tag maps to the value in the Servlet-class tag and ultimately accesses the class in the Servlet-class tag.

Also, the/representation of Web. XML is http://localhost:8080/+ project name. Turn from (Click to open link)

1. JSP page

<form action= "Login" method = "POST" > User name: <input type= "text" name = "UserName" ><br> Secret     Code: <input type= "password" name = "password" ><br><input type= "submit" value= "Login" >

2, click the Login button, submit the form, first match the path in Web. XML, find <Url-pattern> value is Login sevlet, and then according to name to match the Servlet class, find Loginservlet.

public class Loginservlet extends HttpServlet implements Servlet {      @Override      protected void doget ( HttpServletRequest request,              HttpServletResponse response) throws Servletexception, IOException {          doPost ( request, response);      }        @Override      protected void DoPost (HttpServletRequest request,              HttpServletResponse response) throws Servletexception, IOException {          String result = "";          Gets the user name          String userName = Request.getparameter ("UserName");                 Get password          String passwd = request.getparameter ("password");                      Userdao.selectforlogin (userName, password); Find this person in the data
Request.getsession (). SetAttribute ("UserName", userName); Response.sendredirect ("login_success.jsp");
}
}

3, and then jump to the landing success page

<body>          <div align=center>              ${username} welcome you, login success!          </div>   </body>  

But there is always a need for handwritten jump servlets, which are less efficient to develop, so there are many frameworks, such as struct2,spring and so on.

Second, SPRINGMVC

Since Springmvc is a method-level interception, the SPRINGMVC approach is essentially independent, and the request response data is exclusive. It can also be seamlessly integrated with many frameworks, with high development efficiency and performance. Now many companies use SPRINGMVC to develop, our company also uses SPRINGMVC to carry on. Let me show you how SPRINGMVC can register for login.

1. JSP page (login)

<div class= "Content" >    <form action= "login.do" method= "POST" > User name: <input type= "text" Name= " UserName ">        <p> Secret &nbsp;&nbsp;&nbsp;&nbsp; code: <input type=" password "name=" password " >        <p>            <input class= "Submit" type= "submit" value= "sign in" >    </form></div>

2. Then the same matches the Web. XML

<servlet>          <servlet-name>spmvc</servlet-name>          <servlet-class> Org.springframework.web.servlet.dispatcherservlet</servlet-class>        <load-on-startup>1</ load-on-startup> </servlet><servlet-mapping>          <servlet-name>spmvc</servlet-name>          <url-pattern>*.do</url-pattern> </servlet-mapping>

The meaning of the above XML is that all actions ending with. Do have the Org.springframework.web.servlet.DispatcherServlet class. The Load-on-startup element flags whether the container loads the servlet at startup (instantiates and invokes its init () method). At this point the servlet is not initialized, but is given to the container to handle.

Spring is mainly through the Dispatcherservlet implementation of the Servlet interface, also known as the front-end controller, the request from the front end will arrive here first, it is responsible for the background to match the appropriate handler. The main work flow of Dispatcherservlet is as follows:

The front-end request arrives at Dispatcherservlet.

The front-end controller requests handlermappering to find handler.

If you find the processor that exists, go further to call service and DAO layer

Returns the result to the controller layer, renders the specific view, and returns the result to the page.

3. Then load the Sringmvc-servlet.xml configuration file.

<!--can scan controller, service 、... Here let's scan controller, specify the controller's package--><context:annotation-config></context:annotation-config>< Context:component-scan base-package= "Com.qunar.fresh2017.controller" ></context:component-scan>

4, then start scanning Controller This class, find login.do. This is the way to find out what you're looking for with annotations.

/** * When a user logs in, check the database for the presence of this person * * @param userName    entered username * @param password    The user password entered * @param httpSession set Session * @retur N Login successfully returned, otherwise login failed */@RequestMapping ("login.do") Public String Login (string userName, string password, HttpSession Httpsession,httpservletrequest Request,httpservletresponse resp) throws unsupportedencodingexception {    user user = Userdao.selectforlogin (userName, password); Find this person in the data optional<user> userpresent = Optional.of (User);    if (Userpresent.ispresent ()) {Cookie cookie = new Cookie ("nickname", Urlencoder.encode (User.getnickname (), "Utf-8"));    Cookie.setmaxage (24 * 60 * 60 * 7);    Resp.addcookie (cookie);    Request.setattribute ("nickname", User.getnickname ());    Resp.setcharacterencoding ("Utf-8"); Logger.info ("There is this person in the database");       return "Welcome";  } else {        logger.info ("There is no such person in the database"); }    return "Loginerror";}

@RequestMapping ("login.do") this annotation is an annotation in the SPRINGMVC, which shows that for login.do requests, the response is made by the method below the annotation label. Equivalent to a URL to a method.

5, finally return to login successful interface

The view parser in Spring-servlet.xml is required.

<!--view parser resolves JSP parsing by default using Jstl tag, classpath jstl package--><beanclass= " Org.springframework.web.servlet.view.InternalResourceViewResolver "><!--Configure the JSP path prefix--><property name= "prefix" value= "/"/><!--Configure the suffix of the JSP path--><property name= "suffix" value= ". JSP"/></bean>

The above code means parsing the JSP page returned by the method in the controller, prefixed with "/" for the WebApp root directory, and the configuration suffix ". jsp" to automatically add the. jsp suffix after the return value, so that the wecome.jsp under the WebApp is found.

<div class= "Welcomediv" >
Welcome:${nickname}</div>

Displays the sign-in user nickname through the El expression.

This completes the Springmvc login feature.

The spring framework is already a mainstream framework for Java Web development, and there are many advantages of this framework, and there are also shortcomings in it, which simplifies the work of developers to a certain extent than the previous servlet. Using a servlet requires every request to configure a servlet node in Web. XML, and Dispatcherservlet in spring will intercept all requests and go further to find the right processor, a front-end controller.

Here's how to use the session and cookie.

1. Session

Create a new session and add parameters.


JSP page Get session

${nickname}

Filter Get session
String nickname = (string) session.getattribute ("nickname");

2. Cookies
New Cookie
Cookie cookie = new Cookie ("nickname", Urlencoder.encode (User.getnickname (), "Utf-8")); Cookie.setmaxage (24 * 60 * 60 * 7); Resp.addcookie (cookie); Request.setattribute ("nickname", User.getnickname ()); Resp.setcharacterencoding ("Utf-8");

JSP page Get cookie value

${nickname}
Filter Get Cookie
  cookie[] cookies = servletrequest.getcookies ();        if (cookie = null) {for            (int i = 0; i < cookies.length; i++) {                if (Cookies[i].getname (). Equals ("nickname")) {                    nickname = Urldecoder.decode (Cookies[i].getvalue ());                    Break;}}}        
Transfer from https://www.cnblogs.com/haolnu/p/7294533.html

Springmvc and servlet comparison

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.