表单的method=“post”,浏览器会发送post请求
//如果请求参数名写错,会返回null值。
//如果不填写任何数据,会获得空字符串
String getParameter(String paramName);
//当有多个请求参数名相同时,用该方法
//多选框,如果不选择任何选项,浏览器不会发送任何数据给服务器。
String[] getParameterValues(String paramName);
<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>
兴趣:钓鱼<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("您的bmi指数为:"
+ bmi + "" + "您的身体状况:"
+ status + "");
}
}
测试
http://localhost:8087/servlet/form.html
表单提交时,浏览器会对中文参数值进行编码。服务器端
默认会使用iso-8859-1来解码
会使用表单所在的页面打开时使用的字符集来编码
//要加到所有的request.getParameter方法前面
request.setCharacterEncoding("utf-8");
设置 (在tomcat下的conf文件下的server.xml中添加)
注: 只针对get请求有效
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.mavengroupId>
<artifactId>tomcat7-maven-pluginartifactId>
<version>2.2version>
<configuration>
<port>8087port>
<hostName>localhosthostName>
<uriEncoding>UTF-8uriEncoding>
configuration>
plugin>
plugins>
build>
<dependencies>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>4.0.1version>
<scope>providedscope>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.40version>
dependency>
<dependency>
<groupId>commons-dbcpgroupId>
<artifactId>commons-dbcpartifactId>
<version>1.4version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
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;
}
}
<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>
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("添加成功!
");
} catch (Exception e) {
e.printStackTrace();
out.println("系统繁忙,请稍后重试!
");
}
//容器会自动关闭out,这儿不调用out.close()也可以
out.close();
}
}
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("ID ename age salary ");
EmployeeDAO dao=new EmployeeDAO();
List<Employee>list=dao.findAll();
for (Employee employee : list) {
out.println(""+employee.getId()+" "+employee.getEname()+" "+employee.getAge()+" "+employee.getSalary()+" ");
}
out.println("
");
out.close();
}
}
http://localhost:8087/servlet/addEmp.html
http://localhost:8087/servlet/listEmp