Spring Web MVC 入门实例

今天学习了Spring的MVC.根据 http://dev.yesky.com/238/2599738.shtml做了个例子. Spring 的web MVC 框架中担任前端控制器叫色的是org.springframework.web.servlet.DispatcherServlet,DispatcherServlet负责将客户的请求分配给控制对象,所以使用Spring Web MVC的第一步,就是在web.xml中定义DispatcherServlet;

web.xml





	

		ntx

		

			org.springframework.web.servlet.DispatcherServlet

		

		

		contextConfigLocation

		/WEB-INF/ntx.xml

		

		2

	

	

		ntx

		*.do

	

	

		index.jsp

	

在web.xml中定义了一个DispatcherServlet的实例ntx,从设定中可以看到,所有连接至*.do结尾的请求都会由它来处理,"contextConfigLocation"初始化参数用来设定Bean定义文件的
位置与名称,如果不设置,则DispatcherServlet默认会使用Servlet的名称为前置,读取"Servlet 名称_servlet.xml"作为其Bean定义文件,在上面的设定中则读取nxt.xml中的定            义。
DispatcherServlet负责分配请求至控制对象(Controller),在Spring Eeb MVC框架中,控制对象要实现org.springframework.web.servlet.mvc.Controller接口,Controller接口有一个必须实现的handleRequest()方法,其定义如下:
package com.wisetop.controller;



import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.mvc.Controller;

import com.wisetop.service.LoginService;

public class LoginController implements Controller {

	private LoginService loginService;

	private String gotoUrl;

	public ModelAndView handleRequest(HttpServletRequest request,

			HttpServletResponse response) throws Exception {

		String userName = request.getParameter("userName");

		this.getUserInfo(request, userName);

		return new ModelAndView(this.getGotoUrl());



	}

	private void getUserInfo(HttpServletRequest request, String |userName) {

		String userInfo = this.getLoginService().getUserInfo (userName);

		request.setAttribute("userInfo", userInfo);

	}



	public String getGotoUrl() {

		return gotoUrl;

	}



	public void setGotoUrl(String gotoUrl) {

		this.gotoUrl = gotoUrl;

	}



	public LoginService getLoginService() {

		return loginService;

	}

	public void setLoginService(LoginService loginService) {

		this.loginService = loginService;

	}

}
其他两个相关的接口和类定义如下:
package com.wisetop.service;

public interface LoginService {

	public String getUserInfo(String userName);

}



package com.wisetop.serviceimpl;

import com.wisetop.service.LoginService;

public class LoginServiceImpl implements LoginService {

	public String getUserInfo(String userName) {

		return "你的名字是" + userName;

	}



}
Bean文件定义如下:










	

	

		

			

		

		

			/showResult.jsp

		

	

	

		

			

				loginController

			

		

	

测试页面:
index.jsp

<%@ page language="java" pageEncoding="UTF-8"%> 



 

	

	

	    

	

	

	



 

  








showResult.jsp

<%@ page language="java" pageEncoding="UTF-8"%> 



 

	

	

	    

	

	

	



  

  



<% 

String a=(String)request.getAttribute("userInfo");

%>

<%=a%>



你可能感兴趣的:(Hibernate,spring,mvc,web,string,stylesheet,bean)