How to use model in MVC flow - java

I have a jsp file that provides the login screen, upon submitting the form the control has to go to a servlet. Now, how can i save the values in the form to a model(Bean classs) and get them use in the controller.?
I am not using any frameworks like struts, spring, etc.
I used the following code but getting the error
java.lang.NoClassDefFoundError: bean/LoginBean
My code is:
index.jsp:
<form name="signin" method="post" action="LoginServlet">
<table>
<tr><td><font>USERNAME</font></td><td><input type="text" name="signin_uname" /></td></tr>
<tr><td><font>PASSWORD</font></td><td><input type="password" name="signin_pwd" /></td></tr>
<tr><td><input type="reset" value="RESET" /></td><td><input type="submit" value="LOGIN" /></td></tr>
</table>
</form>
LoginServlet.java
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
HttpSession session=request.getSession();
System.out.println(session);
try {
LoginBean login=new LoginBean();
login.setSignin_pwd("raviteja");
login.setSignin_uname("raviteja");
System.out.println(login.getSignin_uname());
System.out.println(login.getSignin_pwd());
} finally {
}
response.sendRedirect("");
}
LoginBean.java
public class LoginBean implements Serializable {
String signin_uname,signin_pwd;
public LoginBean() {
}
public String getSignin_pwd() {
return signin_pwd;
}
public void setSignin_pwd(String signin_pwd) {
this.signin_pwd = signin_pwd;
}
public String getSignin_uname() {
return signin_uname;
}
public void setSignin_uname(String signin_uname) {
this.signin_uname = signin_uname;
}
}
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">
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>servlets.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

1 Add Spring libraries to your project and map DispatherServlet in web.xml to process /LoginServlet
2 Create bean (same names for form and bean fields):
public class LoginData {
private String signin_uname;
private String signin_pwd;
// Getters and setters
}
3 Create controller:
#Controller
public class LoginController {
#RequestMapping(value = "/LoginServlet", method = RequestMethod.POST)
public String postLoginData(#ModelAttribute LoginData loginData) {
// All data from form will be at your model attribute bean. It will also will
// be putted at request
String userName = logigData.getSignin_uname();
return "loginResult.jsp";
}
}

Your code should run properly. You've a problem with the classpath. JVM isn't able to find the class LoginBean at runtime.
By the way what you want to output to the console? If you want to print the entered data user then correct your code with the following:
LoginBean login = new LoginBean();
String username = request.getParameter("signin_uname");
String password = request.getParameter("signin_pwd");
login.setSignin_uname(username);
login.setSignin_pwd(password);
But error shouldn't be if you correctly have created a project with your code.

Related

Can't Post a message using Facebook's API, using MVC and Java

