servlet提交表单

post请求

表单的method=“post”,浏览器会发送post请求

特点

  • 不会将请求参数显示在浏览器地址栏,相对安全
  • 并不会对请求参数加密
  • 会将请求参数添加到实体内容里面,所以,可以提交大量数据给服务器

读取提交的请求参数值

request提供的getParameter

//如果请求参数名写错,会返回null值。
//如果不填写任何数据,会获得空字符串
String  getParameter(String paramName);

request提供的getParameterValues

//当有多个请求参数名相同时,用该方法
//多选框,如果不选择任何选项,浏览器不会发送任何数据给服务器。
String[] getParameterValues(String paramName);  

form表单提交数据

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>计算BMI指数</title>
</head>
<body style="font-size:30px;">
	<form action="bmi" method="post">
		<fieldset>
			<legend>计算BMI指数</legend>
			身高(米):<input name="height"><br>
			体重(公斤):<input name="weight"><br>
			<!--checkbox:复选框  -->
			兴趣:钓鱼<input name="interest" type="checkbox" value="钓鱼">
			做饭<input name="interest" type="checkbox" value="做饭">
			台球<input name="interest" type="checkbox" value="台球"><br>
			城市:<input name="city"><br>
			<input type="submit" value="确定">
		</fieldset>
	</form>
</body>
</html>
package web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/bmi")
public class BmiServlet extends HttpServlet {
	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("UTF-8");
		// 身高
		String height = request.getParameter("height");
		// 体重
		String weight = request.getParameter("weight");
		// 兴趣
		String[] interest = request.getParameterValues("interest");
		response.getWriter().print("兴趣:");
		for (String str : interest) {
			response.getWriter().print(str + " ");
		}
		// 城市
		String city = request.getParameter("city");
		response.getWriter().println("城市:" + city);
		/*
		 *bmi指数: 体重千克数除以身高米数的平方
		 */
		double bmi = Double.parseDouble(weight) / Double.parseDouble(height) / Double.parseDouble(height);
		String status = "正常";
		if (bmi < 18.5) {
			status = "过轻";
		}
		if (bmi > 25) {
			status = "过重";
		}
		response.getWriter().println("<h3>您的bmi指数为:" + bmi + "</h3>" + "<h3>您的身体状况:" + status + "</h3>");
	}
}

测试
http://localhost:8087/servlet/form.html
在这里插入图片描述
在这里插入图片描述

表单中文参数乱码

原因:

表单提交时,浏览器会对中文参数值进行编码。服务器端
默认会使用iso-8859-1来解码
会使用表单所在的页面打开时使用的字符集来编码

解决

表单提交方式为post

//要加到所有的request.getParameter方法前面
request.setCharacterEncoding("utf-8");

表单提交方式为get

在这里插入图片描述

设置 (在tomcat下的conf文件下的server.xml中添加)
注: 只针对get请求有效

写一个Servlet,将所有员工信息以表格形式展现出来

maven项目的jar包依赖

<!--添加tomcat插件 -->
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.tomcat.maven</groupId>
				<artifactId>tomcat7-maven-plugin</artifactId>
				<version>2.2</version>
				<configuration>
					<port>8087</port>
					<hostName>localhost</hostName>
					<uriEncoding>UTF-8</uriEncoding>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<dependencies>
		<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>4.0.1</version>
			<scope>provided</scope>
		</dependency>
		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.40</version>
		</dependency>
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

数据库

create database ems;
use ems;
CREATE TABLE `t_emp` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `ename` varchar(255) DEFAULT NULL COMMENT '雇员名称',
  `salary` decimal(10,2) DEFAULT NULL COMMENT '薪水',
  `age` int(11) DEFAULT NULL COMMENT '年龄',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8

实体类

package pojo;

public class Employee {
	private int id;
	private String ename;//雇员名称
	private double salary;//薪水
	private int age;//年龄

	public String toString() {
		return "Employee [id=" + id + ", ename=" + ename + ", salary=" + salary + ", age=" + age + "]";
	}
	public int getId() {
		return id;
	}

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

	public String getEname() {
		return ename;
	}

	public void setEname(String ename) {
		this.ename = ename;
	}

	public double getSalary() {
		return salary;
	}

	public void setSalary(double salary) {
		this.salary = salary;
	}

	public int getAge() {
		return age;
	}

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

}

数据库连接配置

# database connection parameters
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ems?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
jdbc.initSize=1
jdbc.maxSize=3

数据库连接工具类

package util;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.commons.dbcp.BasicDataSource;

