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

4 篇文章 0 订阅
3 篇文章 0 订阅

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

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,你需要在IDEA创建一个Web项目,并添加Tomcat服务器。 接下来,你需要创建一个JSP页面来实现用户注册和登录的界面,例如: ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>用户登录</title> </head> <body> <h1>用户登录</h1> <form action="login" method="post"> 用户名:<input type="text" name="username"><br> 密码:<input type="password" name="password"><br> <input type="submit" value="登录"> </form> <hr> <h1>用户注册</h1> <form action="register" method="post"> 用户名:<input type="text" name="username"><br> 密码:<input type="password" name="password"><br> 确认密码:<input type="password" name="password2"><br> <input type="submit" value="注册"> </form> </body> </html> ``` 然后,你需要创建一个Servlet来处理用户的注册和登录请求。在Servlet,你需要连接MySQL数据库,并编写相应的SQL语句来实现用户信息的查询、插入和更新操作。 例如,在doPost方法,你可以编写以下代码: ```java protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getServletPath(); switch (action) { case "/login": String username = request.getParameter("username"); String password = request.getParameter("password"); boolean success = checkUser(username, password); if (success) { response.sendRedirect("welcome.jsp"); } else { response.sendRedirect("login.jsp"); } break; case "/register": String username2 = request.getParameter("username"); String password2 = request.getParameter("password"); String password3 = request.getParameter("password2"); if (!password2.equals(password3)) { response.sendRedirect("register.jsp"); } else { boolean success2 = addUser(username2, password2); if (success2) { response.sendRedirect("login.jsp"); } else { response.sendRedirect("register.jsp"); } } break; default: response.sendRedirect("login.jsp"); break; } } private boolean checkUser(String username, String password) { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; boolean success = false; try { Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8"; conn = DriverManager.getConnection(url, "root", "123456"); String sql = "select * from users where username=? and password=?"; ps = conn.prepareStatement(sql); ps.setString(1, username); ps.setString(2, password); rs = ps.executeQuery(); if (rs.next()) { success = true; } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } finally { try { if (rs != null) { rs.close(); } if (ps != null) { ps.close(); } if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } return success; } private boolean addUser(String username, String password) { Connection conn = null; PreparedStatement ps = null; boolean success = false; try { Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8"; conn = DriverManager.getConnection(url, "root", "123456"); String sql = "insert into users(username,password) values(?,?)"; ps = conn.prepareStatement(sql); ps.setString(1, username); ps.setString(2, password); int rows = ps.executeUpdate(); if (rows > 0) { success = true; } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } finally { try { if (ps != null) { ps.close(); } if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } return success; } ``` 在以上代码,checkUser方法用于检查用户的登录信息是否正确,如果正确,则重定向到欢迎页面;否则,则重定向到登录页面。addUser方法用于向数据库插入新用户的信息,如果插入成功,则重定向到登录页面;否则,则重定向到注册页面。 最后,你需要配置web.xml文件,将ServletJSP页面进行映射,例如: ```xml <servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.example.LoginServlet</servlet-class> </servlet> <servlet> <servlet-name>RegisterServlet</servlet-name> <servlet-class>com.example.RegisterServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>RegisterServlet</servlet-name> <url-pattern>/register</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>welcome.jsp</welcome-file> </welcome-file-list> ``` 这样,你就可以在IDEA实现JSP+Servlet + JDBC+MySQL 注册和登录的功能了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值