I was trying to use the facebook API to post a message to share a page I am making as a project to learn to use APIs.
And I'm running into the following problem.
I tried to post and I was redirected to facebook where I accepted a bunch of permisions and then I was redirected to the url "MyUrl/oauth2callback/Facebook?code=A very large code" and got a 404 Not Found error.
I'm not sure what the problem is and I have been trying to find it for the past 3 days, here is the resource I am using:
import org.restlet.resource.ClientResource;
public class FacebookPostResource {
private String uri = "https://graph.facebook.com/me/feed";
private String access_token = null;
public FacebookPostResource(String access_token) {
this.access_token = access_token;
}
public boolean publishPost(String message){
String normalizedMessage=message.replace(' ', '+');
ClientResource cr=new ClientResource(uri+"?access_token="+access_token);
cr.post("message="+normalizedMessage);
return true;
}
}
Here is the Controller:
public class FacebookPostController extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -6818025976353856770L;
private static final Logger log =
Logger.getLogger(FacebookPostController.class.getName());
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws
IOException,ServletException {
String accessToken=(String)req.getSession().getAttribute("Facebook-
token");
if(accessToken!=null && !"".equals(accessToken)){
FacebookPostResource fbResource=new
FacebookPostResource(accessToken);
fbResource.publishPost(req.getParameter("message"));
req.getRequestDispatcher("/").forward(req,resp);
}else{
log.info("Trying to acces to Facebook without an acces token,
redirecting to OAuth servlet");
req.getRequestDispatcher("/AuthController/Facebook").forward(req,resp);
}
}
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws
IOException,ServletException {
doGet(req,resp);
}
}
Here is My scope configuration:
{
"Facebook":{
"tokenUrl":"https://graph.facebook.com/v2.8/oauth/access_token",
"clientId":"MyID",
"clientSecret":"MySecret" ,
"authorizationFormUrl":"https://www.facebook.com/v2.8/dialog/oauth",
"scopes":["user_posts", "user_friends"]
}
}
Here is the JSP where I write the post:
<c:if test='${empty sessionScope["Facebook-token"]}'>
<c:redirect url = "/AuthController/Facebook"/>
</c:if>
<h1>Publicar Post en Facebook</h1>
<div class="container">
<p class="message"></p>
<form action="/facebookPostCreation" method="post">
Mensaje: <textarea name="message"></textarea>
<br>
<div class="bottom_links">
<button type="submit" class="button">Publicar en
Facebook</button>
<button type="button"
onClick="javascript:window.location.href='index.html'"
class="button">Cancel</button>
</div>
</form>
</div>
And finally here is my web.xml
...
<servlet>
<servlet-name>FacebookPostCreation</servlet-name>
<servlet-class>aiss.controller.FacebookPostController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FacebookPostCreation</servlet-name>
<url-pattern>/facebookPostCreation</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>FacebookAuthController</display-name>
<servlet-name>FacebookAuthController</servlet-name>
<servlet-class>aiss.controller.oauth.GenericAuthController</servlet-class>
<init-param>
<param-name>provider</param-name>
<param-value>Facebook</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>FacebookAuthController</servlet-name>
<url-pattern>/AuthController/Facebook</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>FacebookOAuth2Callback</display-name>
<servlet-name>FacebookOAuth2Callback</servlet-name>
<servlet-class>aiss.controller.oauth.OAuth2Callback</servlet-class>
<init-param>
<param-name>provider</param-name>
<param-value>Facebook</param-value>
</init-param>
<init-param>
<param-name>onSuccess</param-name>
<param-value>redirect:/facebookFriendsListing</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>FacebookOAuth2Callback</servlet-name>
<url-pattern>/OAuth2Callback/Facebook</url-pattern>
</servlet-mapping>
Try using my code
https://github.com/OswaldoRosalesA/FacebookAPIJava.git
Use Debuger.java to Test.
I use the Graph API
https://developers.facebook.com/docs/graph-api

Url changed in spring

I have a from and when the form is filled and submitted I wanted the request to be http://localhost:8080/restroo/admin/adminLog but it gives http://localhost:808/adminLogand getting 404 error. I don't know why I am having this problem and actually I was having problem in using two controllers in spring.
web.xml
<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>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
I have spring-servlet.xml
admin.jsp
<form method="post" action="/adminLog" modelAttribute="adminUser">
First Name: <input type = "text" name = "userName">
<br />
password <input type = "password" name = "password" />
<input type = "submit" value = "Submit" />
</form>
AdminPageController.java
#Controller
#RequestMapping("/admin/*")
public class AdminPageController {
#Autowired
AdminUser adminUser;
#Autowired
MenuItems menuItems;
#Autowired
MenuItemsDao menuItemsDao;
#Autowired
AdminLoginDao adminLoginDao;
#RequestMapping(value="", method=RequestMethod.GET)
public ModelAndView addMenuItems(#ModelAttribute MenuItems menuItems){
// if(menuItems != null){
// menuItemsDao.addItems(menuItems);
// }
return new ModelAndView("admin");
}
#RequestMapping(value="/adminLog", method=RequestMethod.POST)
public ModelAndView adminLogin(#ModelAttribute("adminUser") AdminUser ad){
List<AdminUser> adminUser = adminLoginDao.adminLogin();
int len = adminUser.size();
for(int i=1;i<=len;i++){
String userN = adminUser.get(i).getUserName();
String pass = adminUser.get(i).getPassword();
if(userN.equals(ad.getUserName()) && (pass.equals(ad.getPassword()))){
return new ModelAndView("adminLogin");
}
}
return new ModelAndView("admin");
}
}
You are using Internal Resource View Resolver It is not able fetch view Not In Web-INF Floader.
Find This http://www.baeldung.com/spring-mvc-view-resolver-tutorial.
You have to change servlet mapping by adding a prefix for the API of the whole app:
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/restroo</url-pattern>
</servlet-mapping>

how to disable direct access to pages from url for jsp pages

I have created a web application. Everything works fine.But, if the user is not logged in still they can have access to other jsp pages through url. I want to stop url access. I saw some example it shows the usage of filters. I'm new to filters I don't how to implement it. I'm using servlets, dao and jsp pages.
Please suggests me how to do it. I want to make one filter for all the jsp or servlets pages.
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">
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>com.eis.servlet.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.eis.servlet.LoginServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>DayWiseServlet</servlet-name>
<servlet-class>com.eis.servlet.DayWiseServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>com.eis.servlet.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>RetrieveServlet</servlet-name>
<servlet-class>com.eis.servlet.RetrieveServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RetrieveServlet</servlet-name>
<url-pattern>/RetrieveServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>TimeSheet</servlet-name>
<servlet-class>com.eis.servlet.TimeSheet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TimeSheet</servlet-name>
<url-pattern>/TimeSheet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>DayWiseServlet</servlet-name>
<url-pattern>/DayWiseServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/RegisterServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
loginservlet.java
public class LoginServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("Emp_id");
String p=request.getParameter("Pwd");
String Usertype=request.getParameter("usertype");
HttpSession session = request.getSession(false);
if(session!=null){
session.setAttribute("name", n);
session.setAttribute("usertype", Usertype);
}
if(LoginDao.validate(n,p)){
RequestDispatcher rd=request.getRequestDispatcher("/daywise.jsp");
rd.forward(request,response);
}
else{
out.print("<p style=\"color:red\">Sorry Employee ID or password error</p>");
RequestDispatcher rd=request.getRequestDispatcher("/index.jsp");
rd.include(request,response);
}
out.close();
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
myfilter:
public class MyFilter implements Filter{
#Override
public void init(FilterConfig config) throws ServletException {}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp = (HttpServletResponse)response;
if(null==((String) req.getSession().getAttribute("empid")) || ((String) req.getSession().getAttribute("empid")).equals("")){
chain.doFilter(req, resp);
} else {
resp.sendRedirect("/WebTimeSheet/index.jsp");
}
}
#Override
public void destroy() {}
}
Loginpage:
<form action="LoginServlet" method="post">
<fieldset style="width: 300px">
<legend> Login to App </legend>
<table>
<tr>
<td>User ID</td>
<td><input type="text" name="Emp_id" required="required" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="Pwd" required="required" /></td>
</tr>
<tr>
<td>User Type</td>
<td> <select name="usertype">
<option>Employee</option>
<option>Manager</option>
<option>Admin</option>
</select></td>
</tr>
<tr>
<td><input type="submit" value="Login" /></td>
</tr>
</table>
</fieldset>
</form>
</body>
<%#include file="/footer.jsp" %>
</html>
and all my jsp pages are in the web pages folder which is outside the Web-inf folder. Web-inf folder only got web.xml init
Header.jsp
<c:choose>
<c:when test="${usertype eq 'Employee'}">
<div class="nav">
<ul><li class="container"><img src="${pageContext.request.contextPath}/images/enabling.jpg" /></li>
<li class="current">DayWise TimeSheet</li>
<li>Weekly TimeSheet</li>
</ul>
</div>
</c:when>
<c:when test="${usertype eq 'Manager'}">
<div class="nav">
<ul><li class="container"><img src="${pageContext.request.contextPath}/images/enabling.jpg" /></li>
<li class="current">DayWise TimeSheet</li>
<li>Weekly TimeSheet</li>
<li>Add New Employeer</li>
<li>Retrieve TimeSheet</li>
</ul>
</div>
</c:when>
Firstly, JSPs should not be used to serve requests, they should be used to render views. Servlets should be used to serve requests, and then forward to a JSP.
Here's an example:
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
//do some stuff
//forward to JSP to show result
String nextJSP = "/WEB_INF/result.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request,response);
}
}
And in web.xml:
<servlet>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>your.package.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/someurl</url-pattern>
</servlet-mapping>
In this example, the servlet forwards to a JSP in the WEB-INF directory. By putting all your JSPs in the WEB-INF directory, it means that they cannot be requested directly.
Now you have a Servlet, you can set up a Servlet Filter:
public class MyFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
if (isLoggedIn) {
//if user is logged in, complete request
chain.doFilter(req, res);
} else {
//not logged in, go to login page
res.sendRedirect("/login");
}
}
And in web.xml:
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>your.package.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/secret/*</url-pattern>
</filter-mapping>
So that way any URL that fits the pattern /secret/* will be filtered so that login is required.
You need to use a servlet filter and match all the requests.
In that filter you need to check for authorization.
Here is the official docs with example
You can set an authentication cookie in the response header
Cookie someCookie = new Cookie("cookie_name","some_value" );
and, response.addCookie(someCookie)
then , inside your filter you can decide to call chain.doFilter(req, res) based on the cookie value.
you may control the cookie age by cookie.setMaxAge(); ie. set the max age to '0' on log out .

Jsp servlet - login page is not redirecting properly

I am trying to create a login service but my pages are not redirecting properly. I have following:
login.jsp
<form action="login" method="post">
User Name
<br>
<input type="text" name="userId"/>
<br><br>
Password
<br>
<input type="password" name="password"/>
<br><br>
<input type="submit"/>
</form>
LoginServlet.java
package org.sohail.javabrains;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userId, password;
userId=request.getParameter("userId");
password=request.getParameter("password");
LoginService loginService = new LoginService();
boolean result = loginService.authenticate(userId, password);
if (result) {
RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/success.jsp");
dispatcher.forward(request, response);
return;
}
else {
response.sendRedirect("login.jsp");
return;
}
}
}
LoginService.java - has a authenticate(userId, password) method which connects to database, verifies userId and pass and returns a boolean value.
web.xml
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>org.sohail.javabrains.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
from login.jsp page, doesn't matter what I put I get following error:
HTTP Status 404 - /LoginApp/login
It should redirect the page to success.jsp if authenticate() reutrns true.
I am pretty new to this so please feel free to provide any other suggestions.
Thank you Birgit Martinelle for following answer:
change your web.xml servlet mapping to
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
and remove the WEB-INF part from your redirect url:
RequestDispatcher dispatcher = request.getRequestDispatcher("success.jsp");
– Birgit Martinelle 50 mins ago

Spring Mvc Form Post HTTP Status 400 The request sent by the client was syntactically incorrect

I have been trying to add users to mysql database with form but i get:
HTTP Status 400 The request sent by the client was syntactically incorrect.
my codes
User.java
public class User {
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private int id;
private String name;
}
UserDAO.java
public class UserDAO {
public void insert(User u) throws SQLException, ClassNotFoundException {
Connection conn=Database.newDatabase().getConnection();
PreparedStatement ps=conn.prepareStatement("insert into user values (?)");
ps.setString(1,u.getName());
ps.execute();
ps.close();
conn.close();
}
public List<User> getUsers() throws SQLException, ClassNotFoundException {
List<User> list=new ArrayList<User>();
Connection conn=Database.newDatabase().getConnection();
PreparedStatement ps=conn.prepareStatement("select *from user");
ResultSet rs=ps.executeQuery();
while (rs.next()){
User u=new User();
u.setId(rs.getInt("id"));
u.setName(rs.getString("name"));
list.add(u);
}
rs.close();
ps.close();
conn.close();
return list;
}
}
UserController.java
package com.springapp.mvc.Controller;
import java.sql.SQLException;
import com.springapp.mvc.Model.User;
import com.springapp.mvc.Service.UserDAO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class UserController {
#RequestMapping(value = "user",method = RequestMethod.GET)
public ModelAndView getUser() throws ClassNotFoundException, SQLException {
UserDAO udao=new UserDAO();
ModelAndView mav=new ModelAndView();
mav.setViewName("userControl");
mav.addObject("userList",udao.getUsers());
return mav;
}
#RequestMapping(value = "save", method = RequestMethod.POST)
public String createUser(#ModelAttribute(value = "user") User u) throws SQLException, ClassNotFoundException {
UserDAO udao=new UserDAO();
udao.insert(u);
return "redirect:user.html" ;
}
}
userControl.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>User</title>
</head>
<body>
<h1>
Users
</h1>
<form:form action="save.html" method="post" commandName="user">
<input type="hidden" name="id">
<label for="name">User Name</label>
<input type="text" id="name" name="name"/>
<input type="submit" value="Submit"/>
</form:form>
<table border="1">
<c:forEach var="user" items="${userList}">
<tr>
<td>${user.name}</td><td>${user.id}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
web.xml
<web-app 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 Application</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<welcome-file-list>
<welcome-file>hello.jsp</welcome-file>
</welcome-file-list>
</web-app>
mvc-dispatcher-servlet.xml
<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">
<context:component-scan base-package="com.springapp.mvc.Controller,com.springapp.mvc.Service"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
I assume the problem is in your JSP at this line:
<input type="hidden" name="id">
Your id has no value, so there will be a NumberFormatException when trying to convert an empty string to an int.
#RequestMapping(value = "save", method = RequestMethod.POST)
I think "save.html" should be changed to just "save".
Change
<form:form action="save.html" method="post" commandName="user">
use:
<form:form action="save" method="post" commandName="user">
Because #RequestMapping value is url format.
Make changes at Controller:
#RequestMapping(value = "save", method = RequestMethod.POST)
public String createUser(#ModelAttribute(value = "user") User u) throws SQLException, ClassNotFoundException {
UserDAO udao=new UserDAO();
udao.insert(u);
return "redirect:user.html" ;
Return View Name only not an extension:
return "redirect:user" ;

Categories

Resources