文档章节

SpringMvc小应用

黄柳淞
 黄柳淞
发布于 2017/01/14 18:05
字数 2183
阅读 20
收藏 0

com.huangliusong.enties

1Address.java

package com.huangliusong.enties;

public class Address {
	private String provinces;
	private String city;

	public String getProvinces() {
		return provinces;
	}

	public void setProvinces(String provinces) {
		this.provinces = provinces;
	}

	public String getCity() {
		return city;
	}

	@Override
	public String toString() {
		return "Address [provinces=" + provinces + ", city=" + city + "]";
	}

	public void setCity(String city) {
		this.city = city;
	}

}


2User.java

package com.huangliusong.enties;

public class User {
	private String username;
	private int id;

	@Override
	public String toString() {
		return "User [username=" + username + ", password=" + password
				+ ", email=" + email + ", age=" + age + "]";
	}

	public User(int id, String username, String password, String email, int age) {
		super();
		this.username = username;
		this.id = id;
		this.password = password;
		this.email = email;
		this.age = age;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

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

	public User(String username, String password, String email, int age) {
		super();
		this.username = username;
		this.password = password;
		this.email = email;
		this.age = age;
	}

	private String password;
	private String email;
	private int age;
	private Address address;

	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 String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public int getAge() {
		return age;
	}

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

	public Address getAddress() {
		return address;
	}

	public void setAddress(Address address) {
		this.address = address;
	}

}

com.huangliusong.springmvc

4HelloWorld.java

package com.huangliusong.springmvc;

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

@Controller
public class HelloWorld {
	/**
	 * 1.@requestMapping注解来映射url
	 * 2.返回值会通过视图解析器解析为实际的物理视图 对于InternalResoueceViewResolver
	 * 通过prefix+returnVal+后缀这样的方式得到实际的物理视图 然后进行转发操作
	 * @return
	 */
	@RequestMapping("/hello")
	public String hello(){
		System.err.println("hello()");
		return "hello";
	}
}


5SpringMvcTest.java   

package com.huangliusong.springmvc;

import java.util.Arrays;
import java.util.Date;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.huangliusong.enties.User;

/*@SessionAttributes(value = { "user" }, types = { String.class })*/
@RequestMapping("/springmvc")
@Controller
public class SpringMvcTest {
	public static final String SUCCESS = "hello";

	/**
	 * @ModelAttribute 标记的方法 会在每个方法之前被springmvc调用
	 * @param id
	 * @param map
	 */
	@ModelAttribute
	public void getUser(
			@RequestParam(value = "id", required = false) Integer id,
			Map<String, Object> map) {
		if (id != null) {
			// 从数据库中获取一个对象
			User user = new User(1, "tom", "123456", "tom@qq.com", 11);
			System.err.println("从数据库中获取一个对象" + user);
			map.put("user", user);
		}
	}

	/**
	 * 运行流程 1.执行@modelAttribute注解修饰方法 从数据库中取出对象 吧对象放入到map中 键为user
	 * 2.SpringMvc从Map中取出User对象并且把表单的请求参数赋值给User对象对应的属性
	 * 3.SpringMvc把上述对象传入目标方法的参数
	 * 
	 * 注意在ModelAttribute修饰的方法中 放入到Map时的键 需要和目标方法入参类型的第一个字母小写的字符串一致 即为:User
	 * 第一个字母小写
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping("testModelAttribute")
	public String testModelAttribute(User user) {
		System.err.println("修改:" + user);
		return SUCCESS;
	}

	/**
	 * 将值存入session域里面 需要添加@SessionAttributes("user")注解
	 * value={"user"},types={String.class}
	 * 
	 * @sesionAttribute除了可以通过属性名指定需要放到会话中的属性外 
	 *                                        还可以通过模型属性对象类型指定那些模型属性需要放到会话中这个注解只能放在类上面
	 * @param map
	 * @return
	 */
	@RequestMapping("/testSessionAttribute")
	public String testSessionAttribute(Map<String, Object> map) {
		User user = new User("huangliusong", "11111", "11@qq.com", 18);
		map.put("user", user);
		map.put("school", "hls");
		return SUCCESS;
	}

