${pagecontext.request.contextpath}的意义、当前台数据获取的时间为String类型需要转化为Date类型插入到数据库时 (局部转换)

本文详细介绍了Java Web开发中常见的问题及解决方案,包括EL表达式的使用、解决输出乱码、前后台日期转换、复合主键配置、利用Session跨Controller传递数据等关键知识点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

          1.${pagecontext.request.contextpath}作用
${pageContext.request.contextPath}等价于<%=request.getContextPath()%> 
或者可以说是<%=request.getContextPath()%>的EL版 
意思就是取出部署的应用程序名或者是当前的项目名称
比如我的项目名称是quickstart在浏览器中输入为http://localhost:8080/quickstart/register.jsp 
${pageContext.request.contextPath}或<%=request.getContextPath()%>取出来的就是/quickstart,而"/"代表的含义就是http://localhost:8080
所以我们项目中应该这样写${pageContext.request.contextPath}/register.jsp
${pageContext.request.contextPath}用于解决使用相对路径时出现的问题,它的作用是取出所部署项目的名字。
      2.输出乱码(在页面内上显示信息)
例如
  result="<font color='red'>该用户名已经被使用</font>"
  response.setContentType("text/html");
  response.setCharacterEncoding("UTF-8");//response.setContentType("text/html;charset=UTF-8")
  response.getWriter().print(result);
   3.当前台数据获取的时间为String类型需要转化为Date类型插入到数据库时
(局部转换)
 @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request) {
        
        //转换日期
        DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));// CustomDateEditor为自定义日期编辑器
    }

(全局转换)
1.创建CustomDate类实现WebBindingInitializer
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.WebRequest;
 
public class CustomDate implements WebBindingInitializer{
 
    @Override
    public void initBinder(WebDataBinder binder, WebRequest request) {
        // TODO Auto-generated method stub
        //转换日期
        DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
}

2.在Spring-MVC.xml中配置日期转换
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
    <context:component-scan base-package="com.gwd.shopping" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    
    <!-- 日期转换 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="webBindingInitializer">
            <bean class="com.gwd.shopping.core.web.CustomDate"/>
        </property>
    </bean>
    
    <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/back_page/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>
4.Date日期的相加减
 Date d=new Date();   
 SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");   
 System.out.println("今天的日期:"+df.format(d));   
 System.out.println("两天前的日期:" + df.format(new Date(d.getTime() - (long)2 * 24 * 60 * 60 * 1000)));  
   System.out.println("三天后的日期:" + df.format(new Date(d.getTime() + (long)3 * 24 * 60 * 60 * 1000)));
获取某天的年月日:
int year =calendar.get(Calendar.YEAR);    
int month=calendar.get(Calendar.MONTH)+1;
int day =calendar.get(Calendar.DAY_OF_MONTH);    
int hour =calendar.get(Calendar.HOUR_OF_DAY);    
int minute =calendar.get(Calendar.MINUTE);    
int seconds =calendar.get(Calendar.SECOND);   
5.复合主键注意在映射hibernate时,注意无论只进行查询操作,都需要配好复合主键,否则查询就会出错。
6.在controller传给前台的list中,注意加上前缀,否则可能得不到其值。
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
7.利用Session在两个Controller中传递
@Controller
public class ManagerController {
 
    @Resource
    private ManagerService managerServiceImpl;
    
    @RequestMapping(value = "manager/login.do",method = RequestMethod.GET)  
    public ModelAndView login(ManagerModel managerModel,HttpSession httpSession){
        
        ManagerModel manager = managerServiceImpl.getManager(managerModel);
        if(manager!=null){
            manager.setPassword("");
            httpSession.setAttribute("manager", manager);
            return new ModelAndView(new RedirectView("../admin/main.jsp"));
        }else{
            return new ModelAndView(new RedirectView("../admin/login.jsp"));
        }
    }
    
