后端开发基础-SpringMVC框架学习-006——基础概念

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Coder_Boy_/article/details/82917952

基于注解的springmvc

基于注解的mvc应用

编程步骤

读取请求参数值

方式一:通过request。

方式二:处理方法的入参与请求参数名一致。

方式三:封装成javabean。

向页面传值

方式一:使用ModelAndView

方式二:使用request。

方式三:使用ModelMap对象作为处理方法

方式四:使用session。

如何重定向?


基于注解的mvc应用

目录

step1.导包
step2.配置文件
step3.配置DispatcherServlet

step4.写Controller
. 不用实现Controller接口。
. 可以添加多个处理方法。
. 处理方法写起来更灵活:方法名不做要求,
返回值可以是ModelAndView,可以是String,也
可以void。
. 使用到的注解:
@Controller: 要加在类前面。
@RequestMapping:可以加到类前面,也可以
添加到处理方法前面。用来设置请求路径与
处理方法的对应关系。
step5.写jsp
step6.修改配置文件

读取请求参数值

方式一:通过request。

方式二:处理方法的入参与请求参数名一致。

注:如果不一致,可以使用 @RequestParam(请求参数名)。

方式三:封装成javabean。

step1. 先写一个java类,该类要添加
与请求参数名一致的属性,并且为这些
属性添加相应的get/set方法。
step2. 将这个类作为处理方法的入参。

向页面传值

方式一:使用ModelAndView

step1. 将处理结果放到Map对象里面。
step2. 将Map对象添加到ModelAndView对象
里面。
step3. 将ModelAndView作为处理方法的返回值。

方式二:使用request。

方式三:使用ModelMap对象作为处理方法的入参。

方式四:使用session。

如何重定向?

. 默认情况下,springmvc会使用转发机制。
. 如果要重定向,要看处理方法的返回值
的类型。
情形一:返回值是String。
return “redirect:index.do”;
情形二: 返回值是ModelAndView。
step1. RedirectView rv =
new RedirectView(“index.do”);
step2. return new ModelAndView(rv);

generated by haroopad

案例演示:

工程案例目录结构

 spring环境搭建必备jar:

也可以采用Maven的jar管理工具添加依赖,在pom.xml中添加springmvc相关jar即可

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.study</groupId>
  <artifactId>springcase-day04</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
    <dependencies>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-webmvc</artifactId>
  		<version>3.2.8.RELEASE</version>
  	</dependency>
  </dependencies>
</project>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <display-name>springcase-day04</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
  	<servlet-name>springmvc</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	<init-param>
  		<param-name>contextConfigLocation</param-name>
  		<param-value>classpath:app.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>
</web-app>

app.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:context="http://www.springframework.org/schema/context" 
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"  
	xmlns:jee="http://www.springframework.org/schema/jee" 
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop" 
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:util="http://www.springframework.org/schema/util"
	xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
		
		<!-- 配置组件扫描 -->
		<context:component-scan base-package="controller"/>
		<!-- 配置mvc注解扫描 -->
		<mvc:annotation-driven/>

		<!-- 
			配置视图解析器:
			负责将视图名解析成真正的视图对象(比如jsp)。
		 -->
		 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		 	<property name="prefix" value="/WEB-INF/"/>
		 	<property name="suffix" value=".jsp"/>
		 </bean>
</beans>

HelloController.java

package controller;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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;

/**
 * 用注解的方式来开发Controller
 * 1.不用实现Controller接口。
 * 2.可以添加多个处理方法。
 * 3.处理方法要求:
 * 	 a.方法名不做要求。
 *   b.返回值可以是ModelAndView,可以是
 *     String,也可以是void。
 * 4.使用到的注解:
 *   @Controller:要加在类前面。
 *   @RequestMapping:可以加到类前面,也可以
 *   添加到处理方法前面。用来设置请求路径与
 *   处理方法的对应关系。
 * @author Cher_du
 *
 */
@Controller
public class HelloController {

	@RequestMapping("/hello.do")
	public ModelAndView toHello(){
		System.out.println("HelloController的"+
						  "toHello方法...");
		
		return new ModelAndView("hello");
	}
	
	/*
	 * 处理方法的返回值可以是ModelAndView,
	 * 也可以是String。区别:
	 * 如果返回的既有数据,也有视图名,可以
	 * 使用ModelAndView。如果返回值只有视图名,
	 * 可以直接返回String。
	 */
	@RequestMapping("/toLogin.do")
	public String toLogin(){
		System.out.println("HelloController的"+
							"toLogin方法...");
		return "login";
	}
	
	@RequestMapping("/login.do")
	public String checkLogin(HttpServletRequest request) throws UnsupportedEncodingException{
		System.out.println("HelloController的"+
						  "checkLogin方法");
		request.setCharacterEncoding("utf-8");
		String username = request.getParameter("username");
		String pwd = request.getParameter("pwd");
		System.out.println("username:"+username+" pwd:"+pwd);
		//默认情况下,前端控制器会转发
		//到某个jsp页面。
		return "success";
	}
	
