SpringMVC表单的处理

一.获取请求参数
1.通过HttpRequestServlet获取请求参数
public String handlerRegister(HttpServletRequest request) {
    //获取请求参数
    String username = request.getParameter("username");
    return null;
}

2.以上方式要求参数的名称与前端页面的表单中的名称保持一致!如果参数名与表单中使用的名称不同,可以使用 @RequestParam 注解:
public String handlerRegister(@RequestParam("password") String pwd,String username) {
    System.out.println("username="+username);
    System.out.println("password="+pwd);
    return null;
}


3.通过Java Bean直接接收所有请求参数的值
设计一个Java Bean包含所有的请求参数,并且在Java Bean中的属性名与前端页面的表单中使用的名称保持一致,

@Component
public class User {
    private String username;
    private String password;
    private int salary;
    // ... Set/Get方法 ...
}


public String handleRegister(User user) {
    // 直接使用参数即可,这些参数已经被赋值
}


二.使用ModelAndView
public ModelAndView handlerRegister(HttpServletRequest request, User user,
ModelMap data,HttpSession session) {
    ModelAndView mav = new ModelAndView();
    mav.setViewName("user_register_info");
}

1.通过request封装转发
request.setAttribute("name", user.getUsername());

2.使用ModelAndView
mav.getModel().put("pwd", user.getPassword());

3.使用ModelMap
data.addAttribute("salary", user.getSalary());

4.使用session
session.setAttribute("name",user.getUsername());

5.常见使用情况
(1)使用Session保存数据
    a)当前用户的身份标识 
    b)高频率使用的用户数据
(2)仅会在此次请求时显示的数据,使用ModelMap
    a)密码,金额等不常显示数据
    b)异常的错误提示信息


三.案例目标:注册
1.界面
user_register_form.jsp:注册的表单
user_register_success.jsp:注册成功(暂定)
error.jsp:操作失败,用于提交操作失败的信息


2.用户信息
Integer id
String username
String password
Integer salary


3.数据库与数据表
数据库:springmvc
数据表:
create table user (
    id int auto_increment,
    username varchar(16) not null unique,
    password varchar(16) not null,
    salary int,
    primary key(id)
);


四.实例
1.resources下的spring配置文件和数据库信息配置文件

applicationContext.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="cn.tedu.spring"/>
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/"/>
		<property name="suffix" value=".jsp"/>
	</bean>
        
	<util:properties id="dbConfig" location="classpath:db.properties"></util:properties>
	
	<!-- 配置DBCP所需的Bean -->
	<bean id="ds" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="#{dbConfig.driver}"></property>
		<property name="url" value="#{dbConfig.url}"></property>
		<property name="username" value="#{dbConfig.username}"></property>
		<property name="password" value="#{dbConfig.password}"></property>
		<property name="initialSize" value="#{dbConfig.initsize}"></property>
		<property name="maxActive" value="#{dbConfig.maxsize}"></property>
	</bean>
</beans>

db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/springmvc
username=root
password
initsize=1
maxsize=5

