Spring Mvc @RequestMapping 详解

ぃ、小莉子 提交于 2019-12-09 02:21:40

1.项目清单


2.中间层配置

package cn.test;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import cn.test.LoginService;
 
import entity.User;
 
@Controller  //类似Struts的Action
public class TestController {
 
    @RequestMapping("/test/login.do")  // 请求url地址映射,类似Struts的action-mapping
    public String testLogin(@RequestParam(value="username")String username, String password, HttpServletRequest request,HttpServletResponse response) {
        // @RequestParam是指请求url地址映射中必须含有的参数(除非属性required=false)
        // @RequestParam可简写为:@RequestParam("username")
             System.out.println(username);
        if (!"admin".equals(username) || !"admin".equals(password)) {
            return "loginError"; // 跳转页面路径(默认为转发),该路径不需要包含spring-servlet配置文件中配置的前缀和后缀
        }
        return "loginSuccess";
    }
 
    @RequestMapping("/test/login2.do")
    public ModelAndView testLogin2(String username, String password, int age){
        // request和response不必非要出现在方法中,如果用不上的话可以去掉
        // 参数的名称是与页面控件的name相匹配,参数类型会自动被转换
        if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {
            return new ModelAndView("loginError"); // 手动实例化ModelAndView完成跳转页面(转发),效果等同于上面的方法返回字符串
        }
        return new ModelAndView(new RedirectView("../index.jsp"));  // 采用重定向方式跳转页面
        // 重定向还有一种简单写法
        // return new ModelAndView("redirect:../index.jsp");
    }
 
    @RequestMapping("/test/login3.do")
    public ModelAndView testLogin3(User user) {
        // 同样支持参数为表单对象,类似于Struts的ActionForm,User不需要任何配置,直接写即可
    	// 还有一点区别就是在页面上,Struts在页面上要写user.username但是在此处不需要,直接写上username即可
        String username = user.getUsername();
        String password = user.getPassword();
        int age = user.getAge();
         System.out.println(username);
        if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {
            return new ModelAndView("loginError");
        }
        return new ModelAndView("loginSuccess");
    }
 
    @Resource(type=LoginService.class)  // 获取applicationContext.xml中bean的id为loginService的,并注入
    private LoginService loginService;  //等价于spring传统注入方式写get和set方法,这样的好处是简洁工整,省去了不必要得代码
 
    @RequestMapping("/test/login4.do")
    public String testLogin4(User user) {
        if (loginService.login(user) == false) {
            return "loginError";
        }
        return "loginSuccess";
    }
}
package cn.test;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
 
@Controller
@RequestMapping("/test2/login.do")  // 指定唯一一个*.do请求关联到该Controller
public class TestController2 {
     
    @RequestMapping
    public String testLogin(String username, String password, int age) {
        // 如果不加任何参数,则在请求/test2/login.do时,便默认执行该方法
         
        if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {
            return "loginError";
        }
        return "loginSuccess";
    }
 
    @RequestMapping(params = "method=1", method=RequestMethod.POST)
    public String testLogin2(String username, String password) {
        // 依据params的参数method的值来区分不同的调用方法
        // 可以指定页面请求方式的类型,默认为get请求
         
        if (!"admin".equals(username) || !"admin".equals(password)) {
            return "loginError";
        }
        return "loginSuccess";
    }
     
    @RequestMapping(params = "method=2")
    public String testLogin3(String username, @RequestParam(required=false)String password, @RequestParam(required=false)int age) {
    	System.err.println(username);
        if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {
            return "loginError";
        }
        return "loginSuccess";
    }
}
package cn.test;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
 
@Controller
@RequestMapping("/test3/*")  // 父request请求url
public class TestController3 {
 
    @RequestMapping("login.do")  // 子request请求url,拼接后等价于/test3/login.do
    public String testLogin(String username, @RequestParam(required=false)String password, @RequestParam(required=false)Integer age) {
    	//如果上面的参数age是int类型的原始类型,在传值为null,会出现异常,要将其改为包装类型;
    	System.out.println(username);
        if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {
            return "loginError";
        }
        return "loginSuccess";
    }
}
package cn.test;

