一、定义页面及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);
} }

三、测试环境搭建

 public class Student {
private Integer id;
private String name;
private int age; public Student() {
super();
} public Student( String name, int age) {
super();
this.name = name;
this.age = age;
} public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} @Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
} }

Student

 //Dao增删改查
public interface IStudentDao {
void insertStudent(Student student);
void deleteById(int id);
void updateStudent(Student student); List<Student> selectAllStudents();
Student selectStudentById(int id);
}

IStudentDao

 <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jmu.dao.IStudentDao">
<insert id="insertStudent">
insert into student(name,age) values(#{name},#{age})
</insert> <delete id="deleteById">
delete from student where id=#{XXX}
</delete> <update id="updateStudent">
update student set name=#{name},age=#{age} where id=#{id}
</update> <select id="selectAllStudents" resultType="student">
select id,name,age from student
</select> <select id="selectStudentById" resultType="student">
select id,name,age from student where id=#{XXX}
</select>
</mapper>

IStudentDao.xml

IStudentService
 public class StudentServiceImpl implements IStudentService {
private IStudentDao dao; public void setDao(IStudentDao dao) {
this.dao = dao;
} public void addStudent(Student student) {
// TODO Auto-generated method stub
dao.insertStudent(student); } public void removeById(int id) {
// TODO Auto-generated method stub
dao.deleteById(id);
} public void modifyStudent(Student student) {
// TODO Auto-generated method stub
dao.updateStudent(student);
} public List<String> findAllStudentsNames() {
// TODO Auto-generated method stub
List<String> names = new ArrayList<String>();
List<Student> sudents = this.findAllStudents();
for (Student student : sudents) {
names.add(student.getName());
}
return names;
} public String findStudentNameById(int id) {
// TODO Auto-generated method stub
Student student = this.findStudentById(id);
return student.getName();
} public List<Student> findAllStudents() {
// TODO Auto-generated method stub
return dao.selectAllStudents();
} public Student findStudentById(int id) {
// TODO Auto-generated method stub
return dao.selectStudentById(id);
} }

StudentServiceImpl

// 获取Spring容器对象
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
// 从Spring容器中获取到service对象
IStudentService service = (IStudentService) ac.getBean("studentService");
// 调用Service的addStudent()完成插入
service.addStudent(student);

RegisterServlet

 <?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--注册数据源:C3P0 -->
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.user}" />
<property name="password" value="${jdbc.password}" />
</bean> <!-- 注册属性文件 -->
<context:property-placeholder location="classpath:jdbc.properties" /> <bean id="mySqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis.xml"></property>
<property name="dataSource" ref="myDataSource"></property>
</bean> <!--生成Dao的代理对象
当前配置会被本包中所有的接口生成代理对象
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="mySqlSessionFactory" />
<property name="basePackage" value="com.jmu.dao" />
</bean> <!-- 注册Service -->
<bean id="studentService" class="com.jmu.service.StudentServiceImpl">
<!-- 这里的Dao的注入需要使用ref属性,且其作为接口的简单类名 -->
<property name="dao" ref="IStudentDao" />
</bean>
</beans>

applicationContext.xml

 <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration> <!--配置别名 -->
<typeAliases>
<package name="com.jmu.beans" />
</typeAliases> <mappers>
<package name="com.jmu.dao" />
</mappers> </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);
 public class RegisterServlet 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);
// 获取Spring容器对象
String acKey = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
ApplicationContext ac = (ApplicationContext) this.getServletContext().getAttribute(acKey);
// 从Spring容器中获取到service对象
IStudentService service = (IStudentService) ac.getBean("studentService");
// 调用Service的addStudent()完成插入
service.addStudent(student);
request.getRequestDispatcher("/welcome.jsp").forward(request, response);
} }

RegisterServlet

 <?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" id="WebApp_ID" version="2.5">
<display-name>17-spring-web</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list> <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>
<description></description>
<display-name>RegisterServlet</display-name>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>com.jmu.servlets.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/RegisterServlet</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>LoginServlet</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.jmu.servlets.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
</web-app>

web.xml

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

修改servlet中

    // 获取Spring容器对象
WebApplicationContext ac= WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());