	/**
	 * 目标方法可以添加map(实际上也可以是model类型或者modelmap类型)类型的参数
	 * 
	 * @param map
	 * @return
	 */
	@RequestMapping("/testMap")
	public String testMap(Map<String, Object> map) {
		System.err.println(map.getClass().getName());
		map.put("name", Arrays.asList("tom", "jj", "mike"));
		return SUCCESS;
	}

	/**
	 * 目标方法的返回值可以是modelandview类型 其中可以包含视图和模型信息
	 * springmvc会吧ModelAndView的model中数据放入到request域对象
	 * 
	 * @return
	 */
	@RequestMapping("/testModelAndView")
	public ModelAndView testModelAndView() {
		ModelAndView modelAndView = new ModelAndView(SUCCESS);
		modelAndView.addObject("time", new Date());
		System.err.println("testModelAndView");
		return modelAndView;
	}

	@RequestMapping("testPOJO")
	public String testPOJO(User user) {
		System.err.println("testPOJO:" + user);
		return SUCCESS;
	}

	/**
	 * 了解CoolieValue映射 属性同@RequestParam
	 * 
	 * @param cookie
	 * @return
	 */
	@RequestMapping("/testCookieValue")
	public String testCookieValue(@CookieValue("JSESSIONID") String cookie) {
		System.err.println("testCookieValue" + cookie);
		return SUCCESS;
	}

	/**
	 * @RequestHeader映射请求头
	 * @param al
	 * @return
	 */
	@RequestMapping("/testRequestHeader")
	public String testRequestHeader(@RequestHeader(value = "Cookie") String al) {
		System.err.println("testRequestHeader," + al);
		return SUCCESS;
	}

	/**
	 * @RequestParam 用来映射请求参数 value为请求参数的参数名 required该参数是否必须 默认为true
	 *               defaultValue请求参数的默认值
	 * @param username
	 * @param password
	 * @return
	 */
	@RequestMapping("/testRequestParam")
	public String testRequestParam(
			@RequestParam(value = "username") String username,
			@RequestParam(value = "password", required = false, defaultValue = "0") int password) {
		System.err.println("testRequestParam" + "username:" + username);
		System.err.println("testRequestParam" + "pwd:" + password);
		return SUCCESS;
	}

	/*
	 * 如何发送PUT请求和DELETE请求 呢 1.需要配置HiddentHttpMethodFilter 2.需要发送POST请求
	 * 3.需要发送POST请求时携带一个name="_method"的隐藏域 值为DELETE或者PUT
	 * 
	 * 在springMVC的目标方法
	 */
	@RequestMapping(value = "/testRest/{id}", method = RequestMethod.PUT)
	public String testRestPUT(@PathVariable int id) {
		System.err.println("testRest-PUT");
		return SUCCESS;
	}

	@RequestMapping(value = "/testRest/{id}", method = RequestMethod.DELETE)
	public String testRestDELETE(@PathVariable int id) {
		System.err.println("testRest-DELETE");
		return SUCCESS;
	}

	@RequestMapping(value = "/testRest/{id}", method = RequestMethod.POST)
	public String testRest() {
		System.err.println("testRest-POST");
		return SUCCESS;
	}

	@RequestMapping(value = "/testRest/{id}", method = RequestMethod.GET)
	public String testRest(@PathVariable int id) {
		System.err.println("testRest-get");
		return SUCCESS;
	}

	/**
	 * @PathVariable 可以映射URL中的占位符 到目标方法的参数中
	 * @param id
	 * @return
	 */
	@RequestMapping("/testPathVariable/{id}")
	public String testPathVariable(@PathVariable("id") int id) {
		System.err.println("testPathVariable:" + id);
		return SUCCESS;
	}

	@RequestMapping("/testAntPath/*/abc")
	public String testAntPath() {
		System.err.println("testAntPath");
		return SUCCESS;
	}

	public String setParamsAndHanders() {
		return SUCCESS;
	}

	/**
	 * @RequestMapping除了修饰方法还可以修饰类 类定义处:提供初步信息 相对于WEB应用的根目录 方法定义处:提供一个细分信息
	 *                             若类定义未标注@RequestMaping 则方法处标记URL相对于WEB应用的根目录
	 * @return
	 */
	@RequestMapping("/testRequestMappting")
	public String testRequestMappting() {
		System.err.println("testRequestMappting");
		return SUCCESS;
	}
}

6springmvc.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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans  
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
        http://www.springframework.org/schema/context  
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<!-- 被扫描的包的路径 -->
	<context:component-scan base-package="com.huangliusong.springmvc" />