public class DBUtil {
	private static BasicDataSource ds;
	static {
		//加载参数
		Properties p=new Properties();
		try {
			p.load(DBUtil.class.getClassLoader().getResourceAsStream("db.properties"));
			//获取数据库连接参数
			String driverClassName=p.getProperty("jdbc.driver");
			String url=p.getProperty("jdbc.url");
			String username=p.getProperty("jdbc.username");
			String password=p.getProperty("jdbc.password");
			String initialSize=p.getProperty("jdbc.initSize");
			String maxSize=p.getProperty("jdbc.maxSize");
			//创建连接池
			ds=new BasicDataSource();
			//设置连接池参数
			ds.setDriverClassName(driverClassName);
			ds.setUrl(url);
			ds.setUsername(username);
			ds.setPassword(password);
			ds.setInitialSize(Integer.parseInt(initialSize));
			ds.setMaxActive(Integer.parseInt(maxSize));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/*
	 * 由连接池创建的连接,其实现类由连接池提供.
	 */
	public static Connection getConnection() throws SQLException {
		return ds.getConnection();
	}
	/*
	 * 连接池提供的实现类,其close方法内部逻辑是,
	 * 将连接归还给连接池,即它会清空连接对象中的数据
	 * 并且将连接标记为空闲态
	 */
	public static void close(Connection con) {
		if(con!=null) {
			try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException("归还连接失败",e);
			}
		}
	}
}

数据库访问类

package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import pojo.Employee;
import util.DBUtil;

public class EmployeeDAO {
	Connection con = null;
	/*
	 * 新增雇员
	 */
	public void save(Employee e){
		try {
			con = DBUtil.getConnection();
			String sql="insert into t_emp values(null,?,?,?)";
			PreparedStatement ps=con.prepareStatement(sql);
			ps.setString(1, e.getEname());
			ps.setDouble(2, e.getSalary());
			ps.setInt(3,e.getAge());
			ps.executeUpdate();
		} catch (SQLException e1) {
			//记日志(保留现场)
			e1.printStackTrace();
			/*
			 * 看异常能否恢复,如果不能够恢复
			 * (比如,数据库服务暂停等,一般我们称之为系统异常),
			 * 要提示用户稍后重试。
			 * 如果能够恢复,则立即恢复
			 */
			throw new RuntimeException(e1);
		}finally {
			DBUtil.close(con);
		}
	}
	/*
	 *查询所有雇员信息
	 */
	public List<Employee>findAll(){
		List<Employee>list=new ArrayList<Employee>();
		try {
			con=DBUtil.getConnection();
			String sql="select * from t_emp";
			PreparedStatement ps=con.prepareStatement(sql);
			ResultSet rs=ps.executeQuery();
			while(rs.next()) {
				Employee e=new Employee();
				e.setId(rs.getInt("id"));
				e.setEname(rs.getString("ename"));
				e.setAge(rs.getInt("age"));
				e.setSalary(rs.getDouble("salary"));
				list.add(e);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			DBUtil.close(con);
		}
		return list;
	}
}

addEmp.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>添加员工</title>
</head>
<body style="font-size:30px;">
	<form action="addEmp" method="post">
		<fieldset>
			<legend>添加员工</legend>
			姓名:<input name="ename"><br>
			薪水:<input name="salary"><br>
			年龄:<input name="age"><br>
			<input type="submit" value="确定">
		</fieldset>
	</form>
</body>
</html>

新增servlet

package web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.EmployeeDAO;
import pojo.Employee;

@WebServlet("/addEmp")
public class AddEmpServlet extends HttpServlet {
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out=response.getWriter();
		EmployeeDAO dao = new EmployeeDAO();
		String ename=request.getParameter("ename");
		String salary=request.getParameter("salary");
		String age=request.getParameter("age");
		Employee emp=new Employee();
		emp.setEname(ename);
		emp.setSalary(Double.parseDouble(salary));
		emp.setAge(Integer.parseInt(age));
		try {
			dao.save(emp);
			out.println("<h1>添加成功!</h1>");
		} catch (Exception e) {
			e.printStackTrace();
			out.println("<h1>系统繁忙,请稍后重试!</h1>");
		}
		//容器会自动关闭out,这儿不调用out.close()也可以
		out.close();
	}
}

列表servlet

package web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.EmployeeDAO;
import pojo.Employee;

@WebServlet("/listEmp")
public class ListEmpServlet extends HttpServlet {
	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out=response.getWriter();
		out.println("<table><tr><td>ID</td><td>ename</td><td>age</td><td>salary</td></tr>");
		EmployeeDAO dao=new EmployeeDAO();
		List<Employee>list=dao.findAll();
		for (Employee employee : list) {
			out.println("<tr><td>"+employee.getId()+"</td><td>"+employee.getEname()+"</td><td>"+employee.getAge()+"</td><td>"+employee.getSalary()+"</td></tr>");
		}
		out.println("</table>");
		out.close();
	}
}

测试

http://localhost:8087/servlet/addEmp.html
在这里插入图片描述
在这里插入图片描述
http://localhost:8087/servlet/listEmp
在这里插入图片描述

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页