晨曦 2011-02-15
控制器java代码
package springapp.web; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; //声明为servlet控制器 @Controller public class HelloWorld { //访问地址为</hellowor.htm?name=aaaaaaaaa》,@RequestParam("name") String username为接收的参数 @RequestMapping("/hellowor") public String hi(HttpServletRequest request, @RequestParam("name") String username) { System.out.println(username); //设置request范围变量,页面可以获取 request.setAttribute("now", "fdsafdsfdsfdsfds"); //跳转到WEB-INF/hello.jsp页面 return "WEB-INF/hello"; } //访问地址为</hii.htm,htm在web.xml中的配置 @RequestMapping("/hii") public String hii() { //跳转到/hello.jsp页面,路径配置在springapp-servlet.xml配置路径地址的前缀和后缀 /*<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsp"/>*/ return "hello"; } }
mvc拦截器java代码
package springapp.web; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; //定义拦截器 public class MyInterceptor implements HandlerInterceptor { public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { System.out.println("视图已处理完后执行的方法,通常用于释放资源;"); } public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { System.out.println("控制器的方法已经执行完毕,转换成视图之前的处理;"); } public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception { System.out .println("拦截器的前端,执行控制器之前所要处理的方法,通常用于权限控制、日志,其中,Object arg2表示下一个拦截器;"); return true; } }
jsp代码
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Insert title here</title> </head> <body> <h1>Hello - Spring Application</h1> <p>Greetings.WEBINF</p> <%=request.getAttribute("now") %> <h1><fmt:message key="spring.hello"/></h1> </body> </html>