	<!-- 添加viewResolver 配置视图解析器 如何把handler方法的返回值解析为实际的物理视图 -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<!-- 前缀和后缀 -->
		<property name="prefix" value="/WEB-INF/view/" />
		<property name="suffix" value=".jsp" />
	</bean>
</beans> 

7hello.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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 'hello.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>
    success
  </body>
</html>

8hello.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	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 'hello.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>
	success-默认
	<br> time:${requestScope.time  }
	<br>
	<br> name:${requestScope.name }
	<br>
	<br> request user:${requestScope.user }
	<br>
	<br> session user:${sessionScope.user }
	<br>
	<br> request school:${requestScope.school }
	<br>
	<br> session school:${sessionScope.school }
</body>
</html>

9springDispatcherServlet-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:p="http://www.springframework.org/schema/p"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
        http://www.springframework.org/schema/context  
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
    <!-- 被扫描的包的路径 -->  
    <context:component-scan base-package="com.huangliusong.springmvc" />  
    <!-- 添加viewResolver 配置视图解析器
    	如何把handler方法的返回值解析为实际的物理视图
     -->  
    <bean id="viewResolver"  
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <property name="viewClass"  
            value="org.springframework.web.servlet.view.JstlView" />  
        <!-- 前缀和后缀 -->  
        <property name="prefix" value="/WEB-INF/views/" />  
        <property name="suffix" value=".jsp" />  
    </bean>  
</beans> 

10web.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_3_0.xsd"
	id="WebApp_ID" version="3.0">

<!-- 配置 org.springframework.web.filter.HiddenHttpMethodFilter:可以吧post请求转换成delete或post请求-->
	<filter>
		<filter-name>HiddenHttpMethodFilter</filter-name>
		<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>HiddenHttpMethodFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<servlet>
		<servlet-name>springDispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- 如果有多个*-servlet.xml配置文件,则需要如下配置 -->
		<!-- 配置DispatcherServlet的一个初始化参数 配置SpringMvc配置文件的名称和位置 实际上也可以不通过contextConfigLocation来配置SpringMvc的配置文件而是使用默认的 
			默认的为:/WEB-INF/<servlet-name>-servlet.xml -->
		<!-- <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> 
			</init-param> -->
		<!--是否在容器启动时就加载对应的servlet -->
		<load-on-startup>1</load-on-startup>
	</servlet>
	<!-- 对应的映射 -->
	<servlet-mapping>
		<servlet-name>springDispatcherServlet</servlet-name>
		<!-- 表示可以应答所有的请求 -->
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>

11.index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>springmvc测试</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">
</head>

<body>
	<!-- 模拟 操作:
	1.原始数据
	2.密码不能被修改
	3.表单回显
	
	-->
	<form action="springmvc/testModelAttribute" method="post">
		<input type="hidden" name="id" value="1"> <br> 用户名<input
			type="text" name="username" value="huangliusong"> <br>
		电子邮件<input type="text" name="email" value="111@qq.com"> <br>
		年龄<input type="text" name="age" value="23"> <br> <input
			type="submit" value="submit"> <br>
	</form>
	<br>
	<br>
	<br>
	<a href="springmvc/testSessionAttribute">testSessionAttribute </a>
	<br>
	<a href="springmvc/testMap">testMap </a>
	<br>
	<a href="springmvc/testModelAndView">testModelAndView </a>

	<form action="springmvc/testPOJO" method="post">
		用户名<input type="text" name="username"> <br> 密码<input
			type="password" name="password"> <br> 电子邮件<input
			type="text" name="email"> <br> 年龄<input type="text"
			name="age"> <br> 城市<input type="text"
			name="address.city"> <br> 省份<input type="text"
			name="address.provinces"> <br> <input type="submit"
			value="submit"> <br>
	</form>