	@RequestMapping("/login2.do")
	/*
	 *获得请求参数值的第二种方式:
	 *处理方法的入参与请求参数名一致。
	 *注:
	 * 如果不一致,可以使用
	 * @RequestParam(请求参数名)
	 */
	public String checkLogin2(String username,@RequestParam("pwd")String password){
		System.out.println("HelloController的"+
							"checkLogin2方法...");
		System.out.println("username:"+username+" pwd:"+password);
		
		return "success";
	}
	
	@RequestMapping("/login3.do")
	/*
	 * 读取请求参数的第三种方式:
	 * step1.先写一个java类,该类要添加
	 * 与请求参数名一致的属性,并且为这些
	 * 属性添加相应的get/set方法。
	 * step2.将这个类作为处理方法的入参。
	 */
	public String checkLogin3(User user){
		System.out.println("HelloController的"+
							"checkLogin3方法...");
		System.out.println("username:"+user.getUsername()+" pwd:"+user.getPwd());
		return "success";
	}
	//====================================================================//
	/*
	 * 使用ModelAndView向页面传值
	 */
	@RequestMapping("/login4.do")
	public ModelAndView checkLogin4(User user){
		System.out.println("HelloController的"+
							"checkLogin4方法...");
		System.out.println("username:"+user.getUsername()+" pwd:"+user.getPwd());
		//要将处理结果封装成一个Map对象。
		Map<String,Object> data = new HashMap<String,Object>();
		//相当于执行了request.setAttribute
		data.put("user", user);
		ModelAndView mav = new ModelAndView("success",data);
		
		return mav;	
	}
	
	/*
	 *使用request对象向页面传值。 
	 */
	@RequestMapping("/login5.do")
	public String checkLogin5(User user,
			HttpServletRequest request) throws UnsupportedEncodingException{
		System.out.println("HelloController的"+
							"checkLogin5方法...");
		request.setCharacterEncoding("utf-8");
		request.setAttribute("user", user);
		
		return "success";
	}
	
	@RequestMapping("/login6.do")
	/*
	 * 使用ModelMap对象来向页面传值。
	 */
	public String checkLogin6(User user,ModelMap data){
		System.out.println("HelloController的"+
						"checkLogin6方法...");
		//相当于request.setAttribute
		data.addAttribute("user",user);
		return "success";
	}
	
	@RequestMapping("/login7.do")
	/*
	 * 使用session向页面传值
	 */
	public String checkLogin7(User user,
			HttpSession session){
		
		System.out.println("HelloController的"+
						"checkLogin7方法...");
		session.setAttribute("user", user);
		return "success";
	}
	
	//==================================================//
	@RequestMapping("/login8.do")
	/*
	 * 演示如何重定向。
	 * 如果处理方法的返回值是String,
	 * 只需要将"redirect:"作为返回值的前缀。
	 */
	public String checkLogin8(User user){
		System.out.println("HelloController的"+
							"checkLogin8方法...");
		return "redirect:toSuccess.do";
	}
	
	@RequestMapping("/login9.do")
	/*
	 * 演示重定向。
	 * 返回值是ModelAndView。
	 */
	public ModelAndView checkLogin9(){
		System.out.println("HelloController的"+
						"checkLogin9方法...");
		RedirectView rv = new RedirectView("toSuccess.do");
		
		return new ModelAndView(rv);
	}
	
	
	
	@RequestMapping("/toSuccess.do")
	public String toSuccess(){
		System.out.println("..toSuccess...");
		return "success";
	}
	
	
}

User.java

package controller;
/**
 * 用来封装请求参数。
 * @author Cher_du
 *
 */
public class User {

	private String username;
	private String pwd;
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

}

hello.jsp

<h1>Hello.SpringMVC</h1>

login.jsp

<%@page contentType="text/html;charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<title>login</title>
	</head>
	<body style="font-size:30px;">
		<form action="login9.do" method="post">
			<fieldset>
				<legend>登录</legend>
				用户名:<input name="username">
				<br>
				密码:<input type="password" name="pwd">
				<br>
				<input type="submit" value="登录">
			</fieldset>
		
		</form>
	</body>
</html>

success.jsp

<%@page contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<title>login</title>
	</head>
	<body>
		Login success.<br>
		Welcome ${user.username }<br>
	</body>
</html>

启动Tomcat 运行 springcase-day04工程,依次请求如下URL 页面运行结果对应如下

A>

http://localhost:8088/springcase-day04/hello.do

下面演示需要修改的部分:

B>http://localhost:8088/springcase-day04/toLogin.do

 C>http://localhost:8088/springcase-day04/toLogin.do 

当login.jsp修改后提交请求为login3.do情况,其他情况类似。

     

猜你喜欢

转载自blog.csdn.net/Coder_Boy_/article/details/82917952