zoukankan      html  css  js  c++  java
  • Spring与Web

    一、定义页面及Servlet

     在jsp页面加入以下,避免乱码

    <meta charset="utf-8">
    <body>
        <form action="RegisterServlte" method="post">
            姓名:<input type="text" name="name" /><br> 
            年龄:<input type="text" name="age" /><br> 
            <input type="submit" value="注册" />
        </form>
      </body>
    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.jmu.beans.Student;
    
    /**
     * Servlet implementation class RegisterServlte
     */
    public class RegisterServlte extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        /**
         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
            doPost(request, response);
        }
    
        /**
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
            request.setCharacterEncoding("utf-8");
            String name=request.getParameter("name");
            String ageStr=request.getParameter("age");
            Integer age=Integer.valueOf(ageStr);
            Student student=new Student(name,age);
    
            request.getRequestDispatcher("/welcome.jsp").forward(request, response);
        }
    
    }

    三、测试环境搭建

     1 public class Student {
     2     private Integer id;
     3     private String name;
     4     private int age;
     5 
     6     
     7     public Student() {
     8         super();
     9     }
    10 
    11     public Student( String name, int age) {
    12         super();
    13         this.name = name;
    14         this.age = age;
    15     }
    16 
    17     public Integer getId() {
    18         return id;
    19     }
    20 
    21     public void setId(Integer id) {
    22         this.id = id;
    23     }
    24 
    25     public String getName() {
    26         return name;
    27     }
    28 
    29     public void setName(String name) {
    30         this.name = name;
    31     }
    32 
    33     public int getAge() {
    34         return age;
    35     }
    36 
    37     public void setAge(int age) {
    38         this.age = age;
    39     }
    40 
    41     @Override
    42     public String toString() {
    43         return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
    44     }
    45 
    46 }
    Student
     1 //Dao增删改查
     2 public interface IStudentDao {
     3     void insertStudent(Student student);
     4     void deleteById(int id);
     5     void updateStudent(Student student);
     6 
     7 
     8     List<Student> selectAllStudents();
     9     Student selectStudentById(int id);
    10 }
    IStudentDao
     1 <?xml version="1.0" encoding="UTF-8" ?>
     2 <!DOCTYPE mapper
     3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
     4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
     5 <mapper namespace="com.jmu.dao.IStudentDao">
     6     <insert id="insertStudent">
     7         insert into student(name,age) values(#{name},#{age})
     8     </insert>
     9 
    10     <delete id="deleteById">
    11         delete from student where id=#{XXX}
    12     </delete>
    13 
    14     <update id="updateStudent">
    15         update student set name=#{name},age=#{age} where id=#{id}
    16     </update>
    17 
    18     <select id="selectAllStudents" resultType="student">
    19         select id,name,age from student
    20     </select>
    21 
    22     <select id="selectStudentById" resultType="student">
    23         select id,name,age from student where id=#{XXX}
    24     </select>
    25 </mapper>
    IStudentDao.xml
    IStudentService
     1 public class StudentServiceImpl implements IStudentService {
     2     private IStudentDao dao;
     3 
     4     public void setDao(IStudentDao dao) {
     5         this.dao = dao;
     6     }
     7 
     8 
     9     public void addStudent(Student student) {
    10         // TODO Auto-generated method stub
    11         dao.insertStudent(student);
    12 
    13     }
    14 
    15     
    16     public void removeById(int id) {
    17         // TODO Auto-generated method stub
    18         dao.deleteById(id);
    19     }
    20 
    21     
    22     public void modifyStudent(Student student) {
    23         // TODO Auto-generated method stub
    24         dao.updateStudent(student);
    25     }
    26 
    27     
    28     public List<String> findAllStudentsNames() {
    29         // TODO Auto-generated method stub
    30         List<String> names = new ArrayList<String>();
    31         List<Student> sudents = this.findAllStudents();
    32         for (Student student : sudents) {
    33           names.add(student.getName());
    34         }
    35         return names;
    36     }
    37 
    38     
    39     public String findStudentNameById(int id) {
    40         // TODO Auto-generated method stub
    41         Student student = this.findStudentById(id);
    42         return student.getName();
    43     }
    44 
    45     
    46     public List<Student> findAllStudents() {
    47         // TODO Auto-generated method stub
    48         return dao.selectAllStudents();
    49     }
    50 
    51     
    52     public Student findStudentById(int id) {
    53         // TODO Auto-generated method stub
    54         return dao.selectStudentById(id);
    55     }
    56 
    57 }
    StudentServiceImpl
    // 获取Spring容器对象
            ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
            // 从Spring容器中获取到service对象
            IStudentService service = (IStudentService) ac.getBean("studentService");
            // 调用Service的addStudent()完成插入
            service.addStudent(student);
    RegisterServlet
     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <beans xmlns="http://www.springframework.org/schema/beans"
     3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
     4     xsi:schemaLocation="
     5         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
     6         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
     7 
     8 
     9     <!--注册数据源:C3P0 -->
    10     <bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    11         <property name="driverClass" value="${jdbc.driver}" />
    12         <property name="jdbcUrl" value="${jdbc.url}" />
    13         <property name="user" value="${jdbc.user}" />
    14         <property name="password" value="${jdbc.password}" />
    15     </bean>
    16 
    17     <!-- 注册属性文件 -->
    18     <context:property-placeholder location="classpath:jdbc.properties" />
    19     
    20     <bean id="mySqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    21        <property name="configLocation" value="classpath:mybatis.xml"></property>
    22        <property name="dataSource" ref="myDataSource"></property>
    23     </bean>
    24     
    25     
    26     <!--生成Dao的代理对象 
    27      当前配置会被本包中所有的接口生成代理对象
    28     -->
    29     <bean  class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    30         <property name="sqlSessionFactoryBeanName" value="mySqlSessionFactory" />
    31         <property name="basePackage" value="com.jmu.dao" />
    32     </bean>
    33 
    34     <!-- 注册Service -->
    35     <bean id="studentService" class="com.jmu.service.StudentServiceImpl">
    36          <!-- 这里的Dao的注入需要使用ref属性,且其作为接口的简单类名 -->
    37         <property name="dao" ref="IStudentDao" />
    38     </bean>
    39 </beans>
    applicationContext.xml
     1 <?xml version="1.0" encoding="UTF-8" ?>
     2 <!DOCTYPE configuration
     3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
     4 "http://mybatis.org/dtd/mybatis-3-config.dtd">
     5 <configuration>
     6 
     7     <!--配置别名 -->
     8     <typeAliases>
     9         <package name="com.jmu.beans" />
    10     </typeAliases>
    11 
    12     <mappers>
    13         <package name="com.jmu.dao" />
    14     </mappers>
    15 
    16 </configuration>
    mybatis.xml

    四、当前程序存在问题

    刷新会创建不同spring容器对象,而不同servlet创建不同容器。当一个应用只能有一个spring容器

    五、注册ContextLoaderListener

    复制之前web项目,需要修改web context root 

    ctrl+shift+t open Type
    ctrl+o 查看结构
    ctrl+t 查看继承关系
    myeclipse快捷键

    方法一:读源码ContextLoaderListener与ContextLoader获取key

    注册ServletContext监听器,完成2件工作:

    1、在Servletcontext被创建时,创建Spring容器对象;

    2、将创建好的Spring容器对象放入到ServletContext的域属性空间

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    修改applicationContext.xml为spring.xml在web.xml中添加如下(Spring在web项目中必须有的2项配置):

     <context-param>
        <param-name>contextConfigLocation </param-name>
        <param-value>classpath:spring.xml</param-value>
      </context-param>
    <!--   注册servletContext监听器 -->
      <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>

    修改servlet中

        // 获取Spring容器对象
            String acKey = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
            ApplicationContext ac = (ApplicationContext) this.getServletContext().getAttribute(acKey);
     1 public class RegisterServlet extends HttpServlet {
     2     private static final long serialVersionUID = 1L;
     3 
     4     /**
     5      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     6      *      response)
     7      */
     8     protected void doGet(HttpServletRequest request, HttpServletResponse response)
     9             throws ServletException, IOException {
    10         // TODO Auto-generated method stub
    11         doPost(request, response);
    12     }
    13 
    14     /**
    15      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
    16      *      response)
    17      */
    18     protected void doPost(HttpServletRequest request, HttpServletResponse response)
    19             throws ServletException, IOException {
    20         // TODO Auto-generated method stub
    21         request.setCharacterEncoding("utf-8");
    22         String name = request.getParameter("name");
    23         String ageStr = request.getParameter("age");
    24         Integer age = Integer.valueOf(ageStr);
    25         Student student = new Student(name, age);
    26         // 获取Spring容器对象
    27         String acKey = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
    28         ApplicationContext ac = (ApplicationContext) this.getServletContext().getAttribute(acKey);
    29         // 从Spring容器中获取到service对象
    30         IStudentService service = (IStudentService) ac.getBean("studentService");
    31         // 调用Service的addStudent()完成插入
    32         service.addStudent(student);
    33         request.getRequestDispatcher("/welcome.jsp").forward(request, response);
    34     }
    35 
    36 }
    RegisterServlet
     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <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" id="WebApp_ID" version="2.5">
     3   <display-name>17-spring-web</display-name>
     4   <welcome-file-list>
     5     <welcome-file>index.jsp</welcome-file>
     6   </welcome-file-list>
     7   
     8   <context-param>
     9     <param-name>contextConfigLocation </param-name>
    10     <param-value>classpath:spring.xml</param-value>
    11   </context-param>
    12 <!--   注册servletContext监听器 -->
    13   <listener>
    14     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    15   </listener>
    16   <servlet>
    17     <description></description>
    18     <display-name>RegisterServlet</display-name>
    19     <servlet-name>RegisterServlet</servlet-name>
    20     <servlet-class>com.jmu.servlets.RegisterServlet</servlet-class>
    21   </servlet>
    22   <servlet-mapping>
    23     <servlet-name>RegisterServlet</servlet-name>
    24     <url-pattern>/RegisterServlet</url-pattern>
    25   </servlet-mapping>
    26   <servlet>
    27     <description></description>
    28     <display-name>LoginServlet</display-name>
    29     <servlet-name>LoginServlet</servlet-name>
    30     <servlet-class>com.jmu.servlets.LoginServlet</servlet-class>
    31   </servlet>
    32   <servlet-mapping>
    33     <servlet-name>LoginServlet</servlet-name>
    34     <url-pattern>/LoginServlet</url-pattern>
    35   </servlet-mapping>
    36 </web-app>
    web.xml

    方法二:使用工具类获取Spring容器

    修改servlet中

        // 获取Spring容器对象
            WebApplicationContext ac= WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
  • 相关阅读:
    Erlang in Delphi 项目发布!
    云计算将如何改变世界
    win2000server IIS和tomcat5多站点配置
    实践中整理出tomcat集群和负载均衡
    VCL已死,RAD已死(6) 结语与预测
    window下tomcat集群和负载均衡
    团队开发经验:如何带领一个项目团队并做好项目总结 !!
    Install latest R for ubuntu
    P1297 单选错位
    P5322 排兵布阵
  • 原文地址:https://www.cnblogs.com/hoje/p/8525706.html
Copyright © 2011-2022 走看看