Manually Configuring Spring MVC

Source: Internet
Author: User
Tags bind tomcat server
Spring MVC is a follow-on product of springframework and has been integrated into spring Web flow. The Spring framework provides a full-featured MVC module for building WEB applications. Using the spring pluggable MVC architecture, you can choose to use a built-in spring web framework or a WEB framework such as Struts. below to lead you to a pleasant Springmvc tour. Spring MVC Core Architecture diagram: "Environment build" Spring jar package Download Official document: http://spring.io/, remove the-source.jar and-docs.jar files after downloading In my library Spring4.1.1 download: http://download.csdn.net/detail/harderxin/8310511 new Web Project Engineering SPRING-MVC, in order to prevent subsequent projects will have corresponding functionality added, So the spring core jar packages are imported into the Then also need a log jar package: Commons-logging-.jar, otherwise the project start will be error, because the persistence layer has not been introduced, so there is no hibernate or MyBatis related jar package, here is only the spring MVC related Environment building, Jar package in Project:   Configure Web. XML configuration Spring-mvc Core class: Dispatcherservlet
<?xml version= "1.0" encoding= "UTF-8"?> <web-app version= "2.5" xmlns= "Http://java.sun.com/xml/ns/javaee" Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http ://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "> <welcome-file-list> <welcome-file>index.jsp</ Welcome-file> </welcome-file-list> <!--Spring MVC configuration--<servlet> &LT;SERVLET-NAME&GT;SP Ring</servlet-name> <servlet-class>org.springframework.web.servlet.dispatcherservlet</ Servlet-class> <!--can customize the location and name of the Servlet.xml configuration file by default to the Web-inf directory with the name [<servlet-name>]- Servlet.xml, such as Spring-servlet.xml <init-param> <param-name>contextconfiglocation</param-name&gt
	        ; <param-value>/WEB-INF/spring-servlet.xml</param-value>  Default </init-param>-<load-o N-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </ Servlet-mapping> <!--spring Configuration-<listener> <listener-class>org.springframework.web.context. Contextloaderlistener</listener-class> </listener> <!--Specify the directory where the spring bean's configuration files are located. Default configuration in Web-inf directory-<context-param> <param-name>contextConfigLocation</param-name> <par
 Am-value>classpath:config/applicationcontext.xml</param-value> </context-param> </web-app>

"Configure <servlet-name>-servlet.xml": Spring defaults to loading <servlet-name>-under the Web-inf directory Servlet.xml, because we write spring, we create a new file Spring-servlet.xml file in the Web-info file directory, configure the view resolution class: Internalresourceviewresolver and note driver mappings, easy to use annotations , concise, not so many XML files
<beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:context= "http://www.springframework.org/ Schema/context "xmlns:p=" http://www.springframework.org/schema/p "xmlns:mvc=" http://www.springframework.org/ Schema/mvc "xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation="/HTTP/ Www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://w Ww.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd/HTTP  Www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd "> <!-- Resolution of the Model view name, when requested, the model view name is added to and <bean class= " Org.springframework.web.servlet.view.InternalResourceViewResolver "> <property name=" viewclass "value=" Org.springframework.web.servlet.view.JstlView "/> <property name=" prefix "value="/"/> <property name=" su Ffix "value=". jsp "/> </bEan> <!--Start the note-driven Spring MVC feature, register request URLs and annotations Pojo class method mappings--<mvc:annotation-driven/> &L t;! --Start the package scan feature to register classes with annotations such as @controller, @Service, @repository, @Component and so on as spring bean--<context:component-scan b Ase-package= "Com.xin"/> </beans>
"Add Applicationcontext.xml" In Web. XML, we configured the contextconfiglocation to configure the path of our bean, where we can add the beans we need to configure, and we can add the corresponding database connection and transaction processing, etc., so as to facilitate subsequent expansion Create a new source package, create a config package in it, create a new Applicationcontext.xml file in the package
<beans xmlns= "Http://www.springframework.org/schema/beans"
 xmlns:context= "http://www.springframework.org /schema/context "
 xmlns:p=" http://www.springframework.org/schema/p "
 xmlns:mvc="/http/ Www.springframework.org/schema/mvc "
 xmlns:xsi=" Http://www.w3.org/2001/XMLSchema-instance "
 xsi: schemalocation= "Http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/ Spring-beans-4.1.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/ Schema/context/spring-context.xsd
      HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/MVC/
      http Www.springframework.org/schema/mvc/spring-mvc-4.1.xsd ">
      <!--where we can add the beans we need to configure, You can also add appropriate database connections and transactions, and so on, to facilitate further expansion--
