<%
//往pageContext域中存储了一个msg变量
pageContext.setAttribute("msg" ,"hello page msg");
%>
<%
//往pageContext域中存储了一个msg变量
Object msg = pageContext.getAttribute("msg");
System.out.println(msg);
%>
<%
//定义变量的意义! 提高复用性! 提高可维护性!
//String name : 参数名称
//Object value : 参数值
//int scope : 操作的域
pageContext.setAttribute("msg1","hello page1",PageContext.REQUEST_SCOPE);
//请求转发
request.getRequestDispatcher("/demo06.jsp").forward(request,response);
%>
<%
//变量msg1定义到_jspService方法中
Object msg1 = request.getAttribute("msg1");
System.out.println("msg1 : "+msg1);
Object msg11 = pageContext.getAttribute("msg1", PageContext.REQUEST_SCOPE);
System.out.println(msg11);
%>
<%
pageContext.setAttribute("msg2","hello page2",PageContext.SESSION_SCOPE);
%>
<%
pageContext.setAttribute("msg3","hello page3",PageContext.APPLICATION_SCOPE);
%>
<%
pageContext.setAttribute("msg1","hello page1");
%>
${pageScope.msg1}
<%
request.setAttribute("msg1","hello page1");
%>
${requestScope.msg1}
<%
session.setAttribute("msg1","hello page1");
%>
${sessionScope.msg1}
<%
application.setAttribute("msg1","hello page1");
%>
${applicationScope.msg1}
<%
//数组静态初始化
String[] msgs = {"获取","复杂","域"};
pageContext.setAttribute("msgs",msgs);
%>
<%--jsp输出脚本--%>
<%=
((String[])pageContext.getAttribute("msgs"))[0]
%>
${msgs[1]}
<%
List msgs1 = new ArrayList<>();
msgs1.add("复杂的");
msgs1.add("域数据");
request.setAttribute("msgs1",msgs1);
%>
<%=
((List)request.getAttribute("msgs1")).get(0)
%>
${msgs1[1]}
<%
HashMap map = new HashMap<>();
map.put("username","白鸽");
map.put("age",18);
session.setAttribute("map",map);
%>
<%=
((HashMap)session.getAttribute("map")).get("username")
%>
${map.age}
<%
User user = new User();
user.setId(1);
user.setUsername("黑鸦");
user.setPassword("123456");
application.setAttribute("user",user);
%>
<%=
((User)application.getAttribute("user")).getUsername()
%>
${user.password}
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
int num = 1;
request.setAttribute("num" , num);
%>
num等于1
num不等于1
${msg}
${msg}
<%
int num = 1 / 0;
%>
${e}
num 等于 1
num 不等于 1
${num}
<%
List strs = new ArrayList<>();
strs.add("aaa");
strs.add("bbb");
strs.add("ccc");
request.setAttribute("strs",strs); %>
${strs[i]}
${str}
${status.current} -- ${status.index} -- ${status.first} -- ${status.last}
<%
String msg1 = "aaa--bbb--ccc";
request.setAttribute("msg1",msg1);
%>
${sonMsg}
public class ProductDaoImpl implements ProductDao {
@Override
public List selectProductList() throws Exception {
return new QueryRunner(JDBCUtils.getDataSource())
.query("select * from tb_product",
new BeanListHandler(Product.class));
}
}
@WebServlet(name = "ProductServlet" ,urlPatterns = "/selectProductList")
public class ProductServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ProductDao productDao = new ProductDaoImpl();
try {
List productList = productDao.selectProductList();
System.out.println(productList);
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
ID
名称
单价
数量
小计
<%--循环之前,总价为0--%>
<%--forEach标签,循环一次就是一个小计!--%>
${product.id}
${product.name}
${product.price}
${product.count}
${product.price * product.count}
<%--循环之后,计算出总价--%>
总价:${total}元
页面上的name属性值要和java对象中的属性名一致
public class MyBeanUtils {
/**
* 将map集合中的请求参数值封装到对象t中
* @param t
* @param map : 键:参数名称;值:一组参数值。
* @param
*/
public static void populate(T t , Map map ){
Class> clazz = t.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
String fieldName = field.getName();
String methodName = "set"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);
System.out.println(methodName);
//获取对应的set方法
try {
Class> type = field.getType();
Method method = clazz.getMethod(methodName, type);
if (null != method) {
//第二个参数:请求参数的值
//id、username、password、age
Object object = map.get(fieldName);
if (null != object) {
String[] strs = (String[]) object;
if (type.getName().equals("java.lang.Integer")) {
method.invoke(t,Integer.parseInt(strs[0]));
} else {
method.invoke(t,strs[0]);
}
}
}
} catch (Exception e) {
throw new MyNoSuchMethodException("field " + fieldName + " there is no setter method!!!");
}
}
}
}
public class MyNoSuchMethodException extends RuntimeException{
public MyNoSuchMethodException() {
}
public MyNoSuchMethodException(String message) {
super(message);
}
public MyNoSuchMethodException(String message, Throwable cause) {
super(message, cause);
}
public MyNoSuchMethodException(Throwable cause) {
super(cause);
}
public MyNoSuchMethodException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
@Override
public User login(User inputUser) throws Exception {
return new QueryRunner(JDBCUtils.getDataSource())
.query("select * from tb_user where username = ? and password = ?",
new BeanHandler(User.class),
inputUser.getUsername(),
inputUser.getPassword());
}
@Override
public User login(User inputUser) throws Exception {
UserDao userDao = new UserDaoImpl();
return userDao.login(inputUser);
}
private UserService userService = new UserServiceImpl();
public String login(HttpServletRequest request,HttpServletResponse response){
User inputUser = new User();
//将请求参数封装到inputUser中
try {
BeanUtils.populate(inputUser,request.getParameterMap());
User existUser = userService.login(inputUser);
//没有异常有返回值
if (null != existUser) {
//登录成功 , 修改登录状态,跳转到首页
request.getSession().setAttribute("existUser",existUser);
return "redirect:/index.jsp";
} else {
//登录失败 ,记录错误信息,跳转到登录页面
request.setAttribute("errorMsg","账户或密码错误");
return "/login.jsp";
}
} catch (Exception e) {
e.printStackTrace();
}
//有异常,应该有返回值 。意味着登录失败,返回登录页面,重新登录
return "/login.jsp";
}
${errorMsg}
<%--
在登录状态
显示用户名
--%>
欢迎回来~~~ ${existUser.username} 注销
<%--
不在登录状态
提示登录
--%>
您还没有登录,请登录
@Override
public List selectUserList() throws Exception {
return new QueryRunner(JDBCUtils.getDataSource())
.query("select * from tb_user",
new BeanListHandler(User.class));
}
public String selectUserList(HttpServletRequest request,HttpServletResponse response) throws Exception {
List userList = userService.selectUserList();
request.getSession().setAttribute("userList",userList);
return "/index.jsp";
}
<%--
在登录状态
显示用户名
--%>
欢迎回来~~~ ${existUser.username} 注销
<%--显示用户列表--%>
ID
账户
密码
${user.id}
${user.username}
${user.password}
<%--
不在登录状态
提示登录
--%>
您还没有登录,请登录
@WebFilter(filterName = "LoginFilter" ,urlPatterns = "/*")
public class LoginFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
System.out.println("LoginFilter doFilter");
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
//登录校验
String requestURI = request.getRequestURI();
String methodName = request.getParameter("methodName");
if (requestURI.contains("login") || ( methodName != null && methodName.equals("login"))) {
//和登录相关的资源,直接放行
chain.doFilter(req, resp);
} else {
//和登录无关的资源
Object existUser = request.getSession().getAttribute("existUser");
if (null == existUser) {
//不在登录状态,跳转到login.jsp
response.sendRedirect("/day64/login.jsp");
} else {
//在登录状态,直接放行
chain.doFilter(req, resp);
}
}
}
public void init(FilterConfig config) throws ServletException {
}
}
@Override
public int deleteUserById(Integer id) throws Exception {
return new QueryRunner(JDBCUtils.getDataSource())
.update("delete from tb_user where id = ?",id);
}
@Override
public boolean deleteUserById(Integer id) throws Exception {
return userDao.deleteUserById(id) == 1;
}
public String deleteUserById(HttpServletRequest request,HttpServletResponse response){
Integer id = Integer.parseInt(request.getParameter("id"));
try {
boolean flag = userService.deleteUserById(id);
} catch (Exception e) {
e.printStackTrace();
}
//获取用户列表
return "/user?methodName=selectUserList";
}
${user.id}
${user.username}
${user.password}
删除
@Override
public void updateUserById(User inputUser) throws Exception {
new QueryRunner(JDBCUtils.getDataSource())
.update("update tb_user set username = ? , password = ? where id = ?",
inputUser.getUsername(),
inputUser.getPassword(),
inputUser.getId());
}
public String toUpdateUserById(HttpServletRequest request,HttpServletResponse response) {
Integer id = Integer.parseInt(request.getParameter("id"));
User user = null;
try {
user = userService.selectUserById(id);
} catch (Exception e) {
e.printStackTrace();
}
request.setAttribute("user",user);
return "/updateUser.jsp";
}
public String updateUserById(HttpServletRequest request,HttpServletResponse response){
User inputUser = new User();
try {
BeanUtils.populate(inputUser,request.getParameterMap());
userService.updateUserById(inputUser);
//修改成功
return "/user?methodName=selectUserList";
} catch (Exception e) {
e.printStackTrace();
}
request.setAttribute("errorMsg","修改失败");
//修改失败
return "/user?methodName=toUpdateUserById&id="+inputUser.getId();
}
${errorMsg}
public class UserDaoImpl implements UserDao {
@Override
public Integer selectTotalSize() throws Exception {
return new QueryRunner(JDBCUtils.getDataSource())
.query("select * from tb_user",
new BeanListHandler(User.class))
.size();
}
@Override
public List selectUserListByPage(Integer begin, Integer pageSize) throws Exception {
return new QueryRunner(JDBCUtils.getDataSource())
.query("select * from tb_user limit ? , ?" ,
new BeanListHandler(User.class),
begin,
pageSize);
}
}
public String selectUserListByPage(HttpServletRequest request, HttpServletResponse response){
String currentPageStr = request.getParameter("currentPage");
Integer currentPage = getCurrentPage(currentPageStr);
//调用UserService,传递currentPage
try {
PageBean pageBean = userService.selectUserListByPage(currentPage);
System.out.println(pageBean);
request.setAttribute("pageBean",pageBean);
//转发到用户列表页面
return "/userList.jsp";
} catch (Exception e) {
e.printStackTrace();
}
return "/index.jsp";
}
public PageBean selectUserListByPage(Integer currentPage) throws Exception {
PageBean pageBean = new PageBean<>();
// currentPage;当前页数
pageBean.setCurrentPage(currentPage);
// totalSize;总记录数
UserDao userDao = new UserDaoImpl();
Integer totalSize = userDao.selectTotalSize();
pageBean.setTotalSize(totalSize);
// pageSize;每页记录数
Integer pageSize = 3;
pageBean.setPageSize(pageSize);
// totalPage:总页数 = 总记录数 / 每页记录数
Integer totalPage = ( totalSize % pageSize == 0 ) ? ( totalSize / pageSize ) : (totalSize / pageSize + 1 ) ;
pageBean.setTotalPage(totalPage);
// list;当前页数据
//select * from tb_user limit ? , ?
//第一个? : 开始脚标 = (当前页数 - 1) * 每页记录数
//第二个? : 查询多少个 (每页记录数) pageSize
Integer begin = (currentPage - 1) * pageSize;
List list = userDao.selectUserListByPage(begin, pageSize);
pageBean.setList(list);
return pageBean;
}
ID
账户
密码
${user.id}
${user.username}
${user.password}
<%--分页工具条--%>
第${pageBean.currentPage}/${pageBean.totalPage}页
总记录数:${pageBean.totalSize}
每页显示${pageBean.pageSize}条
[首页]
[上一页]
[下一页]
[尾页]