Servlet 中 url-pattern 和 getServletPath 的一點疑惑

對 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>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章