一、定义页面及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. BZOJ 1248--游乐园(DFS&贪心)

    1248: 游乐园Pleasure Ground Time Limit: 10 Sec  Memory Limit: 128 MBSec  Special JudgeSubmit: 6  Solved ...

  2. 设置跨交换机VLAN

    4台计算机,pc1 pc2 连接到交换机1的f1/1和f1/2.Pc3 pc4 连接到交换机2的f1/1和f1/2.pc1设置ip地址192.168.1.10,pc2 pc3 pc4设置ip地址192 ...

  3. jvm字节码简介

    1.概述 java虚拟机的指令由一个字节长度的.代表着某种特定操作含义的数字(成为操作码,Opcde)和跟随其后的0到多个此操作所需参数(操作数,Operands).由于操作码的长度为一个字节,所以指 ...

  4. java爬虫中jsoup的使用

    jsoup可以用来解析HTML的内容,其功能非常强大,它可以向javascript那样直接从网页中提取有用的信息 例如1: 从html字符串中解析数据 //直接从字符串中获取 public stati ...

  5. Springboot接口简单实现生成MySQL插入语句

    Springboot接口简单实现调用接口生成MySQL插入语句 在实际测试中,有这样一个需求场景,比如:在性能压力测试中,可能需要我们事先插入数据库中一些相关联的数据. 我们在实际测试中,遇到问题,需 ...

  6. 钉钉机器人集成Jenkins推送消息模板自定义发送报告

    一.由于公司同样也使用了钉钉.那么在做Jenkins集成自动化部署的时候,也是可以集成钉钉的. 那种Jenkins下载钉钉插件集成,简单设置就可以完成了.我们今天要做的是,定制化的发送消息. 钉钉推送 ...

  7. jquery text html width heigth的用法

    <body> <div id="div1"> <h3>我是标题</h3> </div> <div id=" ...

  8. 教你制作自己logo专属的图片

    说明:以下教程仅适合对图片分辨率要求不高的情况. 第一步:使用Windows自带的画图工具新建一个250像素*250像素的空白图片. 第二步:使用形状中的三角形,按住Shift键,将三角形拖拉至合适的 ...

  9. slatstack高效运维

    一.简介 saltstack是由thomas Hatch于2011年创建的一个开源项目,设计初衷是为了实现一个快速的远程执行系统. 二.诞生的背景 系统管理员日常会进行大量的重复性操作,例如安装软件, ...

  10. DB2 Package Issues and Solution

    Client 从 10.1 升级到11.1之后,而server端的DB 是10.1 版本,当客户执行sql语句时候报错: select * from ebcc.eol_item_info where ...