利用spring mvc写一个登陆论坛并增加积分的小项目
spring mvc的流程
当页面输入:http://localhost:8080/superManager/index.html
映射到控制层中的loginPage(),返回的是login,即指向login.jsp,在login.jsp登陆,表单提交,指向action="<c:url value="/loginCheck.html"/>",映射loginCheck(..),通过业务处理,返回new ModelAndView("main")指向main.jsp;或者new ModelAndView("login",“error”,“账号或者密码错误”);
注意几个注解
当配置了扫描的包之后,用@方式
@Repository 该类被注解成是一个DAO
@Service 住结成Service
@Controller 控制层
@Autowired成员属性,省去了再xml配置bean,且get set方法
@RequestMapping(value="/index.html") 映射前端页面
1、配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!--启动spring容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring*.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- spring mvc 映射 -->
<servlet>
<servlet-name>baobaotao</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>baobaotao</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
2、配置spring-config.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: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/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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd" >
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:jdbc.properties"/>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<!--驱动类-->
<property name="driverClass" value="${jdbc.driverClassName}"/>
<!--url连接串-->
<property name="jdbcUrl" value="${jdbc.url}"/>
<!--用户名-->
<property name="user" value="${jdbc.username}"/>
<!--密码-->
<property name="password" value="${jdbc.password}"/>
<!--proxool自动侦察各个连接状态的时间间隔(毫秒),侦察到空闲的连接就马上回收,超时的销毁 默认30秒-->
<!-- <property name="houseKeepingSleepTime" value="9000"/>-->
<property name="acquireIncrement" value="10"/>
<!--最大连接数(默认5个),超过了这个连接数,再有请求时,就排在队列中等候,最大的等待请求数由maximum-new-connections决定-->
<property name="initialPoolSize" value="10"></property>
<property name="maxPoolSize" value="100"/>
<!--最小连接数(默认2个)-->
<property name="minPoolSize" value="10"/>
<property name="maxIdleTime" value="300"></property>
<property name="idleConnectionTestPeriod" value="60"></property> <!-- 每60秒检查连接池中的空闲连接 -->
<property name="maxStatements" value="20"></property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 配置事务
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="dataSource"/>
<aop:config proxy-target-class="true">
<aop:pointcut id="serviceMethod" expression="execution(* com.baobaotao.service..*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod"/>
</aop:config>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
-->
<!--
第一个*表示匹配所有类型的返回值
第二个*表示匹配所有的类(前面的..表示impl包及其所有子包)
第三个*表示匹配类中所有的方法
最后括号中..表示匹配方法所有参数
-->
</beans>
3、配置spring注解文件baobaotao-servlet.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: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/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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- 扫描类包,应用spring注解配置 -->
<context:component-scan base-package="com.baobaotao.*"/>
<!-- 配置视图解析器 jiang ModelAndView 及字符串解析为具体的页面 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
---------------------------------------------------------------------------------------------------------分割线--------------------------------------------------------------------------------------------------
4、bean
/**
*
*/
package com.baobaotao.domain;
import java.io.Serializable;
import java.util.Date;
/**
* @author Administrator
*
*/
public class User implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
private int userId;
private String userName;
private String password;
private int credits;
private String lastIp;
private Date lastVisit;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getCredits() {
return credits;
}
public void setCredits(int credits) {
this.credits = credits;
}
public String getLastIp() {
return lastIp;
}
public void setLastIp(String lastIp) {
this.lastIp = lastIp;
}
public Date getLastVisit() {
return lastVisit;
}
public void setLastVisit(Date lastVisit) {
this.lastVisit = lastVisit;
}
}
/**
*
*/
package com.baobaotao.domain;
import java.io.Serializable;
import java.util.Date;
/**
* @author Administrator
*
*/
public class LoginLog implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
private int loginLogId;
private int userId;
private String ip;
private Date loginDate;
public int getLoginLogId() {
return loginLogId;
}
public void setLoginLogId(int loginLogId) {
this.loginLogId = loginLogId;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public Date getLoginDate() {
return loginDate;
}
public void setLoginDate(Date loginDate) {
this.loginDate = loginDate;
}
}
---------------------------------------------------------------------------------------------------------分割线--------------------------------------------------------------------------------------------------
5、配置DAO
/**
*
*/
package com.baobaotao.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;
import com.baobaotao.domain.User;
/**
* @author Administrator
*
*/
@Repository
public class UserDao
{
@Autowired
private JdbcTemplate jdbcTemplate;
public int getMatchCount(String userName,String password)
{
String sqlStr= "select count(*) from t_user where user_name = ? and password = ?";
return jdbcTemplate.queryForInt(sqlStr,new Object[]{userName,password});
}
public User findUserByName(final String userName)
{
String sql = "select user_id,user_name,credits from t_user where user_name = ?";
final User user = new User();
jdbcTemplate.query(sql, new Object[]{userName},new RowCallbackHandler() {
public void processRow(ResultSet rs) throws SQLException
{
user.setUserId(rs.getInt("user_id"));
user.setUserName(rs.getString("user_name"));
user.setCredits(rs.getInt("credits"));
}
});
return user;
}
public void updateLoginInfo(User user)
{
String sql = "update t_user set last_visit = ?,last_ip=?,credits=? where user_id=?";
jdbcTemplate.update(sql,new Object[]{user.getLastVisit(),user.getLastIp(),user.getCredits(),user.getUserId()});
}
}
/**
*
*/
package com.baobaotao.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.baobaotao.domain.LoginLog;
/**
* @author Administrator
*
*/
@Repository // 通过spring注解定义一个Dao
public class LoginLogDao
{
@Autowired //�Զ�ע��jdbctemplate
private JdbcTemplate jdbcTemplate;
public void insertLoginLog(LoginLog loginLog)
{
String sql ="insert into t_login_log(user_id,ip,login_datetime) values(?,?,?)";
Object[] args = {loginLog.getUserId(),loginLog.getIp(),loginLog.getLoginDate()};
jdbcTemplate.update(sql,args);
}
}
/**
*
*/
package com.baobaotao.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.baobaotao.domain.LoginLog;
/**
* @author Administrator
*
*/
@Repository // 通过spring注解定义一个Dao
public class LoginLogDao
{
@Autowired //�Զ�ע��jdbctemplate
private JdbcTemplate jdbcTemplate;
public void insertLoginLog(LoginLog loginLog)
{
String sql ="insert into t_login_log(user_id,ip,login_datetime) values(?,?,?)";
Object[] args = {loginLog.getUserId(),loginLog.getIp(),loginLog.getLoginDate()};
jdbcTemplate.update(sql,args);
}
}
---------------------------------------------------------------------------------------------------------分割线--------------------------------------------------------------------------------------------------
6、service
/**
*
*/
package com.baobaotao.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baobaotao.dao.LoginLogDao;
import com.baobaotao.dao.UserDao;
import com.baobaotao.domain.LoginLog;
import com.baobaotao.domain.User;
/**
* @author Administrator
*
*/
@Service
public class UserService
{
@Autowired
private UserDao userDao;
@Autowired
private LoginLogDao loginLogDao;
public boolean hasMatchUser(String userName,String password)
{
int matchCount = userDao.getMatchCount(userName, password);
return matchCount > 0;
}
public User findUserByUserName(String userName)
{
return userDao.findUserByName(userName);
}
public void loginSuccess(User user)
{
user.setCredits(5+user.getCredits());
LoginLog loginLog = new LoginLog();
loginLog.setUserId(user.getUserId());
loginLog.setIp(user.getLastIp());
loginLog.setLoginDate(user.getLastVisit());
userDao.updateLoginInfo(user);
loginLogDao.insertLoginLog(loginLog);
}
}
---------------------------------------------------------------------------------------------------------分割线--------------------------------------------------------------------------------------------------
7、控制层
/**
*
*/
package com.baobaotao.web;
/**
* @author Administrator
*
*/
public class LoginCommand
{
private String userName;
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
/**
*
*/
package com.baobaotao.web;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.baobaotao.domain.User;
import com.baobaotao.service.UserService;
/**
* @author Administrator
*
*/
@Controller //1、标志成为一个Controller
public class LoginController
{
@Autowired
private UserService userService ;
//2/负责处理/index.html的请求
@RequestMapping(value="/index.html")
public String loginPage()
{
return "login";
}
//负责处理/loginCheck.html的请求
@RequestMapping(value="/loginCheck.html")
public ModelAndView loginCheck(HttpServletRequest request,LoginCommand loginCommand)
{
boolean isValidUser = userService.hasMatchUser(loginCommand.getUserName(), loginCommand.getPassword());
if(!isValidUser)
{
return new ModelAndView("login","error","用户名或者密码错误");
}
else
{
User user = userService.findUserByUserName(loginCommand.getUserName());
user.setLastVisit(new Date());
user.setLastIp(request.getRemoteAddr());
userService.loginSuccess(user);
request.getSession().setAttribute("user", user);
return new ModelAndView("main");
}
}
}
---------------------------------------------------------------------------------------------------------分割线--------------------------------------------------------------------------------------------------
8、前端
login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>宝宝淘论坛登录</title>
</head>
<body>
<c:if test="${!empty error}">
<font color="red"><c:out value="${error}"/></font>
</c:if>
<form action="<c:url value="/loginCheck.html"/>" method="post">
用户:<input type="text" name="userName"></br>
密码:<input type="password" name="password">
<input type="submit" value=“登录">
<input type="reset" value=“重置">
</form>
</body>
</html>
main.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>宝宝淘论坛</title>
</head>
<body>
${user.userName} 欢迎进入宝宝淘论坛,您当前积分为${user.credits} ;
</body>
</html>