Using session in Servlet:
/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().write("Servlet HelloWorld!"); HttpSession session = request.getSession(false); if(session == null) { response.sendRedirect("ServletLogin"); return; }else { System.out.println(session.getId()); Integer totalAccess = (Integer) session.getAttribute("totalAccess"); // Get session attribute; if(totalAccess == null) { totalAccess = 0; } totalAccess += 1; session.setAttribute("totalAccess", totalAccess); // set attribute response.getWriter().write("TotalAccess: " + session.getAttribute("totalAccess")); }
Using session in JSP:
Jsp page directive:
<%@ page
[ language=”java” ]
[ extends=”package.class” ]
[ import=”{package.class | package.*}, …” ]
[ session=”true | false” ]
[ buffer=”none | 8kb | sizekb” ]
[ autoFlush=”true | false” ]
[ isThreadSafe=”true | false” ]
[ info=”text” ]
[ errorPage=”relativeURL” ]
[ contentType=”mimeType [ ;charset=characterSet ]” | “text/html ; charset=ISO-8859-1” ]
[ isErrorPage=”true | false” ]
%>
“session = true” by default. when access “session”, if session is not existing, will create one by default.
we can set:
<%-- Prevent the creation of a session –%>
<%@ page session="false">
to prevent the Creation of a Session in a JSP Page.
We didn’t mention about the thread safe of session, here is a post from IBM DW:
http://www.ibm.com/developerworks/library/j-jtp09238/index.html
response.sendRedirect(“ServletLogin”); // User not login, redirect to the login page.
“redirect sets the response status to 302, and the new url in a
Location
header, and sends the response to the browser. Then the browser, according to the http specification, makes another request to the new url”And you can forward to any URL.
request.getServletContext().getRequestDispatcher(“/s/HelloWorld”).forward(request, response);
forward happens entirely on the server. The servlet container just forwards the same request to the target url, without the browser knowing about that. Hence you can use the same request attributes and the same request parameters when handling the new url. And the browser won’t know the url has changed (because it has happened entirely on the server)
So we can get the parameters in the target method:
request.getParameter(“userName”) // HelloWorld…doPost()..
Ref: http://stackoverflow.com/questions/6068891/difference-between-jsp-forward-and-redirect
this picture is from: http://lukejin.iteye.com/blog/586091
Aspect-Oriented Programming (AOP) complements Object-Oriented Programming (OOP) by providing another way of thinking about program structure. The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. Aspects enable the modularization of concerns such as transaction management that cut across multiple types and objects. (Such concerns are often termed crosscutting concerns in AOP literature.)
Here is a simple example showing the AOP feature in Spring, like the definition of bean, we can use AOP by declaring or annotation. we have a method that can insert a new user into the database, and we want to trace a log by AOP:
/** * Insert new user using transactionTemplate. * @param user */ public void insertUserByTxTemplate(final User user) { session.save(user); }
First, we need to crate an Aspect class:
package com.liguoliang.spring.aop; import org.aspectj.lang.ProceedingJoinPoint; public class Logging { public void preLog() { System.out.println("PreLog..."); } public void postLog() { System.out.println("PostLog..."); } public void aroundLog(ProceedingJoinPoint joinPoint) { System.out.println("Around...Logging begin.."); try { joinPoint.proceed(); } catch (Throwable e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Around...Logging end..."); } }
and then, we need define the AOP in spring config file:
<bean id="logging" class="com.liguoliang.spring.aop.Logging"></bean>
<aop:config>
<aop:aspect ref="logging">
<aop:before pointcut="execution(* com.liguoliang.spring.UserHibernateDAO.insertUserByTxTemplate(..))" method="preLog" />
<aop:after pointcut="execution(* com.liguoliang.spring.UserHibernateDAO.insertUserByTxTemplate(..))" method="postLog" />
<aop:around pointcut="execution(* com.liguoliang.spring.UserHibernateDAO.insertUserByTxTemplate(..))" method="aroundLog" />
</aop:aspect>
</aop:config>
And here is the output:
PreLog...
Around...Logging begin..
Exception catched...rollback now...
PostLog...
Around...Logging end...
We can define the pointcut and advices in the aspect class:
package com.liguoliang.spring.aop; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; @Aspect public class LoggingAnnotation { @Pointcut("execution(* com.liguoliang.spring.UserHibernateDAO.insertUserByTxTemplate(..))") public void newUser() { } @Before("newUser()") public void preLog() { System.out.println("[Annotation] PreLog..."); } @After("newUser()") public void postLog() { System.out.println("[Annotation] PostLog..."); } @Around("newUser()") public void aroundLog(ProceedingJoinPoint joinPoint) { System.out.println("[Annotation] Around...Logging begin.."); try { joinPoint.proceed(); } catch (Throwable e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("[Annotation] Around...Logging end..."); } }
Because all configuration info is sorted in this class, so the spring config file is different:
<bean id="loggingAnnotation" class="com.liguoliang.spring.aop.LoggingAnnotation"></bean>
<aop:aspectj-autoproxy />
and here is the output:
[Annotation] PreLog...
[Annotation] Around...Logging begin..
Exception catched...rollback now...
[Annotation] PostLog...
[Annotation] Around...Logging end...
Spring doesn’t directly manage transactions, it comes with a selection of transaction managers, such as: DataSourceTransactionManager, HibernateTransactionManager, JpaTransactionManager etc,.
There are two way to manage transaction in Spring: based on programming or configuration. no matter which way we choose, we always need to define the beans needed:
Here we define a transactionManager using hibernateTransactionManager, and a transaction template:
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="globalRollbackOnParticipationFailure" value="false" />
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="txTemplate" class="org.springframework.transaction.support.TransactionTemplate">
<property name="transactionManager" ref="transactionManager"></property>
</bean>
‘sessionFactory’ bean configuration: http://liguoliang.com/2012/using-spring-jdbc-template/
And now, I’ll show you the the two transaction management ways:
@Autowired private TransactionTemplate txTemplate; /** * Insert new user using transactionTemplate. * @param user */ public void insertUserByTxTemplate(final User user) { txTemplate.execute(new TransactionCallback() { @Override public Void doInTransaction(TransactionStatus txStatus) { try { Session session = sessionFactory.getCurrentSession(); session.save(user); throw new RuntimeException("Exception throwed!"); } catch (Exception e) { txStatus.setRollbackOnly(); } return null; } }); }
Manage transaction using txTemplate.execute().
using annotation
/** * Insert new user using transaction manager. * @param user */ @Transactional(propagation=Propagation.REQUIRED, readOnly=false, rollbackFor=RuntimeException.class) public void insertUser(User user) { Session session = sessionFactory.getCurrentSession(); // SessionFactoryUtils.openSession(sessionFactory); user.setLogin_name(user.getName()); session.save(user); // throw new RuntimeException("RunTimeException for Transaction testing..."); }
If you are using STS(SpringSource tool suite) you can see there is an indicator:
Links:
Spring Transaction – automatic rollback of previous db updates when one db update failes
Spring’s @Transactional does not rollback on checked exceptions
Transaction strategies: Understanding transaction pitfalls
JDBCTemplate simplifies the use of JDBC and helps to avoid common errors. It executes core JDBC workflow, leaving application code to provide SQL and extract results.
http://static.springsource.org/spring/docs/2.0.x/api/org/springframework/jdbc/core/JdbcTemplate.html
Here are two methods, the 2nd one is using JDBCTemplate from Srping, you can see the code are more simple and clear:
/** * LoadUsers using JDBC. * @param dataSource * @return */ public ListloadUserJDBC(DataSource dataSource) { List users = new ArrayList (); Connection conn = null; try { conn = dataSource.getConnection(); PreparedStatement preparedStatement = conn.prepareStatement("SELECT ID, EMAIL, LOGIN_NAME, NAME FROM ACCT_USER"); ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { User user = new User(); users.add(user); user.setId(rs.getInt("id")); user.setName(rs.getString("name")); System.out.println(user); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { if(conn != null) { try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return users; } /** * Load users using Spring JDBCTemplate. * @param jdbcTemplate * @return */ public java.util.List doJDBCTempQuery(JdbcTemplate jdbcTemplate) { String queryUsers = "SELECT ID, EMAIL, LOGIN_NAME, NAME FROM ACCT_USER"; java.util.List users = jdbcTemplate.query(queryUsers, new ParameterizedRowMapper () { @Override public User mapRow(ResultSet rs, int arg1) throws SQLException { User user = new User(); user.setId(rs.getInt(1)); user.setName(rs.getString(4)); return user; } }); return users; }
And here is a example to define the template bean:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/mini-liguoliang.com" />
<property name="username" value="root" />
<property name="password" value="pw" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" >
<constructor-arg ref="dataSource"></constructor-arg>
</bean>
// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.