import org.springframework.stereotype.Component;

import entity.User;
@Component(value="LoginService")
public class LoginService {
private String userName;
private String passWord;
public String getUserName() {
	return userName;
}
public void setUserName(String userName) {
	this.userName = userName;
}
public String getPassWord() {
	return passWord;
}
public void setPassWord(String passWord) {
	this.passWord = passWord;
}
public LoginService() {
}
public boolean login(User user) {
	System.out.println("LoginService login...");
	return false;
}
public void say(){
	System.out.println("LoginService init...");
}
}
package cn.test;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@Scope("prototype")
public class FindEmpController {
	@RequestMapping("/findEmp.do")
	public String load() {
		System.out.println("null");
		return "hello";
	}
}

package entity;

public class User {
private String username;
private String password;
private int age;
public int getAge() {
	return age;
}

public void setAge(int age) {
	this.age = age;
}

public String getUsername() {
	return username;
}

public void setUsername(String username) {
	this.username = username;
}

public String getPassword() {
	return password;
}

public void setPassword(String password) {
	this.password = password;
}

public User() {
	// TODO Auto-generated constructor stub
}
}

3.spring-servlet.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		xmlns:tx="http://www.springframework.org/schema/tx" 
		xmlns:aop="http://www.springframework.org/schema/aop"
		xmlns:context="http://www.springframework.org/schema/context" 
		xmlns:jee="http://www.springframework.org/schema/jee"
		xsi:schemaLocation="
			http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
			http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
			http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
			http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd">

<context:component-scan base-package="cn.test" />  

<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"></bean>

     

<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
		<property name="prefix" 
			value="/WEB-INF/"/>
		<property name="suffix"
			value=".jsp"/>
	</bean>
	

</beans>

4.web.xml配置

<?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>
      <context-param>   
        <param-name>contextConfigLocation</param-name>   
        <param-value>classpath:applicationContext.xml</param-value>   
    </context-param> 
    <!-- Spring 容器启动监听器 此处的监听是不需要的-->   
    <listener>   
        <listener-class>org.springframework.web.context.ContextLoaderListener   
        </listener-class>   
    </listener>  
     
 <!--(1.servlet)   <servlet>
  	<servlet-name>springmvc</servlet-name>
  	<servlet-class>
  		org.springframework.web.servlet.DispatcherServlet
  	</servlet-class>
  	 如果不配置这个init-param的话,它会找寻WEB-INF下面的servlet-name比如spring,的 spring-servlet.xml-->
  	<!--  <init-param>
  		<param-name>
  			contextConfigLocation
  		</param-name>
  		<param-value>
  			classpath:applicationContext.xml
  		</param-value>
  	</init-param>
  	<load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
  	<servlet-name>springmvc</servlet-name>
  	<url-pattern>*.do</url-pattern>
  </servlet-mapping>
  
  -->
  <!--(2.servlet) -->
    <servlet>
  	<servlet-name>spring</servlet-name>
  	<servlet-class>
  		org.springframework.web.servlet.DispatcherServlet
  	</servlet-class>
  	<load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
  	<servlet-name>spring</servlet-name>
  	<url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>

5.index.jsp测试页面

<%@ 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">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
   <a href="<%=basePath%>findEmp.do">springMvc</a><br/>
   <a href="<%=basePath%>test/login.do?username=admin">/test/login.do</a><br/>
   <a href="<%=basePath%>test/login2.do?username=admin&password=admin&age=10">/test/login2.do</a><br/>
   <a href="<%=basePath%>test2/login.do?method=2&username=admin&password=admin&age=10">/test2/login.do</a><br/>
   <a href="<%=basePath%>test3/login.do?username=admin">/test3/login.do</a><br/>
   <form action="<%=basePath%>test/login3.do" method="post">
   <input type="text" name="username" value="admin">
   <input type="submit" value="test/login3.do">
   </form>
    <form action="<%=basePath%>test/login4.do" method="post">
   <input type="text" name="username" value="admin">
   <input type="submit" value="test/login4.do">
   </form>
  </body>
</html>


6.教学博客文档

springMvc 详解

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!