之前用Servlet写项目,方法里面只有两个方法 doGet和doPost 方法,现在运用Filter 和 反射的方法,再也不用担心需要写很多的Servlet了,话不多少,讲解后直接撸代码。
之前的思路
网页跳转到Servlet中,然后Servlet进行跳转(servlet需要在web.xml中配置,若有很多Servlet,则很麻烦),servlet处理后,根据request.sendRedirect()或者request.getRequestDispatcher().forward(request,response)进行跳转,跳转到JSP页面中。
这个图好丑,但是可以看懂
话不多说,开始撸代码
只把关键代码写出了,详细代码,大家可以去github上Fork下来
第一步:网页发送请求
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
LOOK
package filter;
import org.apache.commons.lang.StringUtils;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by LENOVO on 2017/9/5.
*/
public class BackServletFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse)servletResponse;
HttpServletRequest request = (HttpServletRequest)servletRequest;
/* 假定你的web application 名称为news,你在浏览器中输入请求路径:
http://localhost:8080/news/main/list.jsp
则执行下面向行代码后打印出如下结果:
1、 System.out.println(request.getContextPath());
打印结果:/news
2、System.out.println(request.getServletPath());
打印结果:/main/list.jsp
3、 System.out.println(request.getRequestURI());
打印结果:/news/main/list.jsp
4、 System.out.println(request.getRealPath("/"));
打印结果:F:\Tomcat 6.0\webapps\news\test*/
String contextPath = request.getServletContext().getContextPath();
String uri = request.getRequestURI();
uri = StringUtils.remove(uri,contextPath);
if(uri.startsWith("/admin_")){
String servletPath = StringUtils.substringBetween(uri,"_","_")+"Servlet";
String method = StringUtils.substringAfterLast(uri,"_");
request.setAttribute("method",method);
request.getRequestDispatcher("/"+servletPath).forward(request,response);
return ;
}
filterChain.doFilter(request,response);
}
@Override
public void destroy() {
}
}
第三步:跳转到对应的Servlet(只实现了查看的功能)
package servlet;
import po.Category;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* Created by LENOVO on 2017/9/5.
*/
public class CategoryServlet extends BackServlet{
@Override
public String add(HttpServletRequest request, HttpServletResponse response) {
return null;
}
@Override
public String delete(HttpServletRequest request, HttpServletResponse response) {
return null;
}
@Override
public String edit(HttpServletRequest request, HttpServletResponse response) {
return null;
}
@Override
public String update(HttpServletRequest request, HttpServletResponse response) {
return null;
}
@Override
public String list(HttpServletRequest request, HttpServletResponse response) {
List list = categoryDao.getAll();
request.setAttribute("list",list);
return "/WEB-INF/jsp/list.jsp";
}
}
第四步:调用继承类的service 方法。(
)
package servlet;
import dao.CategoryDao;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
/**
* Created by LENOVO on 2017/9/5.
*/
public abstract class BackServlet extends HttpServlet{
public abstract String add(HttpServletRequest request, HttpServletResponse response);
public abstract String delete(HttpServletRequest request, HttpServletResponse response);
public abstract String edit(HttpServletRequest request, HttpServletResponse response);
public abstract String update(HttpServletRequest request, HttpServletResponse response);
public abstract String list(HttpServletRequest request, HttpServletResponse response );
protected CategoryDao categoryDao = new CategoryDao();
public void service(HttpServletRequest request, HttpServletResponse response) {
try {
/*借助反射,调用对应的方法*/
String method = (String) request.getAttribute("method");
Method m = this.getClass().getMethod(method, HttpServletRequest.class,
HttpServletResponse.class);
String redirect = m.invoke(this, request, response).toString();
/*根据方法的返回值,进行相应的客户端跳转,服务端跳转,或者仅仅是输出字符串*/
if (redirect.startsWith("@"))
response.sendRedirect(redirect.substring(1));
else if (redirect.startsWith("%"))
response.getWriter().print(redirect.substring(1));
else
request.getRequestDispatcher(redirect).forward(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
<%--
Created by IntelliJ IDEA.
User: LENOVO
Date: 2017/9/1
Time: 18:34
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
信息查看
ID
Name
Age Password
修改
删除
${student.id}
${student.name}
${student.age}
${student.password}
修改
删除
package util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* Created by LENOVO on 2017/9/5.
*/
public class DButil {
static String ip = "127.0.0.1";
static int port = 3306 ;
static String database = "blog";
static String encoding = "UTF-8";
static String loginName = "root" ;
static String password = "root";
static {
try {
Class.forName("com.mysql.jdbc.Driver");
}catch (ClassNotFoundException e){
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException{
String url = String.format("jdbc:mysql://%s:%d/%s?characterEncoding=%s",ip,port,database,encoding);
return DriverManager.getConnection(url,loginName,password);
}
}
package dao;
import po.Category;
import util.DButil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by LENOVO on 2017/9/5.
*/
public class CategoryDao {
public List getAll(){
String sql = "select * from category ";
//要把这个定义写到这里,如果写到try,catch中,就成为局部函数,不能当做返回值了
List categoryList = new ArrayList<>();
try (Connection connection = DButil.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(sql)){
ResultSet resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
Category category = new Category();
category.setId(resultSet.getInt("id"));
category.setName(resultSet.getString("name"));
category.setAge(resultSet.getInt("age"));
category.setPassword(resultSet.getString("password"));
categoryList.add(category);
}
}catch(SQLException e){
e.printStackTrace();
}
return categoryList;
}
}
好了,应该可以运行成功了 ,还有数据库
我的github地址 https://github.com/boheningmeng/170905_Filter