</beans>
"Writing Our test Files" Above we specified in the Spring-servlet.xml configuration file Driver Scan package is com.xin, so we create the corresponding package in the SRC directory, I put the test package is written in the package com.xin.test directory: welcomecontroller,spring cont Roller equivalent to struts, do control forwarding, page jump and parameter transfer function, need to add @controller annotations on it
@Controller public
class welcomecontroller{

	//Access The following method address: Http://localhost:8080/Spring-mvc/login/wuxin
	@RequestMapping (value = "/login/{user}", method = requestmethod.get) public
	Modelandview MyMethod ( HttpServletRequest request,httpservletresponse Response, 
			@PathVariable ("user") String user, Modelmap Modelmap) Throws Exception {
		modelmap.put ("message", user);
		return new Modelandview ("/hello", Modelmap);
	}
	
	Visit the following method address: Http://localhost:8080/Spring-mvc/hello
	@RequestMapping (value= "/hello1", Method=requestmethod.get Public
	String test1 () {
		return ' index ';
	}
}
"Write our view page file" Above we specified in the Spring-servlet.xml configuration file how the View layer page is displayed, prefix= '/' means the prefix is unrestricted, by default in the Webroot directory, if prefix= '/jsp/' Indicates that the view file is under the JSP directory under Webroot, suffix= ". JSP" means that the view file is of the type JSP file, which we have above for prefix= '/', suffix= ". JSP", which represents the JSP file under Webroot, in the test file above, We return a modelandview ("/hello", Modelmap) with a hello string, or return the string directly to "index"; We need to create the corresponding display page under Webroot: hello.jsp and index.jsp, which is the Spring MVC rule, Spring MVC can automatically find the corresponding display page, jump display: index.jsp page:
<%@ page language= "java" import= "java.util.*" pageencoding= "iso-8859-1"%>
<%
String Path = Request.getcontextpath ();
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";
%>

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >

Hello.jsp page: The test page that is used to receive parameters
<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <% String Path = Request.getcontextpath ()
;
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > "Test" to deploy the project to the Tomcat server, start without error, it means that our project environment to build a successful, enter the test address: Http://localhost:8080/Spring-mvc/hello: Enter the index.jsp page/HTTP/ Localhost:8080/spring-mvc/login/jack: Enter the hello.jsp page and display the value of the corresponding incoming parameter jack indicates that the project environment is set up and tested successfully!! Here's to congratulate you a little bit .... "Project directory Deconstruction"

My SPRING-MVC full project resources Download address: http://download.csdn.net/detail/harderxin/8310529 Spring-mvc In fact, there are many knowledge points, such as source code analysis, internationalization, Upload download and so on, we can study in detail, here to build a good knowledge of the environment to play a role, I hope that we can learn more in-depth, the following for everyone to introduce the controller in two ways:
Visit the following method address: Http://localhost:8080/Spring-mvc/hello
	@RequestMapping (value= "/hello1", Method=requestmethod.get Public
	String test1 () {
		return "index";
	}
Above we use annotations in the method to drive the load, requestmapping represents the request map, the value represents the method request address, methods indicate the request method, we can have get or post, the method return "index", indicating the page to jump, In fact, we will find that, and our controller in the method name does not matter, we named Test1, Test2 and so on all right, the request address only and requestmapping in the value of the relationship @RequestMapping (value= "/hello1", Method=requestmethod.get): Request address is http://localhost:8080/Spring-mvc/hello1, GET request
@RequestMapping (value= "/hello1.do", Method=requestmethod.post): Request address is http://localhost:8080/Spring-mvc/hello1.do, for POST request
	Access the following methods address: Http://localhost:8080/Spring-mvc/login/wuxin
	@RequestMapping (value = "/login/{user}", method = requestmethod.get) Public
	modelandview MyMethod (httpservletrequest request,httpservletresponse response, 
			@ Pathvariable ("user") String user1, Modelmap Modelmap) throws Exception {
		modelmap.put ("message", user1);
		return new Modelandview ("/hello", Modelmap);
	}
In the above method, we return a modelandview, which is a model view in SPRING-MVC class, can be added to the page we want to jump Modelmap parameters passed to the page, above the requestmapping value = "/ Login/{user} ", user represents a parameter variable in the method, and is a string type, @PathVariable (" user ") string user1, @PathVariable (" user ") Users in the user represents the parameter, to be consistent with the above value = "/login/{user}", while the User1 represents the parameters received by the method, the user came to the string type of the parameters of users, will be passed to the method MyMethod User1 in the method, Then the program receives the processing user access address: http://localhost:8080/Spring-mvc/login/wuxin, which indicates that the incoming parameter user is the Wuxin string and is then received by user1, stored through Modelmap, Pass to hello.jsp page receive   "Get request parameters and arguments" in struts we often use httpserveletrequest for parameter acquisition and Delivery Request.setattribute (), Request.getparameter () or using bean Auto-injection, then how to make parameter request and pass to page in Spring-mvc, there are several ways to "GET request Parameter" 1,   Getting parameters passed through @pathvariabl annotations in a path
	The following is the GET request parameter
	/**
	 * Pass parameters in the Get path through @pathvariabl annotations *
	 access to the page by Modelmap
	 * Accessing the following method address: http://localhost:8080/ Spring-mvc/hello.do/1/xin
	 * @param ID
	 * @param userName
	 * @return
	 *
	/@RequestMapping (value= "/ Hello2.do/{id}/{username} ") Public
	String test2 (@PathVariable int id, @PathVariable string userName) {
		System.out.println ("id=" +id+ ", username=" +username);
		return "Hello";
	}
2, directly with HttpServletRequest acquisition, in the method directly add HttpServletRequest parameters can be
	/**
	 * Get directly with httpservletrequest
	 * Access the following method address: http://localhost:8080/Spring-mvc/hello3.do?id=2&userName= Xin
	 * @param request
	 * @param response
	 * @return
	 *
	/@RequestMapping (value= "/hello3.do") Public
	String test3 (httpservletrequest request,httpservletresponse response) {
		int id=integer.parseint ( Request.getparameter ("id"));
		String username=request.getparameter ("UserName");
		System.out.println ("id=" +id+ ", username=" +username);
		return "Hello";
	}
3. Use annotations @requestparam bind request parameter id,username to variable Id,username
	/**
	 * Use annotations @requestparam bind request parameter id,username to variable id,username
	 * exception occurs when request parameter UserName does not exist, can be resolved by setting properties Required=false ,
	 * For example: @RequestParam (value= "UserName", Required=false), the request parameter property is userName
	 * 		String userName: The Receive Parameter property is userName
	 * Access to the following method address: Http://localhost:8080/Spring-mvc/hello4.do?id=2&userName=xin
	 * @param ID
	 * @param userName
	 * @return
	 *
	/@RequestMapping (value= "/hello4.do") public
	String test4 (@ Requestparam ("id") int ID, @RequestParam (value= "UserName", Required=false) String userName) {
		System.out.println ("id=" +id+ ", username=" +username);
		return "Hello";
	}

4, we do the project, may also involve the form submission, such as the submission of user information, we create a new user entity class:
/**
 * Package is a user class
 * @author Dell * * */Public
class User {
	
	private int id;
	Private String userName;
	
	public int getId () {
		return ID;
	}
	public void setId (int id) {
		this.id = ID;
	}
	Public String GetUserName () {
		return userName;
	}
	public void Setusername (String userName) {
		this.username = userName;
	}
}
Controller class receive processing:
	/**
	 * The following methods can be used for form submission
	 * Automatic injection of bean properties (use @modelattribute annotations to get the form form data of the POST request)
	 * Access the following method address: http://localhost : 8080/spring-mvc/hello5.do?id=2&username=xin
	 * Test found that no @modelattribute ("user") in the parameter can be automatically injected
	 * @ param user
	 * @return
	 *
	/@RequestMapping (value= "/hello5.do") public
	String Test5 (@ Modelattribute ("user") user user) {
		System.out.println ("id=" +user.getid () + ", username=" +user.getusername ());
		return "Hello";
	}

Submit a form:
  <form action= "hello5.do" method= "POST" >
    <input type= "text" name= "id"/>
	<input type= "text" Name= "UserName"/>
	<input type= "Submit" value= "Submit"/>
  </form>
You can also use address access: Http://localhost:8080/Spring-mvc/hello5.do?id=2&userName=xin The above two ways, our controller can be received. Does it feel like Spring-mvc is strong?
The Pass Parameters to page page displays ${message} or <%=request.getattribute ("message")%>
1, Modelandview data will use the HttpServletRequest attribute value to hello.jsp
	/**
	 * Modelandview data will use HttpServletRequest's attribute value to hello.jsp
	 * Access the following method address: http://localhost:8080/ Spring-mvc/hello6.do
	 *
    /@RequestMapping (value= "/hello6.do") public
	Modelandview Test6 () {
		Map <String,Object> data=new hashmap<string,object> ();
		Data.put ("message", "Test6-->xin");
		return new Modelandview ("/hello", data);
	}
2, using Modelmap as a Parameter object passed in
    /**
     * Use Modelmap as a Parameter object example:
	   modelmap data will be accessed using the attribute value of HttpServletRequest to hello.jsp in the
	        following method address:/HTTP/ Localhost:8080/spring-mvc/hello7.do
     * @return * *
    @RequestMapping (value= "/hello7.do")
    public String test7 (Modelmap map) {
    	//The following two ways can be
    	//map.addattribute ("message", "Test7-->xin");
    	Map.put ("message", "Test7-->xin");
    	return "Hello";
    }
3, if it is an object, such as user, using @modelattribute bound object, page hello.jsp get object properties: ${user}, ${user.username}
    /**
     * Use the @modelattribute example
	         to use @ on the parameter part of the Controller method or on the Bean property method
	   The Modelattribute data will be accessed using the HttpServletRequest attribute value to success.jsp in the
	       following method address: http://localhost:8080/Spring-mvc/ Hello8.do
     * @param user
     * @return
     *
    /@RequestMapping (value= "/hello8.do") public
    String Test8 (@ModelAttribute ("user") user user) {
    	user.setusername ("Test8-->xin");
    	return "Hello";
    }
4. Session Storage: You can use Httpservletreequest's GetSession () method to pass the HttpServletRequest object as a parameter, so that all the methods in the request object can be used
    /**
     * Session storage: You can use the Httpservletreequest getsession () method
     * To access the following method address: http://localhost:8080/Spring-mvc/ Hello9.do
     * @return * * *
    @RequestMapping (value= "/hello9.do") public
    String Test9 (httpservletrequest Request) {
    	Request.setattribute ("message", "Test9-->xin");
    	Request.getsession (). SetAttribute ("message", "Test9-->xin");
    	return "Hello";
    }
Note: The above GET request parameters and pass parameters to the page we can combine to use each other, receive parameters from the client, then save for logical processing, and then return the results to the user, this is our basic needs "
    @RequestMapping (value= "/hello9.do") public
    String Test9 (httpservletrequest request) {
    	string username= Request.getparameter ("UserName");
    	Request.setattribute ("message", userName);
    	Request.getsession (). SetAttribute ("message", "Test9-->xin");
    	return "Hello";
    }
"Redirect in Spring-mvc" Spring MVC defaults to forwarding to locate the view, if you want to use redirection, you can do the following: 1, using Redirectview 2, using redirect: prefix 1, using Redirectview
    @RequestMapping (value= "/hello10.do") public
	Modelandview test10 () {
		redirectview view=new redirectview (" Hello9.do ");
		return new Modelandview (view);
	}
2. Using redirect: prefix
	Common methods of work
    @RequestMapping (value= "/hello11.do") public
	String test11 () {
		return "redirect:hello9.do";  
	}
Enter Test address: http://localhost:8080/spring-mvc/hello10.do, redirect to Hello9.do method
Spring-mvc still has a lot of knowledge, the revolution is not successful, we have to continue to learn more about the strength of its framework ...

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.