How to watch the annual salary of 50W architect handwriting a framework SpringMVC

Foreword

Java Web development you do, SpringMVC must have heard the name, as is now the most widely used Java frameworks, which so far remains a strong vitality and broad user base.

This article describes how to build the minimum system SpringMVC with eclipse step by step, so-called minimum system is enough to make the project under the framework of SpringMVC successful run, and can do some simple things (such as page visits) system.

Before you begin, so that we would like to ask a few questions to think about:

  • Why handwriting SpringMVC?
  • How handwriting a SpringMVC?
  • Handwritten SpringMVC can really run up?

let's start.

Other environment:
Operating System: Windos 10
Tomcat: v7.0
the JDK: 1.7

text

1. Create a new project

image

We use eclipse new project, select Dynamic Web Project(dynamic Web project).

Click onNext

image

Project nameWritten on the inside springmvc, which is the name of our project, other do not change, just click Finish.

OK, the project is built.

The next item is sure to change the character setUTF-8

Right Projectproperties

Instead UTF-8, click OK.

2. Write web.xml

When we open the WebContent/WEB-INFcatalog, I found there is only a lib directory, this is the place to store a variety of jar package. We know that a web project must have a web.xmlfile job.

Since there is no, we wrote a cough.

Right WEB-INF- new- filecreate a new web.xmlfile.

Click onFinish

The following can be filled into it.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
            xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
            xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" 
            id="WebApp_ID">

<! - This is the name of the project ->
<display-name>springmvc</display-name>

</web-app>

 

This completes the basic configuration, I mean, now that the project is already a standard web project.

3. Verify that the project to build a successful web

In order to verify the correctness so far, we are in WebContentthe following directory to create a new jspfile.

Name is calledindex.jsp

It reads as follows:

. 1 <% @ Page Language = "Java" contentType = "text / HTML; charset = UTF-. 8" the pageEncoding = "UTF-. 8"%>
 2 <HTML>
 . 3      <head>
 . 4          <Meta charset = "UTF-. 8" />
 5      </ head>
 6      <body>
 7          Congratulations, web projects have been successfully set up!
. 8      </ body>
 . 9 </ HTML>

 

We will now be deployed to this project Tomcat, to verify that you can run up.

Right on the project Debug As- -Debug on Server

Just clickFinish

Over time, the console began to print log information, when we see this information when the description Tomcathas started finished.

Let's open the browser, enter the following information in the address bar

http://localhost:8088/springmvc/index.jsp

I Tomcat port number on the computer configuration is 8088, depending on your own Tomcatdecision, possibly 8080so on.

Visible, able to successfully access the page, and this shows us so far it is correct.

4. IntegrationSpringMVC

We web.xmladd the following configuration file inside

4.1 Configuration Listener

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<listener>
    <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>

 

4.2 configure the filter to solve POSTthe garbage problem

<filter>
    <filter-name>encoding</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>
</filter>

<filter-mapping>
    <filter-name>encoding</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

 

4.3 Configuring SpringMVCdistributor, intercepts all requests

<servlet>
    <servlet-name>springmvc</servlet-name>
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>namespace</param-name>
        <param-value>dispatcher-servlet</param-value>
    </init-param>
</servlet>

<servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
 </servlet-mapping>

 

In this configuration, we require the DispatcherServletassociated XML file name is called dispatcher-servlet.

Note that the path is relative to where web.xmlit is, that is, this file is also WEB-INFthe root directory.

So, we need to WEB-INFcreate a new root directory of the dispatcher-servlet.xmlfile.

image

So far, web.xmlthe preparation of documents came to an end.

Write 4.4dispatcher-servlet.xml

dispatcher-servlet.xmlThe effect is to configure SpringMVCthe distributor.

Configuration is as follows:

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util" 
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/util 
       http://www.springframework.org/schema/util/spring-util-3.0.xsd 
       http://www.springframework.org/schema/mvc 
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
      ">

      <! - turn on annotation mode driver -> 
       <mvc:annotation-driven></mvc:annotation-driven>
      <! - package sweeping ->
      <context:component-scan base-package="com.springmvc.*"></context:component-scan>
      <-! Static resource filter ->
         <mvc:resources location="/resources/" mapping="/resources/**"/>

         <-! View rendering jsp / freemaker / velocity ->
         <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <! - page stored in the development path ->
            <property name="prefix" value="/WEB-INF/pages"></property>
            <! - file extension ->
            <property name="suffix" value=".jsp"></property>
         </bean> 

</beans>

 