    @RequestMapping(value = "manager/logout.do",method = RequestMethod.GET)
    public String logout(HttpSession httpSession){
        httpSession.getAttribute("manager");
        return "success";
    }
}
8.
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd 
                        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"
    default-autowire="byName">

Sep 8, 2018 12:00:00 AM
 

题。 这是一个比较全面的JavaWeb应用,需要涉及到数据库操作、JSP页面、Servlet程序以及Filter过滤器等多个方面。下面我会分别介绍一下各个方面的实现。 一、数据库连接池C3P0及JDBC技术 1.1 数据库准备 首先需要准备好一个数据库,在本例中我们使用MySQL数据库。创建一个名为student的数据库,并在该数据库中创建一个名为stu_info的表,包含学号、姓名、性别、出生日期、所在院系、爱好、个人简介等信息。 1.2 C3P0连接池配置 使用C3P0连接池可以有效地提高数据库连接的效率和稳定性。在项目中,我们需要在web.xml文件中配置一个参数,用来指定C3P0配置文件的路径。 ```xml <context-param> <param-name>configLocation</param-name> <param-value>/WEB-INF/c3p0-config.xml</param-value> </context-param> ``` 然后在项目的WEB-INF目录下创建一个名为c3p0-config.xml的文件,并在其中进行连接池的配置。 ```xml <?xml version="1.0" encoding="UTF-8"?> <c3p0-config> <default-config> <property name="jdbcUrl">jdbc:mysql://localhost:3306/student</property> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="user">root</property> <property name="password">123456</property> <property name="maxPoolSize">50</property> <property name="minPoolSize">5</property> <property name="initialPoolSize">10</property> <property name="maxIdleTime">1800</property> <property name="acquireIncrement">3</property> <property name="idleConnectionTestPeriod">60</property> <property name="checkoutTimeout">10000</property> </default-config> </c3p0-config> ``` 1.3 JDBC编程 在JavaWeb应用中,我们需要使用JDBC技术来连接数据库并进行数据的增删改查。在本例中,我们可以使用以下代码来连接数据库并查询学生信息。 ```java public class StudentDao { private ComboPooledDataSource dataSource; public StudentDao() throws Exception { dataSource = new ComboPooledDataSource(); } // 获取学生信息 public List<Student> getStudents() { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; List<Student> students = new ArrayList<Student>(); try { conn = dataSource.getConnection(); String sql = "SELECT * FROM stu_info"; stmt = conn.prepareStatement(sql); rs = stmt.executeQuery(); while (rs.next()) { Student student = new Student(); student.setSno(rs.getString("sno")); student.setName(rs.getString("name")); student.setSex(rs.getString("sex")); student.setBirthday(rs.getDate("birthday")); student.setDepartment(rs.getString("department")); student.setHobby(rs.getString("hobby")); student.setIntro(rs.getString("intro")); students.add(student); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return students; } } ``` 二、JSP页面 在JavaWeb应用中,我们通常需要使用JSP页面来实现前端页面的展示和用户交互。在本例中,我们需要设计三个JSP页面,分别是addStu.jsp、editStu.jsp和stuList.jsp。其中,addStu.jsp页面用来添加学生信息,editStu.jsp页面用来编辑学生信息,stuList.jsp页面用来展示学生信息列表。 addStu.jsp页面代码: ```html <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>添加学生信息</title> </head> <body> <h1>添加学生信息</h1> <form action="${pageContext.request.contextPath}/saveStudent" method="post"> <table> <tr> <td>学号:</td> <td><input type="text" name="sno"></td> </tr> <tr> <td>姓名:</td> <td><input type="text" name="name"></td> </tr> <tr> <td>性别:</td> <td> <input type="radio" name="sex" value="男">男 <input type="radio" name="sex" value="女">女 </td> </tr> <tr> <td>出生日期:</td> <td><input type="date" name="birthday"></td> </tr> <tr> <td>所在院系:</td> <td><input type="text" name="department"></td> </tr> <tr> <td>爱好:</td> <td><input type="text" name="hobby"></td> </tr> <tr> <td>个人简介:</td> <td><textarea name="intro"></textarea></td> </tr> <tr> <td colspan="2"> <input type="submit" value="保存"> <input type="reset" value="重置"> </td> </tr> </table> </form> </body> </html> ``` editStu.jsp页面代码: ```html <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>编辑学生信息</title> </head> <body> <h1>编辑学生信息</h1> <form action="${pageContext.request.contextPath}/editStudent" method="post"> <table> <tr> <td>学号:</td> <td><input type="text" name="sno" value="${student.sno}" readonly></td> </tr> <tr> <td>姓名:</td> <td><input type="text" name="name" value="${student.name}"></td> </tr> <tr> <td>性别:</td> <td> <input type="radio" name="sex" value="男" ${student.sex == '男' ? 'checked' : ''}>男 <input type="radio" name="sex" value="女" ${student.sex == '女' ? 'checked' : ''}>女 </td> </tr> <tr> <td>出生日期:</td> <td><input type="date" name="birthday" value="${student.birthday}"></td> </tr> <tr> <td>所在院系:</td> <td><input type="text" name="department" value="${student.department}"></td> </tr> <tr> <td>爱好:</td> <td><input type="text" name="hobby" value="${student.hobby}"></td> </tr> <tr> <td>个人简介:</td> <td><textarea name="intro">${student.intro}</textarea></td> </tr> <tr> <td colspan="2"> <input type="submit" value="保存"> <input type="reset" value="重置"> </td> </tr> </table> </form> </body> </html> ``` stuList.jsp页面代码: ```html <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>学生信息列表</title> </head> <body> <h1>学生信息列表</h1> <table border="1"> <tr> <th>学号</th> <th>姓名</th> <th>性别</th> <th>出生日期</th> <th>所在院系</th> <th>爱好</th> <th>个人简介</th> <th>操作</th> </tr> <c:forEach items="${students}" var="student"> <tr> <td>${student.sno}</td> <td>${student.name}</td> <td>${student.sex}</td> <td>${student.birthday}</td> <td>${student.department}</td> <td>${student.hobby}</td> <td>${student.intro}</td> <td> <a href="${pageContext.request.contextPath}/editStu?sno=${student.sno}">编辑</a> <a href="${pageContext.request.contextPath}/delStudent?sno=${student.sno}">删除</a> </td> </tr> </c:forEach> </table> <br> <a href="${pageContext.request.contextPath}/addStu.jsp">添加学生信息</a> </body> </html> ``` 三、Servlet程序 在JavaWeb应用中,我们需要使用Servlet程序来处理HTTP请求和响应。在本例中,我们需要设计四个Servlet程序,分别是SaveStudentServlet、EditStudentServlet、DelStudentServlet和SearchStudentServlet。 SaveStudentServlet用来保存学生信息,EditStudentServlet用来编辑学生信息,DelStudentServlet用来删除学生信息,SearchStudentServlet用来查询学生信息。 SaveStudentServlet代码: ```java public class SaveStudentServlet extends HttpServlet { private static final long serialVersionUID = 1L; private StudentDao studentDao; public SaveStudentServlet() { super(); } public void init() throws ServletException { try { studentDao = new StudentDao(); } catch (Exception e) { e.printStackTrace(); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String sno = request.getParameter("sno"); String name = request.getParameter("name"); String sex = request.getParameter("sex"); String birthday = request.getParameter("birthday"); String department = request.getParameter("department"); String hobby = request.getParameter("hobby"); String intro = request.getParameter("intro"); Student student = new Student(); student.setSno(sno); student.setName(name); student.setSex(sex); student.setBirthday(Date.valueOf(birthday)); student.setDepartment(department); student.setHobby(hobby); student.setIntro(intro); try { studentDao.addStudent(student); } catch (Exception e) { e.printStackTrace(); } response.sendRedirect(request.getContextPath() + "/stuList"); } } ``` EditStudentServlet代码: ```java public class EditStudentServlet extends HttpServlet { private static final long serialVersionUID = 1L; private StudentDao studentDao; public EditStudentServlet() { super(); } public void init() throws ServletException { try { studentDao = new StudentDao(); } catch (Exception e) { e.printStackTrace(); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String sno = request.getParameter("sno"); Student student = null; try { student = studentDao.getStudent(sno); } catch (Exception e) { e.printStackTrace(); } request.setAttribute("student", student); request.getRequestDispatcher("/editStu.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String sno = request.getParameter("sno"); String name = request.getParameter("name"); String sex = request.getParameter("sex"); String birthday = request.getParameter("birthday"); String department = request.getParameter("department"); String hobby = request.getParameter("hobby"); String intro = request.getParameter("intro"); Student student = new Student(); student.setSno(sno); student.setName(name); student.setSex(sex); student.setBirthday(Date.valueOf(birthday)); student.setDepartment(department); student.setHobby(hobby); student.setIntro(intro); try { studentDao.updateStudent(student); } catch (Exception e) { e.printStackTrace(); } response.sendRedirect(request.getContextPath() + "/stuList"); } } ``` DelStudentServlet代码: ```java public class DelStudentServlet extends HttpServlet { private static final long serialVersionUID = 1L; private StudentDao studentDao; public DelStudentServlet() { super(); } public void init() throws ServletException { try { studentDao = new StudentDao(); } catch (Exception e) { e.printStackTrace(); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String sno = request.getParameter("sno"); try { studentDao.delStudent(sno); } catch (Exception e) { e.printStackTrace(); } response.sendRedirect(request.getContextPath() + "/stuList"); } } ``` SearchStudentServlet代码: ```java public class SearchStudentServlet extends HttpServlet { private static final long serialVersionUID = 1L; private StudentDao studentDao; public SearchStudentServlet() { super(); } public void init() throws ServletException { try { studentDao = new StudentDao(); } catch (Exception e) { e.printStackTrace(); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); String keyword = request.getParameter("keyword"); List<Student> students = null; try { students = studentDao.searchStudent(keyword); } catch (Exception e) { e.printStackTrace(); } request.setAttribute("students", students); request.getRequestDispatcher("/stuList.jsp").forward(request, response); } } ``` 四、Filter过滤器 在JavaWeb应用中,我们需要使用Filter过滤器来对HTTP请求和响应进行过滤处理。在本例中,我们需要使用Filter过滤器来解决POST提交方式的中文乱码问题。 Filter过滤器代码: ```java public class EncodingFilter implements Filter { private String encoding = "UTF-8"; public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { request.setCharacterEncoding(encoding); response.setCharacterEncoding(encoding); filterChain.doFilter(request, response); } public void init(FilterConfig filterConfig) throws ServletException { String encodingParam = filterConfig.getInitParameter("encoding"); if (encodingParam != null) { encoding = encodingParam; } } public void destroy() { } } ``` 在web.xml文件中配置Filter过滤器: ```xml <filter> <filter-name>encodingFilter</filter-name> <filter-class>com.example.EncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> ``` 以上就是本例中JavaWeb应用的实现,包括C3P0连接池的配置、JSP页面的设计、Servlet程序的编写以及Filter过滤器的使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值