Build Spring MVC under Eclipse

Source: Internet
Author: User
Tags tomcat log4j

build Spring MVC under Eclipse

One, new dynamic Web Project

A Web project is the most basic, only look at 3 places, in the root directory (this directory is generally used to call webcontent or Webroot) have:
1.webroot/web-inf/web.xml Boot file
2.webroot/web-inf/classes/the compiled class file, which establishes the subpath according to package
3.webroot/web-inf/lib/jar Package (Note that no subdirectories can be built under Lib)
This is the general comparison of the structure of the web works commonly used. With these three constructs, and then the absolute path of the Webroot to the Web container such as Tomcat, it can be started (of course, it must have something to do with it).
So although the structure of our general project is: PROJECTNAME/SRC, projectname/webroot but actually src. Java source code is completely unconcerned with Tomcat, and its parsing begins with the WebRoot. Class is what it knows. .

Reference: Build Simple Web project: spring3.0 base configuration (1)


Second, add Spring's dependency pack


Where Commons-logging-1.1.1.jar is the spring log-dependent jar pack, Jstl-api-1.2.jar and Jstl-impl-1.2.jar are Oracle's official JSTL interfaces and implementations, if you choose Apche.

When you play the war package, copy the dependencies to the Webcontent/web-inf/lib:



Third, the configuration Web.xml

Webcontent/web-inf/web.xml:

<?xml version= "1.0" encoding= "UTF-8"?> <web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://java.sun.com/xml/ns/javaee" xmlns:web= "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi: schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id= "Webapp_ ID "version=" 2.5 > <display-name>ContentManagementSystem</display-name> <!--add Spring3 Controller,  
		Dispatcherservletdispatcherservlet is the gateway to spring MVC all the request to enter the spring web has passed through Dispatcherservlet--> <servlet> <servlet-name>LoadBalanceAlg</servlet-name> <servlet-class> Org.springframework.web.servlet.dispatcherservlet</servlet-class> <load-on-startup>1</ Load-on-startup> </servlet> <!--Configure SPRING3 mapping rules--> <servlet-mapping> <servlet-name& Gt  Loadbalancealg</servlet-name> <url-pattern>*.htm</url-pattern> </servlet-mapping> <!-- Configurationlog4j--> <!--spring log4j configuration--> <context-param> <param-name>webapprootke Y</param-name> <param-value>LBAProject</param-value> </context-param> ;!
    	--the location of the log4j configuration file loaded by spring--> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/classes/log4j.conf</param-value> </context-param> <!--spring Refresh Log4
    	J configuration file interval, in units millisecond--> <context-param> <param-name>log4jRefreshIntercal</param-name>
    <param-value>60000</param-value> </context-param> <!--Web Project Spring loaded log4j listening--> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> & Lt;/listener> <!--The default jump to the root directory page--> <welcome-file-list> <welcome-file>index.htm</welcome- File> </welcoMe-file-list> <!--session timeout setup, mins--> <session-config> <session-timeout> 10</session-timeout> </session-config> </web-app>

When loading Dispatcherservlet, Spring tries to read the configuration file, the default profile is located under the same path as the Web.xml, and the filename is related to the registered servlet name: The servlet registration name follows "-servlet.xml".
For example: The above servlet registration name is LOADBALANCEALG, then the default profile name is: Loadbalancealg-servlet.xml.

Of course, you can explicitly configure the file, and you need to set initialization parameters when registering the servlet:

<init-param> 
<param-name>contextConfigLocation</param-name> 
<param-value> 
  <!--profile name--> 
</param-value> 

Reference: Configuration of Spring MVC


iv. Spring configuration Files

The filename should be consistent with the name in the <servlet-name></servlet-name> in Web.xml

<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans" Xmlns:xs I= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:p= "http://www.springframework.org/schema/p" xmlns:context= "  
	Http://www.springframework.org/schema/context "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 "> <!--turn on the Spring MVC Annotation feature to complete the mapping of request and annotation Pojo --> <bean class= "org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/> < Bean class= "Org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/> <!--Default Scan package path- -> <context:component-scan base-package= "Cn.ac.dsp.controller"/> <context:component-scan E= "Cn.ac.dsp.service"/> <!--The resolution of Model view name, that is, before and after the model add prefix--> <bean id= "Viewresolver" class= "Org.springframework.web.servlet.view.InternalResou" Rceviewresolver "> <property name=" Viewclass "><value>org.springframework.web.servlet.view.jstlview </value></property> <property name= "prefix" ><value>/web-inf/jsp/</value></
  
property> <property name= "suffix" ><value>.jsp</value></property> </bean>  </beans>

v. Configuration of log4j

Step One: Import jar packs

Step Two : The configuration in the Web.xml:

