对 Servlet 处理请求有点不太清楚,所以花了半天时间把他搞搞懂。
总结:
前提:在web.xml中配置 url-pattern 为 *.do
(1)getServletPath():获取能够与“url-pattern”中匹配的路径,注意是完全匹配的部分,*的部分不包括。
(2)login.do,find.do 等 .do 结尾的,为表单的 action 所反馈的对象、超链接 href 的 URL,可以使用 getServletPath() 捕获他进行处理,也可以通过重定向来调用他。
(3)JSP页面是用来显示或者输入数据的,我们通过设置他提交的对象 *.do(要和 url-pattern 匹配),在 Servlet 中使用 getServletPath 来获得 request 中action、href 的路径,使用字符串匹配来捕获他,捕获完成后,进行业务处理。之后可以选择跳转等操作。
自己写的测试案例:
主程序Servlet
package web;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.StudentDao;
import dao.StudentDaoImpl;
import entity.Student;
public class MainServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String path = req.getServletPath(); // getServletPath() 获取 url-pattern 中的路径,可以使用这个路径来进行 action 路径的匹配
System.out.println(path);
// 一定要加 /
if("/login.do".equals(path)) {
loginService(req, res);
}else if("/find.do".equals(path)){
findService(req, res);
}else if("main.do".equals(path)) {
loginService(req, res);
}else if("/tofind.do".equals(path)) {
req.getRequestDispatcher("find.jsp").forward(req, res);
}
}
protected void loginService(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
String[] password = req.getParameterValues("password"); // 密码不一致返回到登录页面
/* if(password.length == 0 || password[0].equals(password[1])) {
res.sendRedirect("login.jsp");
}*/
req.setCharacterEncoding("utf-8");
res.setContentType("text/html; charset=utf-8");
// 根据表单的 name值 获取value
String phone = req.getParameter("phone");
String id = req.getParameter("id");
String name = req.getParameter("name");
Integer score = Integer.valueOf(req.getParameter("score"));
String[] like = req.getParameterValues("like");
Student student = new Student();
List<Student> list = new ArrayList<Student>();
student.setId(id);
student.setName(name);
String tmpPassword = password[0];
student.setPassword(tmpPassword);
student.setScore(score);
list.add(student);
StudentDao sd = new StudentDaoImpl();
sd.addStudent(list);
req.setAttribute("phone", phone);
req.setAttribute("id", id);
req.setAttribute("name", name);
req.setAttribute("password", password);
req.setAttribute("score", score);
req.setAttribute("like", like);
// 转发
req.getRequestDispatcher("loginSuccess.jsp").forward(req, res);
}
protected void findService(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
String name = req.getParameter("name");
System.out.println(name);
StudentDao student = new StudentDaoImpl();
List<Student> list = student.findName(name);
req.setAttribute("list", list);
req.getRequestDispatcher("result.jsp").forward(req, res);
}
}
find.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
<style>
div{
margin: 20%;
magrin-left: 40%;
}
</style>
</head>
<body>
<div>
<form action="find.do" method="post">
输入姓名查找:<input type="text" name="name"><br><br>
<input type="submit" value="查找">
</form>
</div>
</body>
</html>
result.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ page import="entity.Student" %>
<%@ page import="java.util.List" %>
<%@ page import="java.io.IOException" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
<style>
div{
margin: 20%;
magrin-left: 40%;
}
</style>
</head>
<body>
<div>
<% try{
List<Student> list = (List<Student>)request.getAttribute("list");
if(list.size() != 0){
for(Student student : list){
%>
ID:<%=student.getId() %> <br><br>
姓名:<%=student.getName() %> <br><br>
密码:<%=student.getPassword() %> <br><br>
分数:<%=student.getScore() %> <br><br>
<%
}
}
}catch(Exception e){
e.printStackTrace();
}
%>
</div>
</body>
</html>
login.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
<style type="text/css">
div{
margin:20%;
margin-left:40%;
}
</style>
</head>
<body>
<!-- login.do 根据web.xml进行配置 -->
<div>
<a href="tofind.do">查找</a>
</div>
<form method="post" action="login.do">
<div id="login">
手机号:<input type="text" name="phone"> <br><br>
ID:<input type="text" name="id"> <br><br>
姓名:<input type="text" name="name"> <br><br>
密码:<input type="password" name="password"> <br><br>
再次确认密码:<input type="password" name="password"> <br><br>
分数:<input type="text" name="score"> <br><br>
爱好:<input type="checkbox" value="代码" name="like"> 代码
<input type="checkbox" value="爬山" name="like"> 爬山
<input type="checkbox" value="电影" name="like"> 电影
<input type="checkbox" value="逛街" name="like"> 逛街 <br><br>
<input type="submit" value="提交">
</div>
</form>
</body>
</html>
DBUtil
package util;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;
import org.apache.commons.dbcp.BasicDataSource;
public class DBUtil {
private static String driver;
private static String url;
private static String user;
private static String password;
private static int initialSize;
private static int maxActive;
private static int maxIdle;
private static int minIdle;
private static BasicDataSource bds;
static {
try {
bds = new BasicDataSource();
InputStream in = DBUtil.class.getClassLoader().getResourceAsStream("db.properties");
Properties cfg = new Properties();
cfg.load(in);
driver = cfg.getProperty("jdbc.driver");
url = cfg.getProperty("jdbc.url");
user = cfg.getProperty("jdbc.user");
password = cfg.getProperty("jdbc.password");
initialSize = Integer.parseInt(cfg.getProperty("jdbc.initialSize"));
maxActive = Integer.parseInt(cfg.getProperty("jdbc.maxActive"));
maxIdle = Integer.parseInt(cfg.getProperty("jdbc.maxIdle"));
minIdle = Integer.parseInt(cfg.getProperty("jdbc.minIdle"));
in.close();
bds.setDriverClassName(driver);
bds.setUrl(url);
bds.setUsername(user);
bds.setPassword(password);
bds.setInitialSize(initialSize);
bds.setMaxActive(maxActive);
bds.setMaxIdle(maxIdle);
bds.setMinIdle(minIdle);
}catch(Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
try {
Connection conn = bds.getConnection(); // 有空闲连接则进行连接,否则等待连接
return conn;
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public static void close(Connection conn) {
try {
if(conn != null) {
conn.close(); // 归还给连接池
}
}catch(Exception e) {
e.printStackTrace();
}
}
public static void rollback(Connection conn) {
try {
if(conn != null) {
conn.rollback();
}
}catch(Exception e) {
e.printStackTrace();
}
}
}
Student
package entity;
public class Student {
private String id;
private String name;
private String password;
private int score;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
StudentDao接口
package dao;
import java.util.List;
import entity.Student;
public interface StudentDao {
public List<Student> findName(String name);
public boolean addStudent(List<Student> list);
}
StudentDaoImpl.java
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import entity.Student;
import util.DBUtil;
public class StudentDaoImpl implements StudentDao {
public List<Student> findName(String name){
Connection conn = null;
try {
conn = DBUtil.getConnection();
List<Student> list = new ArrayList<Student>();
String sql = "select * from test_table where name = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, name);
ResultSet rs = ps.executeQuery();
while(rs.next()) {
Student stu = new Student();
stu.setId(rs.getString("id"));
stu.setName(rs.getString("name"));
stu.setPassword(rs.getString("password"));
stu.setScore(rs.getInt("score"));
list.add(stu);
// System.out.println(rs.getString("id"));
}
return list;
}catch(Exception e) {
e.printStackTrace();
}finally {
DBUtil.close(conn);
}
return null;
}
public boolean addStudent(List<Student> list) {
Connection conn = null;
try {
if(list != null) {
conn = DBUtil.getConnection();
/* String sql1 = "select * from test_table where id = ?";
PreparedStatement ps1 = conn.prepareStatement(sql1);
ps1.setString(1, "1");
ResultSet rs = ps1.executeQuery();
while(rs.next()){
System.out.println(rs.getString("id") + "、" + rs.getInt(1));
}*/
/* String sql = "insert into test_table(id, name, password, score) values('5', 'c', 'e', 5)";*/
/* System.out.println(list.get(0).getId());
System.out.println(list.get(0).getName());
System.out.println(list.get(0).getPassword());
System.out.println(list.get(0).getScore().TYPE); */
String sql = "insert into test_table(id, name, password, score) "
+"values(?, ?, ?, ?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, list.get(0).getId());
ps.setString(2, list.get(0).getName());
ps.setString(3, list.get(0).getPassword());
ps.setInt(4, list.get(0).getScore());
int n = ps.executeUpdate();
// System.out.println(n);
if(n > 0) {
return true;
}
}else {
return false;
}
}catch(Exception e) {
}finally {
DBUtil.close(conn);
}
return false;
}
}
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>web-test-1</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>main</servlet-name>
<servlet-class>web.MainServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>main</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
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>czu.cn</groupId>
<artifactId>web-test-1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
</dependencies>
</project>