spring mvc+ibatis+freemarker+postgres框架实现一个简单的登陆功能
IDE工具为Eclipse
系统代码结构为:
[img]http://dl2.iteye.com/upload/attachment/0086/2184/ce04322b-39b9-3a80-9790-d7780bac6b16.jpg[/img]
LoginController.java代码如下:
UserController.java代码如下:
UserDao.java代码如下:
User.java代码如下:
User.xml文件内容如下:
ibatis.xml配置文件内容如下:
GlobalInterceptor.java代码如下:
LoginCommand.java代码如下:
UserService.java代码如下:
Test.java代码如下:
applicationContext.xml配置文件内容如下:
log4j.properties文件的内容如下:
login.ftl代码如下:
main.ftl代码如下:
updateAddressForm.ftl代码如下:
springmvc-servlet.xml配置文件内容如下:
web.xml内容如下:
数据库表springmvc.pg_userInfo:
[img]http://dl2.iteye.com/upload/attachment/0086/2192/33895531-c9bc-35ed-8fb3-a56d4ffba6a0.jpg[/img]
运行结果:
[img]http://dl2.iteye.com/upload/attachment/0086/2190/61698a13-bf17-32e7-9310-2084cb7ae768.jpg[/img]
IDE工具为Eclipse
系统代码结构为:
[img]http://dl2.iteye.com/upload/attachment/0086/2184/ce04322b-39b9-3a80-9790-d7780bac6b16.jpg[/img]
LoginController.java代码如下:
package com.springmvc.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.springmvc.domain.User;
import com.springmvc.pojo.LoginCommand;
import com.springmvc.service.UserService;
@Controller
public class LoginController {
@Autowired
private UserService userService;
@RequestMapping("/add")
public ModelAndView loginCheck(HttpServletRequest request,@Valid LoginCommand loginCommand,BindingResult result){
String username = loginCommand.getUsername();
String password = loginCommand.getPassword();
if(result.hasErrors()){
return new ModelAndView("login");
}
boolean bool = userService.isLoginSuccess(username, password);
ModelAndView mav = new ModelAndView();
if(bool){
User user = userService.getUserByName(username);
HttpSession session = request.getSession();
session.setAttribute("userInfo", user);
mav.setViewName("main");
mav.addObject("user", user);
return mav;
}else{
mav.setViewName("login");
return mav;
}
}
@RequestMapping("/")
public String loginPage(){
return "login";
}
}
UserController.java代码如下:
package com.springmvc.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.springmvc.domain.User;
import com.springmvc.service.UserService;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value="/formAddress",method=RequestMethod.GET)
public ModelAndView formAddress(HttpServletRequest request){
ModelAndView mav = new ModelAndView();
mav.setViewName("updateAddressForm");
HttpSession session = request.getSession();
User user = (User)session.getAttribute("userInfo");
mav.addObject("user",user);
return mav;
}
@RequestMapping(value="/updateAddress",method=RequestMethod.POST)
public ModelAndView updateAddress(HttpServletRequest request,@RequestParam("newAddress")String newAddress){
HttpSession session = request.getSession();
User user = (User)session.getAttribute("userInfo");
user.setAddress(newAddress);
userService.updateUser(user);
System.out.println(user.getAddress());
ModelAndView mav = new ModelAndView();
mav.setViewName("main");
mav.addObject("user", user);
return mav;
}
}
UserDao.java代码如下:
package com.springmvc.dao;
import java.util.List;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.springmvc.domain.User;
@Repository
public class UserDao {
@Autowired
private SqlSessionTemplate sessionTemplate;
public List<User> getMatchUsers(String username){
return sessionTemplate.selectList("UserDaoMapping.getMatchUser", username);
}
public void update(User user){
sessionTemplate.update("UserDaoMapping.updateUser", user);
}
}
User.java代码如下:
package com.springmvc.domain;
public class User {
//用户id
private Integer id;
//用户名
private String username;
//登录密码
private String password;
//用户地址
private String address;
public User(){
}
/**
* 由于ibatis配置文件的需要,所以写了这个构造函数
* @param id
* @param username
* @param password
* @param address
*/
public User(Integer id,String username,String password,String address){
this.id = id;
this.username = username;
this.password = password;
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
User.xml文件内容如下:
<?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="UserDaoMapping">
<resultMap type="User" id="user">
<constructor>
<idArg column="id" javaType="int" />
<arg column="username" javaType="string" />
<arg column="password" javaType="string" />
<arg column="address" javaType="string" />
</constructor>
</resultMap>
<select id="selectUser" parameterType="int" resultType="User">
select * from pg_userInfo where id=#{id}
</select>
<update id="updateUser" parameterType="User">
update pg_userInfo
set
username = #{username},
password = #{password},
address = #{address}
where id= #{id};
</update>
<select id="getMatchUser" parameterType="string" resultMap="user">
select * from pg_userInfo where username=#{username}
</select>
</mapper>
ibatis.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>
<settings>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="multipleResultSetsEnabled" value="true"/>
<setting name="useColumnLabel" value="true"/>
<setting name="useGeneratedKeys" value="true"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="defaultStatementTimeout" value="25000"/>
</settings>
<typeAliases>
<typeAlias type="com.springmvc.domain.User"
alias="User" />
</typeAliases>
<mappers>
<mapper resource="com/springmvc/domain/User.xml"/>
</mappers>
</configuration>
GlobalInterceptor.java代码如下:
package com.springmvc.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class GlobalInterceptor implements HandlerInterceptor{
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object obj, Exception e)
throws Exception {
System.out.println("after handle");
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object obj, ModelAndView mav) throws Exception {
System.out.println("post handle");
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object obj) throws Exception {
System.out.println("before handle");
return true;
}
}
LoginCommand.java代码如下:
package com.springmvc.po;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
public class LoginCommand {
@NotNull(message="username is null")
private String username;
@NotNull(message="password is null")
private String password;
@Min(value=34)
private int num;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
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;
}
}
UserService.java代码如下:
package com.springmvc.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.springmvc.dao.UserDao;
import com.springmvc.domain.User;
@Service
public class UserService {
@Autowired
private UserDao userDao;
public boolean isLoginSuccess(String username,String password){
List<User> listUser = userDao.getMatchUsers(username);
if(listUser.size()==1&&listUser.get(0).getPassword().equals(password)){
return true;
}else{
return false;
}
}
public User getUserByName(String username){
List<User> listUser = userDao.getMatchUsers(username);
return listUser.get(0);
}
public void updateUser(User user){
userDao.update(user);
}
}
Test.java代码如下:
package com.springmvc.test;
import static org.junit.Assert.*;
import java.util.List;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.springmvc.dao.UserDao;
import com.springmvc.domain.User;
import com.springmvc.service.UserService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/applicationContext.xml"})
public class Test {
@Autowired
private UserService userService;
@Autowired
private UserDao userDao;
@org.junit.Test
public void testUserDao(){
List<User> userList = userDao.getMatchUsers("yangjianzhou");
//assertEquals(userList.get(0).getAddress(),"shanghai-songjiang");
User user = userList.get(0);
user.setAddress("hubei-xiaogan");
userDao.update(user);
userList = userDao.getMatchUsers("yangjianzhou");
user = userList.get(0);
assertEquals(user.getAddress(), "hubei-xiaogan");
}
}
applicationContext.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- 扫描类包,将标注Spring注解的类自动转化Bean,同时完成Bean的注入 -->
<context:component-scan base-package="com.springmvc.dao*"/>
<context:component-scan base-package="com.springmvc.service*"/>
<context:component-scan base-package="com.springmvc.controller*"/>
<!-- 配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close"
p:driverClassName="org.postgresql.Driver"
p:url="jdbc:postgresql://localhost:5432/springmvc"
p:username="postgres"
p:password="admin" />
<!-- 配置SqlSessionFactoryBean工厂产生SqlSession对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:com/springmvc/ibatis/ibatis.xml"/>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource" />
<bean class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg ref="sqlSessionFactory"/>
</bean>
<!-- 通过AOP配置提供事务增强,让service包下所有Bean的所有方法拥有事务 -->
<aop:config proxy-target-class="true">
<aop:pointcut id="serviceMethod"
expression=" execution(* com.springmvc.service..*(..))" />
<aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice" />
</aop:config>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" />
</tx:attributes>
</tx:advice>
</beans>
log4j.properties文件的内容如下:
log4j.rootLogger=DEBUG,A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d %5p [%t] (%F:%L) - %m%n
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.logger.com.ibatis=debug
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug
log4j.logger.java.sql.Connection=debug
log4j.logger.java.sql.Statement=debug
log4j.logger.java.sql.PreparedStatement=debug,stdout
login.ftl代码如下:
<html>
<body>
<div style="height:20px; text-align=center"></div>
<form action="${rc.contextPath}/add" method="post">
<table align="center">
<tr>
<td>username:</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>password:</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="submit">
</td>
</tr>
</table>
</form>
</body>
</html>
main.ftl代码如下:
<html>
<body>
<div style="height:100px; text-align=center">主页</div>
<div style="height:20px; text-align=center">恭喜,用户${user.username}登录成功!</div>
<div><a href="${rc.contextPath}/user/formAddress">修改地址!</div>
</body>
</html>
updateAddressForm.ftl代码如下:
<div> update address</div>
<form method="POST" action="${rc.contextPath}/user/updateAddress">
<p><br>old adress:</br>${user.address}
<p>Your new address:<br>
<input type="text" name="newAddress" size=60>
<p><input type="submit" value="Submit">
</form>
springmvc-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:mvc="http://www.springframework.org/schema/mvc"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.springmvc.controller" />
<mvc:interceptors>
<bean class="com.springmvc.interceptor.GlobalInterceptor" />
</mvc:interceptors>
<!-- freemarker 配置 -->
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/ftl/"/>
</bean>
<!-- FreeMarker视图解析 如返回userinfo。。在这里配置后缀名ftl和视图解析器。。 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.freemarker.FreeMarkerView" />
<property name="suffix" value=".ftl" />
<property name="contentType" value="text/html;charset=utf-8" />
<property name="exposeRequestAttributes" value="true" />
<property name="exposeSessionAttributes" value="true" />
<property name="exposeSpringMacroHelpers" value="true" />
<property name="requestContextAttribute" value="rc" />
</bean>
<!-- 配置两种视图资源,先查找在/WEB-INF/ftl/下查找.ftl的视图,然后在/WEB-INF/jsp/下面查找.jsp的视图 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
web.xml内容如下:
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>spring mvc</display-name>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<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>freemarker</servlet-name>
<servlet-class>freemarker.ext.servlet.FreemarkerServlet</servlet-class>
<init-param>
<param-name>TemplatePath</param-name>
<param-value>/</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>freemarker</servlet-name>
<url-pattern>*.ftl</url-pattern>
</servlet-mapping>
</web-app>
数据库表springmvc.pg_userInfo:
[img]http://dl2.iteye.com/upload/attachment/0086/2192/33895531-c9bc-35ed-8fb3-a56d4ffba6a0.jpg[/img]
运行结果:
[img]http://dl2.iteye.com/upload/attachment/0086/2190/61698a13-bf17-32e7-9310-2084cb7ae768.jpg[/img]