快速搭建一个java config(无web.xml)的web工程(一)

阅读更多

 

1、新建一个maven 工程;

 

2、pom.xml文件引入jar包,并配置failOnMissingWebXml 


	4.0.0
	com.huatech
	1.0.0
	web-demo
	war
	web-demo

	
		
			org.springframework
			spring-webmvc
			4.2.5.RELEASE
		
		
			javax.servlet
			javax.servlet-api
			3.0.1
			provided
		
	


	
		${project.artifactId}
		
			  
	            org.apache.maven.plugins  
	            maven-war-plugin  
	            2.6  
	              
	                false  
	              
	          
	       
			
				org.apache.maven.plugins
				maven-compiler-plugin
				3.6.0
				
					1.7
					1.7
					UTF-8
					-Xlint:all
					true
					true
				
			
			
			
		
	

 

3、以java config方式设置spring mvc; 

package com.huatech.support;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.servlet.DispatcherServlet;

public class SimpleWebApplicationInitializer implements WebApplicationInitializer {

	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		ServletRegistration.Dynamic registration = servletContext.addServlet("huatech", new DispatcherServlet());
        registration.setLoadOnStartup(1);
        registration.setInitParameter("contextConfigLocation", "classpath:huatech-servlet.xml");
        registration.addMapping("/");
	}
	
} 

WebApplicationInitializer是Spring MVC提供的接口,可以确保基于代码的配置被探测到、且被自动用于初始化Servlet 3 容器。该接口的一个abstract基类是AbstractAnnotationConfigDispatcherServletInitializer,该abstract基类注册DispatcherServlet更简便,只需要指定映射、列出配置类即可。 

 

 

4、配置huatech-servlet.xml





	
	

	
	
	
		
		
	

 

5、编写一个IndexController

package com.huatech.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class IndexController {

	@RequestMapping(value="/index")
	public String index(){		
		return "index";
	}
	
}

 

6、在WEB-INF下新建一个index.jsp文件

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




首页




	首页

 

附件为demo代码

  • web-demo.zip (5.3 KB)
  • 下载次数: 0

你可能感兴趣的:(java,web)