2.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>DAY05-SpringMVC-Sample</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: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>
 
 <filter>
 	<filter-name>CharacterEncodingFilter</filter-name>
 	<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
 	<init-param>
 		<param-name>encoding</param-name>
 		<param-value>utf-8</param-value>
 	</init-param>
 </filter>
 <filter-mapping>
 	<filter-name>CharacterEncodingFilter</filter-name>
 	<url-pattern>/*</url-pattern>
 </filter-mapping>
 
 <!-- 只适用与Post请求 -->
</web-app>
3.WEB-INF下jsp文件下三个文件

user_register_form.jsp
<%@ page language="java" 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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>注册</title>
<style type="text/css">
tr{
	padding:5px;
	line-height:30px;
	font-size:16px;
}
input{
	line-height:20px;
	padding:7px;
	background-color:#eee;
	border:0;
}
.user{
	padding:7px;
	line-height:20px;
}
</style>
</head>
<body>
	<h1>用户注册</h1>
	<form action="handlerRegister.do" method="post">
		<table>
			<tr><td class="user">用户名</td><td><input type="text" name="username" placeholder="username"/></td></tr>
			<tr><td class="user">密码</td><td><input type="password" name="password" placeholder="password"/></td></tr>
			<tr><td class="user">月薪</td><td><input type="text" name="salary" placeholder="salary"/></td></tr>
			<tr><td><input style="background-color:#bbb;color:#f6a;width:45px;" type="submit" value="提交"/></td></tr>
		</table>
	</form>
</body>
</html>

user_register_success.jsp

<%@ page language="java" 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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>注册成功</title>
<style type="text/css">
tr{
	padding:5px;
	line-height:30px;
	font-size:16px;
}
input{
	line-height:20px;
	padding:7px;
	background-color:#eee;
	border:0;
}
.user{
	padding:7px;
	line-height:20px;
}
</style>
</head>
<body>
	<h3>注册成功</h3>
	<h4>您的用户名:${username },用户ID:${uid},密码:${pwd },月薪:${salary }。</h4>
</body>
</html>

error.jsp

<%@ page language="java" 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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>注册成功</title>
<style type="text/css">
tr{
	padding:5px;
	line-height:30px;
	font-size:16px;
}
input{
	line-height:20px;
	padding:7px;
	background-color:#eee;
	border:0;
}
.user{
	padding:7px;
	line-height:20px;
}
</style>
</head>
<body>
	<h3>注册失败</h3>
	<h4>${errorMessage}</h4>
</body>
</html>


4.自定义异常类
package cn.tedu.spring.exception;

public class UsernameAlreadyExistsException extends RuntimeException{

	private static final long serialVersionUID = -7585802889324479550L;

	public UsernameAlreadyExistsException() {
		super();
	}

	public UsernameAlreadyExistsException(String message) {
		super(message);
	}
	
}
5.数据库关闭连接类
package cn.tedu.spring.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBUtil {
	public static void close(Connection conn, Statement stmt, ResultSet rs) {
		close(conn);
		close(stmt);
		close(rs);
	}
	public static void close(Connection conn) {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static void close(Statement stmt) {
		if (stmt != null) {
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static void close(ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}

6.JavaBean类

package cn.tedu.spring.bean;

public class User {
	private Integer id;
	private String username;
	private String password;
	private Integer salary;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	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 Integer getSalary() {
		return salary;
	}
	public void setSalary(Integer salary) {
		this.salary = salary;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", password=" + password + ", salary=" + salary + "]";
	}
	
}


7.Dao类
package cn.tedu.spring.dao;

import cn.tedu.spring.bean.User;

public interface IUserDao {
	/**
	 * 增加用户数据
	 * @param user 被增加的数据
	 * @return 增加的数据在数据库中的ID
	 */
	Integer insert(User user);
	
	/**
	 * 根据用户名查找用户信息
	 * @param username 用户信息
	 * @return 与用户名匹配的用户数据,如果没有匹配
	 *   的数据,则返回null
	 */
	User findUserByUsername(String username);
}

package cn.tedu.spring.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.annotation.Resource;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.stereotype.Component;

import cn.tedu.spring.bean.User;
import cn.tedu.spring.util.DBUtil;

@Component("userDao")
public class UserDaoImpl implements IUserDao {