	<br>
	<br>
	<br>
	<br>
	<br>
	<br>
	<br>
	<a href="springmvc/testCookieValue">testCookieValue </a>
	<br>
	<a href="springmvc/testRequestHeader">testRequestHeader </a>
	<br>
	<a href="springmvc/testRequestParam?username=hls&&password=12">testRequestParam
	</a>
	<br>
	<a href="springmvc/testRequestMappting">huangliusong </a>
	<br>
	<a href="hello">huangliusong </a>
	<br>
	<a href="springmvc/testAntPath/mnnn/abc">testAntPath </a>
	<br>
	<a href="springmvc/testPathVariable/1">testPathVariable </a>
	*****************
	<form action="springmvc/testRest/1" method="post">
		<input type="hidden" name="_method" value="PUT" /> <input
			type="submit" value="TestRest PUT" />
	</form>
	*****************
	<form action="springmvc/testRest/1" method="post">
		<input type="hidden" name="_method" value="DELETE" /> <input
			type="submit" value="TestRest DELETE" />
	</form>
	*****************
	<form action="springmvc/testRest" method="post">
		<input type="submit" value="TestRest POST" />
	</form>
	<br>
	<a href="springmvc/testRest/1">testRestGet </a>
	<br>
</body>
</html>

 

© 著作权归作者所有

上一篇: myeclipse2014-mysqL
下一篇: SpringMvc-helloword
黄柳淞
粉丝 2
博文 108
码字总数 54251
作品 0
南宁
程序员
私信 提问
spring 相关jar包详解

spring.jar是包含有完整发布的单个jar包,spring.jar中包含除了 spring-mock.jar里所包含的内容外其它所有jar包的内容,因为只有在开发环境下才会用到spring-mock.jar来进行辅助测试,正式应...

满风
2011/10/20
0
0
Spring实战读书笔记(1)

Spring的根本使命是? 简化Java开发 为了降低Java开发的复杂性,Spring采取了哪4种关键策略? 1、基于POJO的轻量级和最小侵入性编程 2、通过依赖注入和面向接口实现松耦合 3、基于切面和惯例...

祥林会跟你远走高飞
2014/12/30
0
0
spring

Spring 2.5 jar 所有开发包及完整文档及项目开发实例 spring jar 包详解spring.jar是包含有完整发布的单个jar包,spring.jar中包含除了 spring-mock.jar里所包含的内容外其它所有jar包的内容...

allen515
2009/11/27
616
0
Spring MVC 到 Spring Boot 的简化之路

背景 从Servlet技术到Spring和Spring MVC,开发Web应用变得越来越简捷。但是Spring和Spring MVC的众多配置有时却让人望而却步,相信有过Spring MVC开发经验的朋友能深刻体会到这一痛苦。因为...

别打我会飞
2018/10/21
0
0
Spring Boot 的 10 个核心模块

学习 Spring Boot 必须得了解它的核心模块,和 Spring 框架一样,Spring Boot 也是一个庞大的项目,也是由许多核心子模块组成的。 你所需具备的基础 告诉你,Spring Boot 真是个牛逼货! Sp...

Java技术栈
2018/12/27
0
0

没有更多内容

加载失败,请刷新页面

加载更多

c 基础教程六:c 循环结构

有的时候,我们可能需要多次执行同一块代码,c 语言提供了如下几种循环,各有特色。 while 循环 for 循环 do-while 循环 while 循环 只要给定的条件为真,C 语言中的 while 循环语句会重复执...

故城以南丶思念不安
23分钟前
4
0
spark 常见操作

为spark DataFrom 添加一个为 空的新列,使用UDF函数 想产生一个IntegerType类型列为null的DataFrame该怎么做。 import org.apache.spark.sql.functions._import org.apache.spark.sql.type...

蜉先生
34分钟前
2
0
Flutter for Web 详细预研

首先感谢@栖冰 @祖建国 一起对FFW的预研做的投入! 背景 Google在最新的Google I/O上推出了Flutter for Web,旨在进一步解决一次代码,多端运行的问题。Flutter for Web还处于早期试验版,官...

阿里云云栖社区
44分钟前
1
0
mongodb自动备份脚本

mongodb自动备份脚本 2019年04月08日 13:27:28 遗失的曾经! 阅读数 73 #!/bin/bash# 要备份的数据库名'多个数据库用空格分开# 备份文件要保存的目录basepath="/data/backup/dump$(da...

linjin200
45分钟前
1
0
如何使用pagehelper分页

<c:if test="${page != null && page.getTotal() > 0 }"> <nav style="text-align: center"><ul class="pagination pagination-lg"><li><a>共 ${page.total } 条记录</a></l......

南桥北木
54分钟前
1
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部