Where Webapprootkey represents the absolute path of the Web project root, and if the Webapprootkey parameter is not configured, then Webapprootkey is the default "Webapp.root" and is best set to avoid conflicting names between projects. You can then use ${lbaproject} in the log4j configuration file to represent the absolute path to the Web project directory, and ${webapp.root} to represent the absolute path to the Web project directory if Webapprootkey is not set.

Attention:

1, log4j's profile file name can not be "log4j.properties", but to change to another name, otherwise reported abnormal:
Log4j:error Setfile (null,true) call failed.
Java.io.FileNotFoundException: \web-inf\log\abc.log (the system cannot find the specified path.) )

The reason is that log4j.properties and Tomcat's log4j duplicate name, and changed names. Because in Tomcat startup is the default to find Log4j.properties, but at this time listener not up, Tomcat will go to \web-inf \log\abc.log write the log can not find.

2, ${webapp.root} represents the engineering directory, you can add it to the log4j configuration file to enter the front of the path, such as:
Log4j.appender.appender_demo. File = ${webapp.root}/web-inf/log/abc.log

3. The configuration file must be placed in the SRC directory, so that it automatically generated into the/web-inf/classes/directory. Otherwise, the Spring report exception:
Log4j:warn No Appenders could is found for logger (...).
Log4j:warn Please initialize the log4j system properly.

Step three : Create the configuration file under src log4j.conf
Log4j.conf:

Log4j.rootlogger = INFO, stdout, A1, A2 # #log message to console log4j.appender.stdout = Org.apache.log4j.ConsoleAppender
Log4j.appender.stdout.Target = System.out Log4j.appender.stdout.layout = org.apache.log4j.PatternLayout Log4j.appender.stdout.layout.ConversionPattern =%d{yyyy-mm-dd HH:mm:ss. SSS}%5p [%t]%c:%l-%m%n # #log message to file Log4j.appender.A1.Threshold = INFO log4j.appender.A1 = org.apache.log4j.
Dailyrollingfileappender Log4j.appender.A1.File = ${lbaproject}/web-inf/log/lba-info.log
Log4j.appender.A1.DatePattern = ' yyyy-mm-dd '. Log ' log4j.appender.A1.layout = Org.apache.log4j.PatternLayout Log4j.appender.A1.layout.ConversionPattern =%d{yyyy-mm-dd HH:mm:ss. SSS}%5p [%t]%c:%l-%m%n # #log warn/error to file Log4j.appender.A2.Threshold = Warn log4j.appender.A2 = Org.apache.log 4j.
Dailyrollingfileappender Log4j.appender.A2.File = ${lbaproject}/web-inf/log/lba-error.log Log4j.appender.A2.DatePattern = ' yyyy-mm-dd '. Log ' log4j.appender.A2.layout = ORG.APACHE.LOG4J.PAtternlayout Log4j.appender.A2.layout.ConversionPattern =%d{yyyy-mm-dd hh:mm:ss,sss}%5p [%t]%c:%l-%m%n 
Reference: log4j attention to the problem

Configuration log4j problem in spring

Build a simple Web project: spring3.0 basic Configuration (2)

Configure log4j to store log files into a specified directory in spring's project


six, front and back code

First, create a new JSP package under WEB-INF/JSP, corresponding to the value in prefix above (loadbalancealg-servlet.xml the directory where the View parsing module is configured), such as dboperation.jsp:

<%@ page language= "java" contenttype= "text/html; Charset=iso-8859-1 "
    pageencoding=" iso-8859-1 "%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
Write the background code under SRC (in loadbalancealg-servlet.xml configured packages), such as Dboperation.java:

Package Cn.ac.dsp.controller;

Import java.util.List;

Import Org.apache.log4j.Logger;
Import Org.springframework.stereotype.Controller;
Import org.springframework.web.bind.annotation.RequestMapping;

Import Cn.ac.dsp.dao.ResourceDAO;
Import cn.ac.dsp.entity.ResourceEntity;

@Controller public
class Dboperation {

	private final static Logger log = Logger.getlogger (Dboperation.class); c9/> @RequestMapping ("/dboperation.htm") public
	String Start () {
		log.info ("Request for Dboperation");
		list<resourceentity> resdaolist = Resourcedao.getinstance (). SelectAll ();
		for (resourceentity re:resdaolist) {
			System.out.println (Re.hashcode ());
		}
		return "Dboperation";
	}
	/**
	 * @param args */public
	static void Main (string[] args) {
		dboperation d = new dboperation (); 
  
   d.start ();
	}

  


Vii. Testing

Make the project in Eclipse a war package (note that you want to copy the dependency package to web-inf/lib), and put it under Tomcat's WebApps to start Tomcat.

The page opens in the browser as follows:



Reference: SPRING3 MVC Series One: Basic Architecture Configuration (annotated version)

Related Article

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.