	@Resource(name="ds")
	private BasicDataSource ds;
	public Integer insert(User user) {
		//1. 声明变量
		// -- Connection
		// -- PreparedStatement
		// -- ResultSet
		// -- String sql
		// -- 返回值
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "insert into user (username, password, salary) values (?,?,?)";
		Integer id = -1;
		//2. 为这些变量赋值
		// -- sql
		// -- Connection
		// -- PreparedStatement
		// -- ... ...
		
		//3. 为PreparedStatement配置?的值
		try {
			conn=ds.getConnection();
			pstmt=conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
			pstmt.setString(1, user.getUsername());
			pstmt.setString(2, user.getPassword());
			pstmt.setInt(3, user.getSalary());
		
		
		//4. 执行
			int affectedRows = pstmt.executeUpdate();
		
		//5. 处理结果
			if (affectedRows > 0) {
				rs = pstmt.getGeneratedKeys();
				if (rs.next()) {
					id = rs.getInt(1);
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			// 6. 释放资源
			DBUtil.close(conn, pstmt, rs);
		}
		
		// 7. 返回
		return id;
		
	}

	public User findUserByUsername(String username) {
		// 1. 声明变量:
		// -- Connection
		// -- PreparedStatement
		// -- ResultSet
		// -- String sql
		// -- 返回值
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "select id, username, password, salary from user where username=?";
		User user = null;

		try {
			// 2. 为这些变量赋值
			// -- Connection
			// -- PreparedStatement
			// -- ... ...
			conn = ds.getConnection();
			pstmt = conn.prepareStatement(sql);

			// 3. 为PreparedStatement配置?的值
			pstmt.setString(1, username);

			// 4. 执行
			rs = pstmt.executeQuery();

			// 5. 处理结果
			if (rs.next()) {
				user = new User();
				user.setId(rs.getInt(1));
				user.setUsername(rs.getString(2));
				user.setPassword(rs.getString(3));
				user.setSalary(rs.getInt(4));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			// 6. 释放资源
			DBUtil.close(conn, pstmt, rs);
		}

		// 7. 返回
		return user;
	}

}

8.service类

package cn.tedu.spring.service;

import cn.tedu.spring.bean.User;

public interface IUserService {
	/**
	 * 注册 
	 * @param user 需要注册的用户信息
	 * @return 成功注册的用户的ID,如果注册失败,返回-1
	 * @throws UsernameAlreadyExistsException
	 */
	Integer reg(User user);
}

package cn.tedu.spring.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import cn.tedu.spring.bean.User;
import cn.tedu.spring.dao.IUserDao;
import cn.tedu.spring.exception.UsernameAlreadyExistsException;

@Component("userService")
public class UserServiceImpl implements IUserService{
	@Resource(name="userDao")
	private IUserDao userDao;
	public Integer reg(User user) {
		//根据需要增加的用户的用户名去查找数据库
		User check = userDao.findUserByUsername(user.getUsername());
		//如果没有找到数据,则意味着用户名没有被注册
		//则允许注册
		//如果找到数据,则意味着用户名已经被注册
		//则不允许注册
		if(check==null) {
			return userDao.insert(user);
		}else {
			throw new UsernameAlreadyExistsException("注册失败!用户名已经被注册!");
		}
	}
}

9.控制器类

package cn.tedu.spring.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

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

import cn.tedu.spring.bean.User;
import cn.tedu.spring.exception.UsernameAlreadyExistsException;
import cn.tedu.spring.service.IUserService;

@Controller
@RequestMapping("/user")
public class UserController {
	
	@Resource(name="userService")
	private IUserService userService;
	
	@RequestMapping("/reg.do")
	public String showRegisterForm() {
		return "user_register_form";
	}
	@RequestMapping("/handlerRegister.do")
	public String handlerRegisterForm(User user,ModelMap data,HttpSession session) {
		//由于需要调用的Service中的方法是可能抛出异常的,
		//所以,以下代码使用try_catch语法
		try {
			//尝试调用注册功能
			Integer uid = userService.reg(user);
			//使用Session保存数据
			// a)当前用户的身份标识 
			// b)高频率使用的用户数据
			session.setAttribute("uid", uid);
			session.setAttribute("username", user.getUsername());
			//仅会在此次请求时显示的数据,使用ModelMap
			data.addAttribute("pwd", user.getPassword());
			data.addAttribute("salary", user.getSalary());
			//如果执行以上方法时没有抛出异常
			//则注册是成功的,则转发到“注册成功”的页面
			return "user_register_success";
		} catch (UsernameAlreadyExistsException e) {
			//跟踪异常信息
			e.printStackTrace();
			//将异常的错误提示封装并转发
			data.addAttribute("errorMessage",e.getMessage());
			//转发
			return "error";
		}catch (Exception e) {
			//跟踪异常信息
			e.printStackTrace();
			//将异常的错误提示封装并转发
			data.addAttribute("errorMessage","未知错误!请联系系统管理员!");
			//转发
			return "error";
		}
	}
}

10.测试类,过程中有需要可以写

package cn.tedu.test;

import java.sql.SQLException;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;

import com.mysql.jdbc.Driver;

import cn.tedu.spring.bean.User;
import cn.tedu.spring.dao.IUserDao;
import cn.tedu.spring.service.IUserService;

@SuppressWarnings("unused")
public class Test {
	@SuppressWarnings("null")
	public void test() {
		Driver driver;
		CharacterEncodingFilter filter;
		BasicDataSource source = null;
		source.setDriverClassName(null);
		source.setUrl(null);
		source.setUsername(null);
		source.setPassword(null);
		source.getInitialSize();
		source.getMaxActive();
	}
	@org.junit.Test
	public void testDBCP() {
		String file = "applicationContext.xml";
		AbstractApplicationContext context = new ClassPathXmlApplicationContext(file);
		BasicDataSource ds = context.getBean("ds",BasicDataSource.class);
		
		System.out.println(ds.getDriverClassName());
		System.out.println(ds.getUrl());
		System.out.println(ds.getUsername());
		System.out.println(ds.getPassword());
		System.out.println(ds.getInitialSize());
		System.out.println(ds.getMaxActive());
		try {
			System.out.println(ds.getConnection());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		context.close();
	}
	
	@org.junit.Test
	public void testInsert() {
		String file = "applicationContext.xml";
		AbstractApplicationContext context = new ClassPathXmlApplicationContext(file);
		
		User user = new User();
		user.setUsername("admin");
		user.setPassword("admin888");
		user.setSalary(8000);
		IUserDao userDao = context.getBean("userDao",IUserDao.class);
		Integer id = userDao.insert(user);
		System.out.println("id=" + id);
		context.close();
	}
	
	@org.junit.Test
	public void testFindUser() {
		String file = "applicationContext.xml";
		AbstractApplicationContext ctx 
			= new ClassPathXmlApplicationContext(file);
		
		IUserDao userDao 
			= ctx.getBean("userDao", IUserDao.class);
		
		User user = userDao.findUserByUsername("admin");
		System.out.println(user);
		
		ctx.close();
	}
	
	@org.junit.Test
	public void testReg() {
		String file = "applicationContext.xml";
		AbstractApplicationContext context = new ClassPathXmlApplicationContext(file);
		
		User user = new User();
		user.setUsername("admin");
		user.setPassword("admin888");
		user.setSalary(8000);
		IUserService userService = context.getBean("userService",IUserService.class);
		Integer id = userService.reg(user);
		System.out.println("id=" + id);
		context.close();
	}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

linsa_pursuer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值