Spring与Web的更多相关文章

  1. 转载:如何让spring mvc web应用启动时就执行

    转载:如何让spring mvc web应用启动时就执行特定处理 http://www.cnblogs.com/yjmyzz/p/4747251.html# Spring-MVC的应用中 一.Appl ...

  2. Spring的web应用启动加载数据字典方法

    在一个基于Spring的web项目中,当我们需要在应用启动时加载数据字典时,可写一个监听实现javax.servlet.ServletContextListener 实现其中的contextIniti ...

  3. Spring实战5:基于Spring构建Web应用

    主要内容 将web请求映射到Spring控制器 绑定form参数 验证表单提交的参数 对于很多Java程序员来说,他们的主要工作就是开发Web应用,如果你也在做这样的工作,那么你一定会了解到构建这类系 ...

  4. 使用XFire+Spring构建Web Service(一)——helloWorld篇

    转自:http://www.blogjava.net/amigoxie/archive/2007/09/26/148207.html原文出处:http://tech.it168.com/j/2007- ...

  5. 使用Maven创建一个Spring MVC Web 项目

    使用Maven创建java web 项目(Spring MVC)用到如下工具: 1.Maven 3.2 2.IntelliJ IDEA 13 3.JDK 1.7 4.Spring 4.1.1 rele ...

  6. 使用XFire+Spring构建Web Service

    XFire是与Axis 2并列的新一代Web Service框架,通过提供简单的API支持Web Service各项标准协议,帮助你方便快速地开发Web Service应用. 相 对于Axis来说,目 ...

  7. 基于Spring的Web缓存

    缓存的基本思想其实是以空间换时间.我们知道,IO的读写速度相对内存来说是非常比较慢的,通常一个web应用的瓶颈就出现在磁盘IO的读写上.那么,如果我们在内存中建立一个存储区,将数据缓存起来,当浏览器端 ...

  8. Spring Boot Web Executable Demo

    Spring Boot Web Executable Demo */--> pre.src {background-color: #292b2e; color: #b2b2b2;} pre.sr ...

  9. Spring之WEB模块

    Spring的WEB模块用于整合Web框架,例如Struts 1.Struts 2.JSF等 整合Struts 1 继承方式 Spring框架提供了ActionSupport类支持Struts 1的A ...

  10. J2EE进阶(五)Spring在web.xml中的配置

     J2EE进阶(五)Spring在web.xml中的配置 前言 在实际项目中spring的配置文件applicationcontext.xml是通过spring提供的加载机制自动加载到容器中.在web ...

随机推荐

  1. Django 项目拆分配置文件settings.py

    使用Django命令生成一个项目的基本结构时, 配置信息默认保存在和项目目录同名的目录下的settings.py文件里, 对于一个项目而言, 这样往往是不合适的, 在实际的开发中,需要将配置文件拆分为 ...

  2. jzoj1792

    #include<bits/stdc++.h> using namespace std; long long a[100010],m,n; int main(){ scanf(" ...

  3. time 模块学习

    前情提要: time模块是经常使用的模块.主要是用来记录时间,以及时间上的相关操作 一:时间戳 1:第一种形式 import time print(time.time()) 从1970 1 1 0:0 ...

  4. lspci

    lspci 是一个用来显示系统中所有PCI总线设备或连接到该总线上的所有设备的工具. 列出所有的PCIE设备: lspci 选项: -v 使得 lspci 以冗余模式显示所有设备的详细信息. -vv ...

  5. (JAVA作业)练习:创建一个类名为Fruit;包含实例变量:水果名称,颜色,价格,上市月份,有无种子 10个实例:苹果,香蕉,芭乐,柚子,李子,杨桃,猕猴桃,哈密瓜,葡萄,榴莲; 实现功能:提示用户输入水果品种编号,输出该水果的全部信息。

    class Lei { String name; String color; int price; int date; int num; String zz; void assemble(){ Sys ...

  6. (转)Memcached 之 .NET(C#)实例分析

    一:Memcached的安装 step1. 下载memcache(http://jehiah.cz/projects/memcached-win32)的windows稳定版(这里我下载了memcach ...

  7. (转)aix非计算内存 占用过高 案例一则

    原文:http://www.talkwithtrend.com/Article/28621 两台小型机组成的RAC环境,在用topas查看资源使用情况时,发现一台机器的非计算内存占用过高: MEMOR ...

  8. 【Sublime】Sublime插件

    alignmentcodecs33convertToUtf8sublimeAstyleFormattersublimeLintersublimeLInter-contrib-clangtagInput ...

  9. 创建自己的加密货币MNC——以太坊代币(二)

    创建一个基于以太坊平台的分红币MNC,根据持有的代币数量,进行分红的算法.github地址: https://github.com/lxr1907/MNC 1.使用以太坊根据比例换购token MNC ...

  10. python-FTP模块

    #!/user/bin/python #coding=utf-8 import ftplib import os import socket HOST = 'ftp.kernel.org' DIRN ...