Depending on the configuration, there are three places that need attention.

  1. It scans com.springmvcthe lower cladding all Java classes, but those who encountered annotated, such as @Controller, , @Service, @Autowiredwill be added to the Spring of them beaninside the factory to go.
  2. All static resource files, for example js, css, imagesneed to be placed /resourcesin the directory, the directory now we have not built.
  3. All display pages, such as jsp files need to be placed in /WEB-INF/pagesthe directory, the directory now we do not build.
    OK, we add the corresponding directory.

The first is the Javacatalog file.

We are in the right place, to create a new compackage, in which to build a springmvcpackage, or use .built along the way.

Click onFinish

According to SpringMVCthe stratification, we springmvcbuilt three packages below package, namely controller, service,dao

In this case, when we project once started, springmvcit will scan these three packages, but there will be those who have annotated classes are extracted together into the Springcontainer (or Springthe beanfactory), by means of Springcontainer unified management. That is, you never go to a new Controllercause.

Next, we build a directory of static resources.

In WebContenta new directory resourcesfolder.

Then by the way js, css, imgthe folders are built look, here we store static resource files.

Finally, we WEB-INFbuild a directory pagesfolder as a storage directory display page.

The previous index.jspcopy come.

This configuration is almost the same.

The leader packet and verification

We will jarpack into the libdirectory:

Then start the project, verify constructed so far is correct.

Open Serversview, click on the image is the same as the beetle icon.

Discovered the error, the error message is as follows:

error:
Could not open ServletContext resource [/WEB-INF/applicationContext.xml]

It says we're WEB-INFbelow one less applicationContext.xmlthis document, the original, we have less of the SpringBeanconfiguration of the plant, it means is that we have to look at the provisions, in Springtime to start the vessel, and what we need to reload?

So, we put applicationContext.xmltogether.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
  http://www.springframework.org/schema/beans/spring-beans.xsd  
  http://www.springframework.org/schema/aop   
  http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
  http://www.springframework.org/schema/tx   
  http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
  http://www.springframework.org/schema/context   
  http://www.springframework.org/schema/context/spring-context-4.0.xsd
  http://www.springframework.org/schema/util   
  http://www.springframework.org/schema/util/spring-util-4.0.xsd
  ">

</beans>

 

Inside us what is not configured to start again Tomcat.

This time is not being given.

6. ConfigureViewController

We know that WEB-INFany resource directory is not directly a browser urlto access the address, to ensure safety. This is also the reason why we put pages in the catalog on.

For differentiated, we also set up a separate pagesfolder, these pages will be saved.

Now, in order to access this page, we need to use SpringMVCthe page jump mechanism.

We Controllercreate a new package underViewController

Click onFinish

ViewController Code:

package com.springmvc.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class ViewController {

    @RequestMapping("/view")
    public ModelAndView view(HttpServletRequest request){
        String path = request.getParameter("path") + "";
        ModelAndView mav = new ModelAndView ();
        mav.setViewName(path);
        return mav;
    }
}

 

I just need to want to visit a page on the pathinside, by urlpass came on the line.

Because adding a javaclass, so we re-start Tomcat.

After startup, in the address bar:
HTTP: // localhost:? 8088 / SpringMVC / View index path =

result:

Never mind, we see him report what is wrong.

message /springmvc/WEB-INF/pagesindex.jsp

pagesindex.jspWhat the hell? ?

It turned out dispatcher-servlet.xml, we wrote a little "/"

Add the herd.

After saving, since modified the XMLconfiguration file, so we need to be restarted Tomcat.

After startup, continue!

Success.

7. introduction of static resources

For example, I resources/imgdelegated a picture catalog, how to introduce into index.jspit?

background : url(http://localhost:8088/springmvc/resources/img/bg.jpg);
background-size : 100% 100%;

Indeed, this is one way. However, it has a drawback is that the root path to write the dead, and we certainly do not want that.

In fact, we can viewControllerget the project root path inside, and then passed to the jsppage on OK.

We debugging information "Congratulations, web projects have been successfully set up!" Deleted.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
    <head>
        <meta charset="UTF-8" />
    </head>

    <style>
        body {
            background : url(${contextPath}/resources/img/bg.jpg);
            background-size : 100% 100%;
        }
    </style>
    <body>

    </body>
</html>

 

${contextPath}May be taken to Controllerpass over the contextPathvalue.

Success!

Access to information

The free for everyone to recommend a study group, which summarized Java Architecture / Distributed / Micro Services / docker / high concurrency and high performance interviews resources.
Java program to ape architecture interested are welcome to join the group Q: 790,047,143 , whether you are newly recruited Daniel, I was still welcome, there is a large cattle finishing a highly efficient route learning and tutorials to share with you for free, at the same time every day update videos.
Finally, I wish you all soon learn something.

Guess you like

Origin www.cnblogs.com/ourtest/p/11163947.html