- 浏览: 6830 次
- 性别:
- 来自: 北京
文章分类
最新评论
web.xml配置:
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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>s3h3</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name> <!-- 这里在配成spring,下边也要写一个名为spring-servlet.xml的文件,主要用来配置它的controller -->
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
spring-servlet,主要配置controller的信息
<?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:p="http://www.springframework.org/schema/p"
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/aop http://www.springframework.org/schema/aop/spring-aop-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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<!-- 把标记了@Controller注解的类转换为bean -->
<context:component-scan base-package="com.mvc.controller" />
<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/view/" p:suffix=".jsp" />
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="utf-8" />
</beans>
applicationContext.xml代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="com.mvc" /> <!-- 自动扫描所有注解该路径 -->
<context:property-placeholder location="classpath:/hibernate.properties" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${dataSource.dialect}</prop>
<prop key="hibernate.hbm2ddl.auto">${dataSource.hbm2ddl.auto}</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.mvc.entity</value><!-- 扫描实体类,也就是平时所说的model -->
</list>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${dataSource.driverClassName}" />
<property name="url" value="${dataSource.url}" />
<property name="username" value="${dataSource.username}" />
<property name="password" value="${dataSource.password}" />
</bean>
<!-- Dao的实现 -->
<bean id="entityDao" class="com.mvc.dao.EntityDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<tx:annotation-driven mode="aspectj"/>
<aop:aspectj-autoproxy/>
</beans>
hibernate.properties数据库连接配置
dataSource.password=123
dataSource.username=root
dataSource.databaseName=test
dataSource.driverClassName=com.mysql.jdbc.Driver
dataSource.dialect=org.hibernate.dialect.MySQL5Dialect
dataSource.serverName=localhost:3306
dataSource.url=jdbc:mysql://localhost:3306/test
dataSource.properties=user=${dataSource.username};databaseName=${dataSource.databaseName};serverName=${dataSource.serverName};password=${dataSource.password}
dataSource.hbm2ddl.auto=update
配置已经完成,下面开始例子
先在数据库建表,例子用的是mysql数据库
CREATE TABLE `test`.`student` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
`psw` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
)
建好表后,生成实体类
package com.mvc.entity;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "student")
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Integer id;
@Column(name = "name")
private String user;
@Column(name = "psw")
private String psw;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPsw() {
return psw;
}
public void setPsw(String psw) {
this.psw = psw;
}
}
Dao层实现
package com.mvc.dao;
import java.util.List;
public interface EntityDao {
public List<Object> createQuery(final String queryString);
public Object save(final Object model);
public void update(final Object model);
public void delete(final Object model);
}
package com.mvc.dao;
import java.util.List;
import org.hibernate.Query;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class EntityDaoImpl extends HibernateDaoSupport implements EntityDao{
public List<Object> createQuery(final String queryString) {
return (List<Object>) getHibernateTemplate().execute(
new HibernateCallback<Object>() {
public Object doInHibernate(org.hibernate.Session session)
throws org.hibernate.HibernateException {
Query query = session.createQuery(queryString);
List<Object> rows = query.list();
return rows;
}
});
}
public Object save(final Object model) {
return getHibernateTemplate().execute(
new HibernateCallback<Object>() {
public Object doInHibernate(org.hibernate.Session session)
throws org.hibernate.HibernateException {
session.save(model);
return null;
}
});
}
public void update(final Object model) {
getHibernateTemplate().execute(new HibernateCallback<Object>() {
public Object doInHibernate(org.hibernate.Session session)
throws org.hibernate.HibernateException {
session.update(model);
return null;
}
});
}
public void delete(final Object model) {
getHibernateTemplate().execute(new HibernateCallback<Object>() {
public Object doInHibernate(org.hibernate.Session session)
throws org.hibernate.HibernateException {
session.delete(model);
return null;
}
});
}
}
Dao在applicationContext.xml注入
<bean id="entityDao" class="com.mvc.dao.EntityDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Dao只有一个类的实现,直接供其它service层调用,如果你想更换为其它的Dao实现,也只需修改这里的配置就行了。
开始写view页面,WEB-INF/view下新建页面student.jsp,WEB-INF/view这路径是在spring-servlet.xml文件配置的,你可以配置成其它,也可以多个路径。student.jsp代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="/include/head.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>添加</title>
<script language="javascript" src="<%=request.getContextPath()%><!--
/script/jquery.min.js">
// --></script>
<style><!--
table{ border-collapse:collapse; }
td{ border:1px solid #f00; }
--></style><style mce_bogus="1">table{ border-collapse:collapse; }
td{ border:1px solid #f00; }</style>
<script type="text/javascript"><!--
function add(){
window.location.href="<%=request.getContextPath() %>/student.do?method=add";
}
function del(id){
$.ajax( {
type : "POST",
url : "<%=request.getContextPath()%>/student.do?method=del&id=" + id,
dataType: "json",
success : function(data) {
if(data.del == "true"){
alert("删除成功!");
$("#" + id).remove();
}
else{
alert("删除失败!");
}
},
error :function(){
alert("网络连接出错!");
}
});
}
// --></script>
</head>
<body>
<input id="add" type="button" onclick="add()" value="添加"/>
<table >
<tr>
<td>序号</td>
<td>姓名</td>
<td>密码</td>
<td>操作</td>
</tr>
<c:forEach items="${list}" var="student">
<tr id="<c:out value="${student.id}"/>">
<td><c:out value="${student.id}"/></td>
<td><c:out value="${student.user}"/></td>
<td><c:out value="${student.psw}"/></td>
<td>
<input type="button" value="编辑"/>
<input type="button" onclick="del('<c:out value="${student.id}"/>')" value="删除"/>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
student_add.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="/include/head.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>学生添加</title>
<mce:script type="text/javascript"><!--
function turnback(){
window.location.href="<%=request.getContextPath() %>/student.do";
}
// --></mce:script>
</head>
<body>
<form method="post" action="<%=request.getContextPath() %>/student.do?method=save">
<div><c:out value="${addstate}"></c:out></div>
<table>
<tr><td>姓名</td><td><input id="user" name="user" type="text" /></td></tr>
<tr><td>密码</td><td><input id="psw" name="psw" type="text" /></td></tr>
<tr><td colSpan="2" align="center"><input type="submit" value="提交"/><input type="button" onclick="turnback()" value="返回" /> </td></tr>
</table>
</form>
</body>
</html>
controller类实现,只需把注解写上,spring就会自动帮你找到相应的bean,相应的注解标记意义,不明白的,可以自己查下@Service,@Controller,@Entity等等的内容。
package com.mvc.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.mvc.entity.Student;
import com.mvc.service.StudentService;
@Controller
@RequestMapping("/student.do")
public class StudentController {
protected final transient Log log = LogFactory
.getLog(StudentController.class);
@Autowired
private StudentService studentService;
public StudentController(){
}
@RequestMapping
public String load(ModelMap modelMap){
List<Object> list = studentService.getStudentList();
modelMap.put("list", list);
return "student";
}
@RequestMapping(params = "method=add")
public String add(HttpServletRequest request, ModelMap modelMap) throws Exception{
return "student_add";
}
@RequestMapping(params = "method=save")
public String save(HttpServletRequest request, ModelMap modelMap){
String user = request.getParameter("user");
String psw = request.getParameter("psw");
Student st = new Student();
st.setUser(user);
st.setPsw(psw);
try{
studentService.save(st);
modelMap.put("addstate", "添加成功");
}
catch(Exception e){
log.error(e.getMessage());
modelMap.put("addstate", "添加失败");
}
return "student_add";
}
@RequestMapping(params = "method=del")
public void del(@RequestParam("id") String id, HttpServletResponse response){
try{
Student st = new Student();
st.setId(Integer.valueOf(id));
studentService.delete(st);
response.getWriter().print("{\"del\":\"true\"}");
}
catch(Exception e){
log.error(e.getMessage());
e.printStackTrace();
}
}
}
service类实现
package com.mvc.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.mvc.dao.EntityDao;
import com.mvc.entity.Student;
@Service
public class StudentService {
@Autowired
private EntityDao entityDao;
@Transactional
public List<Object> getStudentList(){
StringBuffer sff = new StringBuffer();
sff.append("select a from ").append(Student.class.getSimpleName()).append(" a ");
List<Object> list = entityDao.createQuery(sff.toString());
return list;
}
public void save(Student st){
entityDao.save(st);
}
public void delete(Object obj){
entityDao.delete(obj);
}
}
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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>s3h3</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name> <!-- 这里在配成spring,下边也要写一个名为spring-servlet.xml的文件,主要用来配置它的controller -->
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
spring-servlet,主要配置controller的信息
<?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:p="http://www.springframework.org/schema/p"
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/aop http://www.springframework.org/schema/aop/spring-aop-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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<!-- 把标记了@Controller注解的类转换为bean -->
<context:component-scan base-package="com.mvc.controller" />
<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/view/" p:suffix=".jsp" />
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="utf-8" />
</beans>
applicationContext.xml代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="com.mvc" /> <!-- 自动扫描所有注解该路径 -->
<context:property-placeholder location="classpath:/hibernate.properties" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${dataSource.dialect}</prop>
<prop key="hibernate.hbm2ddl.auto">${dataSource.hbm2ddl.auto}</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.mvc.entity</value><!-- 扫描实体类,也就是平时所说的model -->
</list>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${dataSource.driverClassName}" />
<property name="url" value="${dataSource.url}" />
<property name="username" value="${dataSource.username}" />
<property name="password" value="${dataSource.password}" />
</bean>
<!-- Dao的实现 -->
<bean id="entityDao" class="com.mvc.dao.EntityDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<tx:annotation-driven mode="aspectj"/>
<aop:aspectj-autoproxy/>
</beans>
hibernate.properties数据库连接配置
dataSource.password=123
dataSource.username=root
dataSource.databaseName=test
dataSource.driverClassName=com.mysql.jdbc.Driver
dataSource.dialect=org.hibernate.dialect.MySQL5Dialect
dataSource.serverName=localhost:3306
dataSource.url=jdbc:mysql://localhost:3306/test
dataSource.properties=user=${dataSource.username};databaseName=${dataSource.databaseName};serverName=${dataSource.serverName};password=${dataSource.password}
dataSource.hbm2ddl.auto=update
配置已经完成,下面开始例子
先在数据库建表,例子用的是mysql数据库
CREATE TABLE `test`.`student` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
`psw` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
)
建好表后,生成实体类
package com.mvc.entity;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "student")
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Integer id;
@Column(name = "name")
private String user;
@Column(name = "psw")
private String psw;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPsw() {
return psw;
}
public void setPsw(String psw) {
this.psw = psw;
}
}
Dao层实现
package com.mvc.dao;
import java.util.List;
public interface EntityDao {
public List<Object> createQuery(final String queryString);
public Object save(final Object model);
public void update(final Object model);
public void delete(final Object model);
}
package com.mvc.dao;
import java.util.List;
import org.hibernate.Query;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class EntityDaoImpl extends HibernateDaoSupport implements EntityDao{
public List<Object> createQuery(final String queryString) {
return (List<Object>) getHibernateTemplate().execute(
new HibernateCallback<Object>() {
public Object doInHibernate(org.hibernate.Session session)
throws org.hibernate.HibernateException {
Query query = session.createQuery(queryString);
List<Object> rows = query.list();
return rows;
}
});
}
public Object save(final Object model) {
return getHibernateTemplate().execute(
new HibernateCallback<Object>() {
public Object doInHibernate(org.hibernate.Session session)
throws org.hibernate.HibernateException {
session.save(model);
return null;
}
});
}
public void update(final Object model) {
getHibernateTemplate().execute(new HibernateCallback<Object>() {
public Object doInHibernate(org.hibernate.Session session)
throws org.hibernate.HibernateException {
session.update(model);
return null;
}
});
}
public void delete(final Object model) {
getHibernateTemplate().execute(new HibernateCallback<Object>() {
public Object doInHibernate(org.hibernate.Session session)
throws org.hibernate.HibernateException {
session.delete(model);
return null;
}
});
}
}
Dao在applicationContext.xml注入
<bean id="entityDao" class="com.mvc.dao.EntityDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Dao只有一个类的实现,直接供其它service层调用,如果你想更换为其它的Dao实现,也只需修改这里的配置就行了。
开始写view页面,WEB-INF/view下新建页面student.jsp,WEB-INF/view这路径是在spring-servlet.xml文件配置的,你可以配置成其它,也可以多个路径。student.jsp代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="/include/head.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>添加</title>
<script language="javascript" src="<%=request.getContextPath()%><!--
/script/jquery.min.js">
// --></script>
<style><!--
table{ border-collapse:collapse; }
td{ border:1px solid #f00; }
--></style><style mce_bogus="1">table{ border-collapse:collapse; }
td{ border:1px solid #f00; }</style>
<script type="text/javascript"><!--
function add(){
window.location.href="<%=request.getContextPath() %>/student.do?method=add";
}
function del(id){
$.ajax( {
type : "POST",
url : "<%=request.getContextPath()%>/student.do?method=del&id=" + id,
dataType: "json",
success : function(data) {
if(data.del == "true"){
alert("删除成功!");
$("#" + id).remove();
}
else{
alert("删除失败!");
}
},
error :function(){
alert("网络连接出错!");
}
});
}
// --></script>
</head>
<body>
<input id="add" type="button" onclick="add()" value="添加"/>
<table >
<tr>
<td>序号</td>
<td>姓名</td>
<td>密码</td>
<td>操作</td>
</tr>
<c:forEach items="${list}" var="student">
<tr id="<c:out value="${student.id}"/>">
<td><c:out value="${student.id}"/></td>
<td><c:out value="${student.user}"/></td>
<td><c:out value="${student.psw}"/></td>
<td>
<input type="button" value="编辑"/>
<input type="button" onclick="del('<c:out value="${student.id}"/>')" value="删除"/>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
student_add.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="/include/head.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>学生添加</title>
<mce:script type="text/javascript"><!--
function turnback(){
window.location.href="<%=request.getContextPath() %>/student.do";
}
// --></mce:script>
</head>
<body>
<form method="post" action="<%=request.getContextPath() %>/student.do?method=save">
<div><c:out value="${addstate}"></c:out></div>
<table>
<tr><td>姓名</td><td><input id="user" name="user" type="text" /></td></tr>
<tr><td>密码</td><td><input id="psw" name="psw" type="text" /></td></tr>
<tr><td colSpan="2" align="center"><input type="submit" value="提交"/><input type="button" onclick="turnback()" value="返回" /> </td></tr>
</table>
</form>
</body>
</html>
controller类实现,只需把注解写上,spring就会自动帮你找到相应的bean,相应的注解标记意义,不明白的,可以自己查下@Service,@Controller,@Entity等等的内容。
package com.mvc.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.mvc.entity.Student;
import com.mvc.service.StudentService;
@Controller
@RequestMapping("/student.do")
public class StudentController {
protected final transient Log log = LogFactory
.getLog(StudentController.class);
@Autowired
private StudentService studentService;
public StudentController(){
}
@RequestMapping
public String load(ModelMap modelMap){
List<Object> list = studentService.getStudentList();
modelMap.put("list", list);
return "student";
}
@RequestMapping(params = "method=add")
public String add(HttpServletRequest request, ModelMap modelMap) throws Exception{
return "student_add";
}
@RequestMapping(params = "method=save")
public String save(HttpServletRequest request, ModelMap modelMap){
String user = request.getParameter("user");
String psw = request.getParameter("psw");
Student st = new Student();
st.setUser(user);
st.setPsw(psw);
try{
studentService.save(st);
modelMap.put("addstate", "添加成功");
}
catch(Exception e){
log.error(e.getMessage());
modelMap.put("addstate", "添加失败");
}
return "student_add";
}
@RequestMapping(params = "method=del")
public void del(@RequestParam("id") String id, HttpServletResponse response){
try{
Student st = new Student();
st.setId(Integer.valueOf(id));
studentService.delete(st);
response.getWriter().print("{\"del\":\"true\"}");
}
catch(Exception e){
log.error(e.getMessage());
e.printStackTrace();
}
}
}
service类实现
package com.mvc.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.mvc.dao.EntityDao;
import com.mvc.entity.Student;
@Service
public class StudentService {
@Autowired
private EntityDao entityDao;
@Transactional
public List<Object> getStudentList(){
StringBuffer sff = new StringBuffer();
sff.append("select a from ").append(Student.class.getSimpleName()).append(" a ");
List<Object> list = entityDao.createQuery(sff.toString());
return list;
}
public void save(Student st){
entityDao.save(st);
}
public void delete(Object obj){
entityDao.delete(obj);
}
}
相关推荐
基于jpa+hibernate+spring+spring mvc注解方式项目案例带整体架构及一个页面操作小流程适合新手
关于Spring注解的配置,使用都有详细的注释说明 spring的MVC架构这里不是很明显,但LZ稍作添加即可!
作为架构师和Java开发者,深入理解Spring MVC的原理和实践应用是非常重要的。本文通过分析Spring MVC的核心组件和执行流程,提供了一个全面的学习指南。 Spring MVC基于Model-View-Controller(MVC)架构模式,优化...
spring mvc 架构的注解使用,非常值得一看
Spring MVC支持注解,可以简化开发。 作为Spring的一部分,能够使用Spring框架的IOC容器和Aop编程。 方便整合Struts、MyBatis、Hibernate、JPA等其他框架。 强化注解的使用,在控制器、Service、Dao都可以使用注解,...
描述了Spring mvc的基本配置以及开发常用注解、核心类。 该源码主要是以spring mvc编写的权限模板代码,仅供参考。
本系统采用struts+spring+hibernate架构,重在讲述三者结合在一起的应用开发,所有源程序都 有详细的注释,供入门者学生参考,未经作者允许不得用于商业用途,只能用于教学或个人学习。 程序只是整个系统中的...
适合初学者学习spring的mvc架构,理解spring3注解的开发
本文将详细介绍在Spring Boot框架中如何...Spring Cloud对Feign进行了封装,使其支持了Spring MVC标准注解和HttpMessageConverters。Feign可以与Eureka和Consul等服务发现组件配合使用,以实现动态服务路由和负载均衡。
基于Spring4框架的三层架构开发完成。 3. Mybatis版本为:3.2.8。 4. 使用了SpringMVC框架,Spring4的xml配置和注解配置。 5. 前台展示页面使用了JQuery EasyUI的布局、列表和消息组件。 6. 系统实现了较为完善...
无论是文件配置还是代码编写,可以说是很规范的了,对于想用sprimg注解模式大家框架的人员来说,该实例是个不错的选择,而且作者还会定期更新一些新的功能和架构方面的知识,里面还是说明文档,可见是非常用心了
NULL 博文链接:https://hankaibo.iteye.com/blog/1396350
基于注解的SpringMVC的电子商务网站架构,只是架构雏形,没有全部业务
使用 Spring 可插入的 MVC 架构,从而在使用 Spring 进行 WEB 开发时,可以选择使用 Spring的 Spring MVC 框架或集成其他 MVC 开发框架,如 Struts1(现在一般不用),Struts2 等。SpringMVC 已经成为目前最主流的 MVC...
本博客系统是利用Spring + Spring MVC + Mybatis构建的,Apache的Shrio作为安全框架实现安全认证,前端使用来自Twitter的Bootstrap架构进行页面构建,编写博文和解析博文用的是Bootstrap_Markdown,数据库用mysql,...
一个全面使用JDK1.8语法的J2EE示例,附带模拟数据库操作和基于注解的Bean注入管理。供J2EE开发新手学习。无需spring,掌握SpringMvc主要的开发思路。
使用 Spring 可插入的 MVC架构,从而在使用Spring进行WEB开发时,可以选择使用Spring的SpringMVC框架或集成其他MVC开发框架,如Struts1,Struts2等。 1、第一种方式是spring2时代的产物,也就是每个json视图...
大厂Spring面试题归纳整理: 概述,依赖注入,Spring Beans,Spring注解,Spring数据访问,Spring面向切面编程(AOP),Spring 的MVC...
300M资源,微服务架构面试专题系列(MySQL,JVM,并发编程,RabbitMQ消息中间件,Spring)。 囊括的知识点非常多 ...springMVC的原理 Spring MVC工作原理 及注解说明 SpringMVC框架介绍 SpringMVC原理
作为用户在Spring MVC测试中使用注释运行 108 12.2.4测试HTTP基本认证 109 12.3 SecurityMockMvcRequestBuilders 109 12.3.1测试基于表单的认证 109 12.3.2测试注销 110 12.4 SecurityMockMvcResultMatchers 110 ...